@pecot/workflow-mcp 0.0.0-stage → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/.claude-plugin/plugin.json +8 -0
  2. package/LICENSE +21 -0
  3. package/README.md +126 -2
  4. package/bin/pecot-workflow-mcp.mjs +10 -0
  5. package/cli/dist/cli.d.ts +26 -0
  6. package/cli/dist/cli.js +222 -0
  7. package/cli/dist/commands/cell-table.d.ts +3 -0
  8. package/cli/dist/commands/cell-table.js +495 -0
  9. package/cli/dist/commands/command-binding.d.ts +26 -0
  10. package/cli/dist/commands/command-binding.js +266 -0
  11. package/cli/dist/commands/command-definition.d.ts +136 -0
  12. package/cli/dist/commands/command-definition.js +101 -0
  13. package/cli/dist/commands/command-help.d.ts +8 -0
  14. package/cli/dist/commands/command-help.js +173 -0
  15. package/cli/dist/commands/command-stop.d.ts +19 -0
  16. package/cli/dist/commands/command-stop.js +30 -0
  17. package/cli/dist/commands/dependabot.d.ts +3 -0
  18. package/cli/dist/commands/dependabot.js +165 -0
  19. package/cli/dist/commands/directory-option.d.ts +7 -0
  20. package/cli/dist/commands/directory-option.js +48 -0
  21. package/cli/dist/commands/failure.d.ts +13 -0
  22. package/cli/dist/commands/failure.js +33 -0
  23. package/cli/dist/commands/fuzzy.d.ts +7 -0
  24. package/cli/dist/commands/fuzzy.js +79 -0
  25. package/cli/dist/commands/github-client.d.ts +12 -0
  26. package/cli/dist/commands/github-client.js +23 -0
  27. package/cli/dist/commands/global-options.d.ts +25 -0
  28. package/cli/dist/commands/global-options.js +83 -0
  29. package/cli/dist/commands/help-layout.d.ts +40 -0
  30. package/cli/dist/commands/help-layout.js +117 -0
  31. package/cli/dist/commands/help.d.ts +8 -0
  32. package/cli/dist/commands/help.js +55 -0
  33. package/cli/dist/commands/input-schema.d.ts +14 -0
  34. package/cli/dist/commands/input-schema.js +56 -0
  35. package/cli/dist/commands/issue-board.d.ts +38 -0
  36. package/cli/dist/commands/issue-board.js +62 -0
  37. package/cli/dist/commands/issue-comment.d.ts +3 -0
  38. package/cli/dist/commands/issue-comment.js +196 -0
  39. package/cli/dist/commands/issue-create.d.ts +3 -0
  40. package/cli/dist/commands/issue-create.js +329 -0
  41. package/cli/dist/commands/issue-project.d.ts +3 -0
  42. package/cli/dist/commands/issue-project.js +176 -0
  43. package/cli/dist/commands/issue-quick.d.ts +3 -0
  44. package/cli/dist/commands/issue-quick.js +126 -0
  45. package/cli/dist/commands/issue-read.d.ts +3 -0
  46. package/cli/dist/commands/issue-read.js +80 -0
  47. package/cli/dist/commands/issue-shared.d.ts +159 -0
  48. package/cli/dist/commands/issue-shared.js +419 -0
  49. package/cli/dist/commands/issue.d.ts +4 -0
  50. package/cli/dist/commands/issue.js +15 -0
  51. package/cli/dist/commands/names.d.ts +9 -0
  52. package/cli/dist/commands/names.js +16 -0
  53. package/cli/dist/commands/output.d.ts +78 -0
  54. package/cli/dist/commands/output.js +187 -0
  55. package/cli/dist/commands/pr.d.ts +3 -0
  56. package/cli/dist/commands/pr.js +933 -0
  57. package/cli/dist/commands/project-info.d.ts +48 -0
  58. package/cli/dist/commands/project-info.js +181 -0
  59. package/cli/dist/commands/project-sync.d.ts +91 -0
  60. package/cli/dist/commands/project-sync.js +273 -0
  61. package/cli/dist/commands/project.d.ts +5 -0
  62. package/cli/dist/commands/project.js +677 -0
  63. package/cli/dist/commands/registry.d.ts +6 -0
  64. package/cli/dist/commands/registry.js +27 -0
  65. package/cli/dist/commands/release.d.ts +10 -0
  66. package/cli/dist/commands/release.js +414 -0
  67. package/cli/dist/commands/repository-display.d.ts +3 -0
  68. package/cli/dist/commands/repository-display.js +7 -0
  69. package/cli/dist/commands/repository-match.d.ts +14 -0
  70. package/cli/dist/commands/repository-match.js +33 -0
  71. package/cli/dist/commands/repository.d.ts +5 -0
  72. package/cli/dist/commands/repository.js +265 -0
  73. package/cli/dist/commands/rich-panel.d.ts +22 -0
  74. package/cli/dist/commands/rich-panel.js +295 -0
  75. package/cli/dist/commands/security.d.ts +3 -0
  76. package/cli/dist/commands/security.js +164 -0
  77. package/cli/dist/commands/session.d.ts +3 -0
  78. package/cli/dist/commands/session.js +161 -0
  79. package/cli/dist/commands/tracker-sync.d.ts +58 -0
  80. package/cli/dist/commands/tracker-sync.js +53 -0
  81. package/cli/dist/commands/usage-error.d.ts +47 -0
  82. package/cli/dist/commands/usage-error.js +72 -0
  83. package/cli/dist/commands/value-types.d.ts +46 -0
  84. package/cli/dist/commands/value-types.js +94 -0
  85. package/cli/dist/commands/work-target.d.ts +13 -0
  86. package/cli/dist/commands/work-target.js +41 -0
  87. package/cli/dist/commands/worktree.d.ts +3 -0
  88. package/cli/dist/commands/worktree.js +335 -0
  89. package/cli/dist/domain/api-error-detail.d.ts +10 -0
  90. package/cli/dist/domain/api-error-detail.js +25 -0
  91. package/cli/dist/domain/branch-name.d.ts +5 -0
  92. package/cli/dist/domain/branch-name.js +10 -0
  93. package/cli/dist/domain/changelog.d.ts +43 -0
  94. package/cli/dist/domain/changelog.js +107 -0
  95. package/cli/dist/domain/config.d.ts +215 -0
  96. package/cli/dist/domain/config.js +300 -0
  97. package/cli/dist/domain/dependabot-pull-requests.d.ts +82 -0
  98. package/cli/dist/domain/dependabot-pull-requests.js +338 -0
  99. package/cli/dist/domain/dependabot-source.d.ts +51 -0
  100. package/cli/dist/domain/dependabot-source.js +4 -0
  101. package/cli/dist/domain/dependabot.d.ts +47 -0
  102. package/cli/dist/domain/dependabot.js +88 -0
  103. package/cli/dist/domain/errors.d.ts +19 -0
  104. package/cli/dist/domain/errors.js +31 -0
  105. package/cli/dist/domain/field-options.d.ts +31 -0
  106. package/cli/dist/domain/field-options.js +44 -0
  107. package/cli/dist/domain/format.d.ts +47 -0
  108. package/cli/dist/domain/format.js +168 -0
  109. package/cli/dist/domain/frontmatter.d.ts +122 -0
  110. package/cli/dist/domain/frontmatter.js +264 -0
  111. package/cli/dist/domain/git-runner.d.ts +10 -0
  112. package/cli/dist/domain/git-runner.js +4 -0
  113. package/cli/dist/domain/git-url.d.ts +17 -0
  114. package/cli/dist/domain/git-url.js +30 -0
  115. package/cli/dist/domain/issue-kind.d.ts +16 -0
  116. package/cli/dist/domain/issue-kind.js +16 -0
  117. package/cli/dist/domain/issue-readout.d.ts +107 -0
  118. package/cli/dist/domain/issue-readout.js +4 -0
  119. package/cli/dist/domain/json-null.d.ts +2 -0
  120. package/cli/dist/domain/json-null.js +5 -0
  121. package/cli/dist/domain/json.d.ts +21 -0
  122. package/cli/dist/domain/json.js +47 -0
  123. package/cli/dist/domain/prerequisites.d.ts +32 -0
  124. package/cli/dist/domain/prerequisites.js +192 -0
  125. package/cli/dist/domain/pull-request.d.ts +134 -0
  126. package/cli/dist/domain/pull-request.js +232 -0
  127. package/cli/dist/domain/python-format.d.ts +105 -0
  128. package/cli/dist/domain/python-format.js +304 -0
  129. package/cli/dist/domain/readiness.d.ts +172 -0
  130. package/cli/dist/domain/readiness.js +280 -0
  131. package/cli/dist/domain/reference-parser.d.ts +49 -0
  132. package/cli/dist/domain/reference-parser.js +119 -0
  133. package/cli/dist/domain/release.d.ts +49 -0
  134. package/cli/dist/domain/release.js +72 -0
  135. package/cli/dist/domain/repository-policy.d.ts +32 -0
  136. package/cli/dist/domain/repository-policy.js +65 -0
  137. package/cli/dist/domain/repository-resolver.d.ts +57 -0
  138. package/cli/dist/domain/repository-resolver.js +119 -0
  139. package/cli/dist/domain/sections.d.ts +69 -0
  140. package/cli/dist/domain/sections.js +514 -0
  141. package/cli/dist/domain/security-alerts-source.d.ts +29 -0
  142. package/cli/dist/domain/security-alerts-source.js +4 -0
  143. package/cli/dist/domain/security-alerts.d.ts +52 -0
  144. package/cli/dist/domain/security-alerts.js +107 -0
  145. package/cli/dist/domain/security-tracker.d.ts +115 -0
  146. package/cli/dist/domain/security-tracker.js +353 -0
  147. package/cli/dist/domain/state.d.ts +29 -0
  148. package/cli/dist/domain/state.js +56 -0
  149. package/cli/dist/domain/tracker-body.d.ts +70 -0
  150. package/cli/dist/domain/tracker-body.js +65 -0
  151. package/cli/dist/domain/yaml-document.d.ts +5 -0
  152. package/cli/dist/domain/yaml-document.js +206 -0
  153. package/cli/dist/infra/authored-notes.d.ts +37 -0
  154. package/cli/dist/infra/authored-notes.js +66 -0
  155. package/cli/dist/infra/changelog-file.d.ts +19 -0
  156. package/cli/dist/infra/changelog-file.js +43 -0
  157. package/cli/dist/infra/child-stdin.d.ts +4 -0
  158. package/cli/dist/infra/child-stdin.js +8 -0
  159. package/cli/dist/infra/config-store.d.ts +49 -0
  160. package/cli/dist/infra/config-store.js +121 -0
  161. package/cli/dist/infra/diagnostics.d.ts +9 -0
  162. package/cli/dist/infra/diagnostics.js +2 -0
  163. package/cli/dist/infra/file-kind.d.ts +9 -0
  164. package/cli/dist/infra/file-kind.js +26 -0
  165. package/cli/dist/infra/frontmatter-file.d.ts +14 -0
  166. package/cli/dist/infra/frontmatter-file.js +30 -0
  167. package/cli/dist/infra/git.d.ts +74 -0
  168. package/cli/dist/infra/git.js +133 -0
  169. package/cli/dist/infra/github/auth.d.ts +60 -0
  170. package/cli/dist/infra/github/auth.js +158 -0
  171. package/cli/dist/infra/github/client.d.ts +173 -0
  172. package/cli/dist/infra/github/client.js +576 -0
  173. package/cli/dist/infra/github/dependabot-source.d.ts +13 -0
  174. package/cli/dist/infra/github/dependabot-source.js +33 -0
  175. package/cli/dist/infra/github/errors.d.ts +47 -0
  176. package/cli/dist/infra/github/errors.js +42 -0
  177. package/cli/dist/infra/github/index.d.ts +13 -0
  178. package/cli/dist/infra/github/index.js +19 -0
  179. package/cli/dist/infra/github/issues.d.ts +129 -0
  180. package/cli/dist/infra/github/issues.js +273 -0
  181. package/cli/dist/infra/github/payload.d.ts +44 -0
  182. package/cli/dist/infra/github/payload.js +80 -0
  183. package/cli/dist/infra/github/projects.d.ts +108 -0
  184. package/cli/dist/infra/github/projects.js +303 -0
  185. package/cli/dist/infra/github/pulls.d.ts +80 -0
  186. package/cli/dist/infra/github/pulls.js +161 -0
  187. package/cli/dist/infra/github/queries.d.ts +36 -0
  188. package/cli/dist/infra/github/queries.js +883 -0
  189. package/cli/dist/infra/github/readout.d.ts +18 -0
  190. package/cli/dist/infra/github/readout.js +156 -0
  191. package/cli/dist/infra/github/repos.d.ts +68 -0
  192. package/cli/dist/infra/github/repos.js +137 -0
  193. package/cli/dist/infra/github/rest-path.d.ts +14 -0
  194. package/cli/dist/infra/github/rest-path.js +31 -0
  195. package/cli/dist/infra/github/security-alerts-source.d.ts +15 -0
  196. package/cli/dist/infra/github/security-alerts-source.js +73 -0
  197. package/cli/dist/infra/gitignore-spec.d.ts +36 -0
  198. package/cli/dist/infra/gitignore-spec.js +235 -0
  199. package/cli/dist/infra/nx-scope.d.ts +51 -0
  200. package/cli/dist/infra/nx-scope.js +182 -0
  201. package/cli/dist/infra/os-error.d.ts +24 -0
  202. package/cli/dist/infra/os-error.js +38 -0
  203. package/cli/dist/infra/paths.d.ts +88 -0
  204. package/cli/dist/infra/paths.js +234 -0
  205. package/cli/dist/infra/state-store.d.ts +45 -0
  206. package/cli/dist/infra/state-store.js +118 -0
  207. package/cli/dist/infra/template-store.d.ts +15 -0
  208. package/cli/dist/infra/template-store.js +34 -0
  209. package/cli/dist/infra/text-file.d.ts +12 -0
  210. package/cli/dist/infra/text-file.js +33 -0
  211. package/cli/dist/infra/worktree-copy.d.ts +24 -0
  212. package/cli/dist/infra/worktree-copy.js +95 -0
  213. package/cli/dist/infra/worktree-links.d.ts +139 -0
  214. package/cli/dist/infra/worktree-links.js +433 -0
  215. package/cli/dist/infra/worktree-setup.d.ts +21 -0
  216. package/cli/dist/infra/worktree-setup.js +41 -0
  217. package/cli/dist/infra/worktree.d.ts +174 -0
  218. package/cli/dist/infra/worktree.js +567 -0
  219. package/cli/dist/mcp/result.d.ts +33 -0
  220. package/cli/dist/mcp/result.js +52 -0
  221. package/cli/dist/mcp/serve.d.ts +51 -0
  222. package/cli/dist/mcp/serve.js +183 -0
  223. package/cli/dist/mcp/server.d.ts +21 -0
  224. package/cli/dist/mcp/server.js +128 -0
  225. package/cli/dist/mcp/session-directory.d.ts +26 -0
  226. package/cli/dist/mcp/session-directory.js +84 -0
  227. package/cli/dist/package.json +1 -0
  228. package/cli/dist/version.d.ts +17 -0
  229. package/cli/dist/version.js +42 -0
  230. package/cli/templates/comment/merge-diff.md +34 -0
  231. package/cli/templates/comment/plan.md +181 -0
  232. package/cli/templates/comment/precede-notify.md +33 -0
  233. package/cli/templates/comment/review-findings.md +42 -0
  234. package/cli/templates/comment/review-resolution.md +48 -0
  235. package/cli/templates/issue/bug.md +63 -0
  236. package/cli/templates/issue/epic.md +54 -0
  237. package/cli/templates/issue/task-implement.md +67 -0
  238. package/cli/templates/issue/task.md +48 -0
  239. package/cli/templates/issue/tracker.md +48 -0
  240. package/cli/templates/pr/create.md +123 -0
  241. package/cli/templates/pr/release.md +56 -0
  242. package/hooks/lib/core/pecot-gitignore-ensure.sh +48 -0
  243. package/npm-shrinkwrap.json +83 -0
  244. package/package.json +22 -4
@@ -0,0 +1,567 @@
1
+ /* eslint-disable security/detect-non-literal-fs-filename -- パスは呼び出し側が渡すリポジトリ・プロジェクトルート配下 */
2
+ // ワークツリー管理のコアロジック。ワークツリーの作成・削除を提供する。
3
+ //
4
+ // 全ての関数は cwd 引数で対象リポジトリを指定する。
5
+ // pecot CLI は pecot リポジトリ内で実行されるが、worktree コマンドは別のリポジトリを対象にするため、cwd 引数が必須。
6
+ // 失敗は WorktreeRuntimeError(Python の RuntimeError に当たる)で伝える。
7
+ //
8
+ // 設定ファイル(worktree-config.json・.worktreeignore)の読み書きと symlink 作成は worktree-links.ts にある。
9
+ // ファイルのコピーは worktree-copy.ts、setup_command の実行は worktree-setup.ts にある。
10
+ // このファイルがそれらを読む。逆向きの import は作らない(findWorktreeConfigFile と findMainWorktree をここに置くのはそのため)。
11
+ import { BaseError } from '../domain/errors.js';
12
+ import { existsSync, readdirSync, readFileSync, rmdirSync, writeFileSync } from 'node:fs';
13
+ import path from 'node:path';
14
+ import { findRepository, getDevelopBranch } from '../domain/config.js';
15
+ import { pythonStrip, ValidationFailure } from '../domain/python-format.js';
16
+ import { createRepositoryReference } from '../domain/repository-resolver.js';
17
+ import { loadActiveConfig } from './config-store.js';
18
+ import { isDirectory } from './file-kind.js';
19
+ import { GitCommandError, gitToplevel, listRemotes, preferredRemotes, remoteRepository, runGit } from './git.js';
20
+ import { toOsError } from './os-error.js';
21
+ import { normalizePath, resolveRealPath, WORKTREE_CONFIG_FILENAME } from './paths.js';
22
+ import { createSymlinks, loadConfig, loadCopyExcludeSpec, WorktreeConfigError, } from './worktree-links.js';
23
+ import { copyFiles } from './worktree-copy.js';
24
+ import { runSetupCommand } from './worktree-setup.js';
25
+ /**
26
+ ワークツリー操作に失敗した(Python の RuntimeError に当たる)。メッセージは利用者に見せる文
27
+ */
28
+ export class WorktreeRuntimeError extends BaseError {
29
+ }
30
+ // 環境ガード
31
+ function isSet(value = '') {
32
+ return value !== '';
33
+ }
34
+ /**
35
+ pecot worktree 系コマンドが devcontainer 内で実行されていることを確認する。
36
+
37
+ devcontainer 外(host 直接)での実行はサポート外。プロジェクトの devcontainer が整えるマウント構造
38
+ (/workspaces/<project>/base/<repo>)に依存するため、外で動かしても動作は保証しない。
39
+
40
+ 検出方法(いずれかでヒットすれば通過)は次のとおり。
41
+ - `/.dockerenv` ファイルの存在。パスは dockerEnvironmentFile で差し替えられる。
42
+ - 環境変数 REMOTE_CONTAINERS・CODESPACES・DEVCONTAINER のいずれかが設定されている。
43
+
44
+ いずれも満たさなければ WorktreeRuntimeError
45
+ */
46
+ export function ensureDevcontainerEnvironment(dockerEnvironmentFile = '/.dockerenv') {
47
+ if (existsSync(dockerEnvironmentFile) || isSet(process.env['REMOTE_CONTAINERS']) || isSet(process.env['CODESPACES']) || isSet(process.env['DEVCONTAINER']))
48
+ return;
49
+ throw new WorktreeRuntimeError('this command must run inside a devcontainer\n'
50
+ + 'the current environment does not have the mount layout pecot expects '
51
+ + '(/workspaces/<project>/base/<repo>)\n'
52
+ + 'prepare .devcontainer/ in the project, run Reopen in Container in VS Code, and run it again');
53
+ }
54
+ // Git 操作関数
55
+ function outputLines(stdout) {
56
+ return pythonStrip(stdout).split('\n').filter(line => line !== '');
57
+ }
58
+ // `git worktree list --porcelain` を worktree ごとに分ける。パスの空白はそのまま残る
59
+ function parsePorcelain(stdout) {
60
+ const entries = [];
61
+ for (const line of outputLines(stdout)) {
62
+ if (line.startsWith('worktree '))
63
+ entries.push({ path: line.slice('worktree '.length), commit: '', branch: undefined });
64
+ const entry = entries.at(-1);
65
+ if (entry === undefined)
66
+ continue;
67
+ if (line.startsWith('HEAD '))
68
+ entry.commit = line.slice('HEAD '.length);
69
+ else if (line.startsWith('branch '))
70
+ entry.branch = line.slice('branch '.length).replace(/^refs\/heads\//u, '');
71
+ }
72
+ return entries;
73
+ }
74
+ /**
75
+ git worktree list --porcelain の結果を分ける。実行に失敗したら空
76
+ */
77
+ export function getWorktreeList(cwd) {
78
+ const result = runGit(['worktree', 'list', '--porcelain'], { cwd });
79
+ return result.exitCode === 0 ? parsePorcelain(result.stdout) : [];
80
+ }
81
+ /**
82
+ メインワークツリーのパスを取得する。git worktree list の最初のエントリがメイン WT。
83
+ 任意の WT 内から呼べる。一覧を取得できなければ WorktreeRuntimeError
84
+ */
85
+ export function findMainWorktree(cwd) {
86
+ const result = runGit(['worktree', 'list', '--porcelain'], { cwd });
87
+ const main = result.exitCode === 0 ? parsePorcelain(result.stdout)[0] : undefined;
88
+ if (main === undefined)
89
+ throw new WorktreeRuntimeError(`cannot get the worktree list: ${result.stderr}`);
90
+ return normalizePath(main.path);
91
+ }
92
+ /**
93
+ メインワークツリーの設定ファイルを探す。無ければ undefined
94
+ */
95
+ export function findWorktreeConfigFile(cwd = process.cwd()) {
96
+ let mainWorktree;
97
+ try {
98
+ mainWorktree = findMainWorktree(cwd);
99
+ }
100
+ catch (error) {
101
+ if (error instanceof WorktreeRuntimeError)
102
+ return undefined;
103
+ throw error;
104
+ }
105
+ const configPath = path.join(mainWorktree, WORKTREE_CONFIG_FILENAME);
106
+ return existsSync(configPath) ? configPath : undefined;
107
+ }
108
+ /**
109
+ サブワークツリー環境かどうかを判定する。git rev-parse --git-dir と --git-common-dir を比較し、
110
+ サブ WT では git-dir がメインの .git を指すため、両者が異なる。
111
+ Git リポジトリ外、または git コマンドの失敗なら WorktreeRuntimeError
112
+ */
113
+ export function isWorktreeEnvironment(cwd) {
114
+ let gitDirectory;
115
+ let commonDirectory;
116
+ try {
117
+ gitDirectory = runGit(['rev-parse', '--git-dir'], { cwd, check: true }).stdout;
118
+ commonDirectory = runGit(['rev-parse', '--git-common-dir'], { cwd, check: true }).stdout;
119
+ }
120
+ catch (error) {
121
+ if (error instanceof GitCommandError)
122
+ throw new WorktreeRuntimeError(`not a git repository: ${error.stderr.trim()}`, { cause: error });
123
+ throw error;
124
+ }
125
+ // 相対パスは、cwd ではなくこのプロセスの作業ディレクトリ基準で解決する(Python の Path.resolve() と同じ)
126
+ return resolveRealPath(pythonStrip(gitDirectory)) !== resolveRealPath(pythonStrip(commonDirectory));
127
+ }
128
+ /**
129
+ サブワークツリーのパス一覧を取得する。get_worktree_list の最初のエントリ(メイン WT)を除く。
130
+ 一覧を取得できなければ WorktreeRuntimeError
131
+ */
132
+ export function getWorktreeDirectories(cwd) {
133
+ const entries = getWorktreeList(cwd);
134
+ if (entries.length === 0)
135
+ throw new WorktreeRuntimeError('cannot get the worktree list');
136
+ return entries.slice(1).map(entry => normalizePath(entry.path));
137
+ }
138
+ // worktree add が wtN を書く記録。管理ディレクトリ(.git/worktrees/<id>/)の中に置く
139
+ const WORKTREE_NAME_RECORD = 'pecot-worktree-name';
140
+ // 記録のパス。git が解決した絶対パス(このプロセスの cwd に依らない)。取れなければ undefined
141
+ function worktreeNameRecordPath(cwd) {
142
+ const result = runGit(['rev-parse', '--path-format=absolute', '--git-path', WORKTREE_NAME_RECORD], { cwd });
143
+ const recordPath = pythonStrip(result.stdout);
144
+ return recordPath !== '' && result.exitCode === 0 ? recordPath : undefined;
145
+ }
146
+ function readRecord(file) {
147
+ try {
148
+ return pythonStrip(readFileSync(file, 'utf8'));
149
+ }
150
+ catch {
151
+ return '';
152
+ }
153
+ }
154
+ // 作った worktree に名前を記録する。失敗は warning にとどめる
155
+ function recordWorktreeName(worktreePath, name, diagnostics) {
156
+ const recordPath = worktreeNameRecordPath(worktreePath);
157
+ if (recordPath === undefined) {
158
+ diagnostics.warning(`failed to record the worktree name ${name}: cannot resolve the git path: ${worktreePath}`);
159
+ return;
160
+ }
161
+ try {
162
+ writeFileSync(recordPath, `${name}\n`);
163
+ }
164
+ catch (error) {
165
+ const converted = toOsError(error);
166
+ diagnostics.warning(`failed to record the worktree name ${name}: ${recordPath}: ${converted instanceof Error ? converted.message : String(converted)}`);
167
+ }
168
+ }
169
+ /**
170
+ 使用中の wtN の名前を返す。全 worktree の記録と、wtN のブランチを checkout している worktree の和
171
+ */
172
+ export function claimedSetNames(mainWorktree) {
173
+ const names = new Set();
174
+ const common = runGit(['rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd: mainWorktree });
175
+ const commonDirectory = pythonStrip(common.stdout);
176
+ if (commonDirectory !== '' && common.exitCode === 0) {
177
+ const administrative = path.join(commonDirectory, 'worktrees');
178
+ const entries = existsSync(administrative) ? readdirSync(administrative) : [];
179
+ for (const entry of entries) {
180
+ const recorded = readRecord(path.join(administrative, entry, WORKTREE_NAME_RECORD));
181
+ if (recorded !== '')
182
+ names.add(recorded);
183
+ }
184
+ }
185
+ const references = runGit(['for-each-ref', '--format=%(refname:short)%00%(worktreepath)', 'refs/heads/'], { cwd: mainWorktree });
186
+ if (references.exitCode === 0) {
187
+ for (const line of references.stdout.split('\n')) {
188
+ const [branch, worktreePath] = line.split('\0', 2);
189
+ if (branch !== undefined && worktreePath !== undefined && worktreePath !== '' && /^wt\d+$/u.test(branch))
190
+ names.add(branch);
191
+ }
192
+ }
193
+ return names;
194
+ }
195
+ /**
196
+ 現在のサブワークツリー名を取得する。
197
+ サブ WT でなければ undefined。記録(`pecot-worktree-name`)があればそれを返す。
198
+ 無ければ toplevel の親ディレクトリ名を、`wt\d+` か `base` のときだけ返し、それ以外は undefined。
199
+ Git リポジトリ外なら WorktreeRuntimeError
200
+ */
201
+ export function getCurrentWorktreeName(cwd) {
202
+ if (!isWorktreeEnvironment(cwd))
203
+ return undefined;
204
+ const recordPath = worktreeNameRecordPath(cwd);
205
+ const recorded = recordPath === undefined ? '' : readRecord(recordPath);
206
+ if (recorded !== '')
207
+ return recorded;
208
+ const toplevel = gitToplevel({ cwd });
209
+ const parent = toplevel === undefined ? undefined : path.basename(path.dirname(toplevel));
210
+ return parent !== undefined && /^(?:wt\d+|base)$/u.test(parent) ? parent : undefined;
211
+ }
212
+ /**
213
+ プロジェクトルートを検出する。呼び出し側リポジトリの main WT を正規化し、`<root>/base/<repo>` の形になっているか確認する。
214
+ `<root>` の絶対パスを返す。その形でなければ WorktreeRuntimeError
215
+ */
216
+ export function detectProjectRoot(cwd) {
217
+ const resolved = resolveRealPath(findMainWorktree(cwd));
218
+ const parent = path.dirname(resolved);
219
+ if (path.basename(parent) !== 'base') {
220
+ const expected = path.join(parent, 'base', path.basename(resolved));
221
+ throw new WorktreeRuntimeError('this repository is not placed in the layout pecot expects for a project\n'
222
+ + '\n'
223
+ + ` current: ${resolved}\n`
224
+ + ` expected: ${expected}\n`
225
+ + '\n'
226
+ + 'why base/ is needed:\n'
227
+ + ' the devcontainer mounts the parallel sets (wt1, wt2...) selectively, so base/ '
228
+ + 'separates the resident set from the parallel sets\n'
229
+ + '\n'
230
+ + 'migration steps (the cwd goes away, so close this CLI session first):\n'
231
+ + ' 1. close this CLI session\n'
232
+ + ' 2. in another terminal, run:\n'
233
+ + ` mkdir -p ${parent}/base\n`
234
+ + ` mv ${resolved} ${parent}/base/\n`
235
+ + ` 3. restart the CLI in ${parent}/base/${path.basename(resolved)}/`);
236
+ }
237
+ return path.dirname(parent);
238
+ }
239
+ // プロジェクトルート直下の `<prefix><数字>` ディレクトリの番号を昇順で返す
240
+ function existingSetNumbers(projectRoot, prefix) {
241
+ const entries = existsSync(projectRoot) ? readdirSync(projectRoot) : [];
242
+ return entries
243
+ .filter(entry => entry.startsWith(prefix) && /^\d+$/u.test(entry.slice(prefix.length)) && isDirectory(path.join(projectRoot, entry)))
244
+ .map(entry => Number(entry.slice(prefix.length)))
245
+ .toSorted((a, b) => a - b);
246
+ }
247
+ /**
248
+ プロジェクトルート基準で、対象リポの参加先セット名を決める(プロジェクトセット = 同じ wtN 配下の複数リポ WT)。
249
+
250
+ 1. `<projectRoot>/wt\d+/` と `options.claimed` の番号を列挙する。claimed の番号は参加せず、max にも数える。
251
+ 2. 各 wtN について `wtN/<repositoryDirectoryName>` が存在しないものを先頭から探す。見つかったら既存セットに参加させる形でその名前を返す。
252
+ 3. 全ての既存 wtN に該当リポが既にあるなら、max(N)+1 で新セット `wt<N+1>` を返す。
253
+ 4. 既存セットが無ければ `wt1` を返す。
254
+
255
+ 全セットに参加済みで maxNumber を超えるなら WorktreeRuntimeError
256
+ */
257
+ export function getNextSetName(projectRoot, repositoryDirectoryName, options = {}) {
258
+ const prefix = options.prefix ?? 'wt';
259
+ const maxNumber = options.maxNumber ?? 9;
260
+ const claimed = new Set();
261
+ const claimedNames = [...options.claimed ?? []];
262
+ for (const claimedName of claimedNames) {
263
+ if (claimedName.startsWith(prefix) && /^\d+$/u.test(claimedName.slice(prefix.length)))
264
+ claimed.add(Number(claimedName.slice(prefix.length)));
265
+ }
266
+ const numbers = [...new Set([...existingSetNumbers(projectRoot, prefix), ...claimed])].toSorted((a, b) => a - b);
267
+ const last = numbers.at(-1);
268
+ if (last === undefined)
269
+ return `${prefix}1`;
270
+ // 既存セットで該当リポが未登場のものがあればそこに参加
271
+ const joinable = numbers.find(number => !claimed.has(number) && !existsSync(path.join(projectRoot, `${prefix}${String(number)}`, repositoryDirectoryName)));
272
+ if (joinable !== undefined)
273
+ return `${prefix}${String(joinable)}`;
274
+ // 全セットに参加済み → 新セット
275
+ if (last + 1 > maxNumber)
276
+ throw new WorktreeRuntimeError(`all of ${prefix}1 to ${prefix}${String(maxNumber)} are in use: no free set`);
277
+ return `${prefix}${String(last + 1)}`;
278
+ }
279
+ // 未追跡ファイル操作
280
+ /**
281
+ git 管理外(gitignored)ファイルの一覧を取得する。cwd はメイン WT のルート。相対パスを返す
282
+ */
283
+ export function getUntrackedFiles(cwd) {
284
+ const result = runGit(['ls-files', '--others', '--ignored', '--exclude-standard'], { cwd });
285
+ return result.exitCode === 0 ? outputLines(result.stdout).map(line => normalizePath(line)) : [];
286
+ }
287
+ /**
288
+ コピー対象外のファイルを除く。spec は .worktreeignore から読んだ判定
289
+ */
290
+ export function filterCopyableFiles(files, spec) {
291
+ return files.filter(file => !spec.matchFile(normalizePath(file)));
292
+ }
293
+ // オーケストレーション
294
+ const NO_REMOTE_MESSAGE = 'cannot get the repository information: check that a git remote is set to a GitHub repository URL';
295
+ // remote 候補を優先順に返す。origin があれば origin だけ、無ければ git remote の順にすべて。URL を読めない remote の repository は undefined
296
+ function readRemoteCandidates(cwd) {
297
+ return preferredRemotes(listRemotes(cwd) ?? []).map((remote) => {
298
+ const location = remoteRepository(cwd, remote);
299
+ if (location === undefined)
300
+ return { remote, repository: undefined };
301
+ try {
302
+ return { remote, repository: createRepositoryReference(location.owner, location.repository) };
303
+ }
304
+ catch (error) {
305
+ if (error instanceof ValidationFailure)
306
+ return { remote, repository: undefined };
307
+ throw error;
308
+ }
309
+ });
310
+ }
311
+ // 必須設定ファイルの存在チェック(無ければ早期エラー、init を促す)。(ワークツリー設定ファイルのパス, コピー除外 spec) を返す
312
+ function loadCopyExcludeSpecOrRaise(mainWorktree, diagnostics) {
313
+ const configPath = path.join(mainWorktree, WORKTREE_CONFIG_FILENAME);
314
+ if (!existsSync(configPath)) {
315
+ throw new WorktreeRuntimeError(`worktree config not found: ${WORKTREE_CONFIG_FILENAME}\n run pecot worktree init to generate the template`);
316
+ }
317
+ try {
318
+ return { configPath, spec: loadCopyExcludeSpec(mainWorktree, diagnostics) };
319
+ }
320
+ catch (error) {
321
+ if (error instanceof WorktreeConfigError)
322
+ throw new WorktreeRuntimeError(error.message, { cause: error });
323
+ throw error;
324
+ }
325
+ }
326
+ // リポジトリ登録チェック。remote は origin、無ければ登録済みのリポを指す最初の remote、どれも未登録なら最初の remote(未登録として止まる)
327
+ function requireRegisteredRepository(cwd) {
328
+ const candidates = readRemoteCandidates(cwd);
329
+ if (candidates.length === 0)
330
+ throw new WorktreeRuntimeError(NO_REMOTE_MESSAGE);
331
+ const config = loadActiveConfig();
332
+ if (config === undefined) {
333
+ throw new WorktreeRuntimeError('project config not found\n hint: run pecot project activate <PROJECT> to set the project');
334
+ }
335
+ for (const candidate of candidates) {
336
+ if (candidate.repository !== undefined && findRepository(config, candidate.repository.owner, candidate.repository.repository) !== undefined) {
337
+ return { repository: candidate.repository, config, remote: candidate.remote };
338
+ }
339
+ }
340
+ const repository = candidates[0]?.repository;
341
+ if (repository === undefined)
342
+ throw new WorktreeRuntimeError(NO_REMOTE_MESSAGE);
343
+ const registered = config.repositories.length > 0
344
+ ? config.repositories.map(item => ` - ${item.owner}/${item.name}`).join('\n')
345
+ : ' (none registered)';
346
+ throw new WorktreeRuntimeError(`repository ${repository.owner}/${repository.repository} is not registered in the `
347
+ + 'active pecot project\n'
348
+ + '\n'
349
+ + 'registered repositories:\n'
350
+ + `${registered}\n`
351
+ + '\n'
352
+ + 'to add this repository to the pecot project:\n'
353
+ + ` pecot project set-repo ${repository.owner}/${repository.repository}\n`
354
+ + '\n'
355
+ + 'to switch to another project:\n'
356
+ + ' pecot project activate <PROJECT>');
357
+ }
358
+ // ベースブランチ決定(プロジェクト設定の develop_branch を使用)
359
+ function defaultBaseBranch(config, repository) {
360
+ const developBranch = getDevelopBranch(config, repository.owner, repository.repository);
361
+ if (developBranch === undefined || developBranch === '') {
362
+ throw new WorktreeRuntimeError(`develop_branch is not set for repository ${repository.owner}/${repository.repository}\n`
363
+ + ' add develop_branch to repositories in the project config file\n'
364
+ + ' or pass --base explicitly');
365
+ }
366
+ return developBranch;
367
+ }
368
+ // ワークツリー設定を読み込む(設定は存在確認済み)。存在するが読み込み・検証に失敗したときは、不在と同様に hard error にして修正を促す
369
+ function loadWorktreeConfigOrRaise(configPath) {
370
+ try {
371
+ return loadConfig(configPath);
372
+ }
373
+ catch (error) {
374
+ if (error instanceof WorktreeConfigError) {
375
+ throw new WorktreeRuntimeError(`failed to load the worktree config: ${normalizePath(configPath)}: ${error.message}\n fix the config file and run it again`, { cause: error });
376
+ }
377
+ throw error;
378
+ }
379
+ }
380
+ // シンボリックリンク作成。(結果, 作成成功したリンクの WT 相対パス) を返す。後者はコピー除外に使う
381
+ function createWorktreeSymlinks(config, projectRoot, worktreePath, diagnostics) {
382
+ const linkedFiles = createSymlinks(config, projectRoot, worktreePath, diagnostics);
383
+ const symlinkedPaths = linkedFiles
384
+ .filter(link => link.action === 'created')
385
+ .map(link => path.relative(worktreePath, link.symlinkPath))
386
+ .filter(relative => relative !== '..' && !relative.startsWith('../'));
387
+ return { linkedFiles, symlinkedPaths };
388
+ }
389
+ function isRelativeTo(file, base) {
390
+ const relative = path.relative(base, file);
391
+ return relative !== '..' && !relative.startsWith('../') && !path.isAbsolute(relative);
392
+ }
393
+ // 未追跡ファイルコピー(シンボリックリンク対象を除外)
394
+ function copyUntrackedToWorktree(mainWorktree, worktreePath, spec, symlinkedPaths) {
395
+ const copyable = filterCopyableFiles(getUntrackedFiles(mainWorktree), spec)
396
+ .filter(file => symlinkedPaths.every(linked => !isRelativeTo(file, linked)));
397
+ return copyable.length > 0 ? copyFiles(mainWorktree, worktreePath, copyable) : [];
398
+ }
399
+ // セットアップコマンド実行。優先順位: CLI --setup 明示 > config.setup_command > skip
400
+ function runEffectiveSetup(setupCommand, config, worktreePath, diagnostics) {
401
+ const effective = setupCommand ?? config.setup_command;
402
+ if (effective === undefined || effective === '')
403
+ return undefined;
404
+ const result = runSetupCommand(effective, worktreePath, config.setup_command_timeout);
405
+ if (result.exitCode !== 0) {
406
+ // Python の core と同じ 1 メッセージ。字下げは受け口側が付ける
407
+ const head = result.exitCode === -1 ? `setup command timed out: ${effective}` : `setup command failed (exit ${String(result.exitCode)}): ${effective}`;
408
+ const lines = [head];
409
+ if (result.stdout.trim() !== '')
410
+ for (const line of result.stdout.replace(/\n+$/, '').split('\n'))
411
+ lines.push(`out: ${line}`);
412
+ if (result.stderr.trim() !== '')
413
+ for (const line of result.stderr.replace(/\n+$/, '').split('\n'))
414
+ lines.push(`err: ${line}`);
415
+ diagnostics.warning(lines.join('\n'));
416
+ }
417
+ return result;
418
+ }
419
+ /**
420
+ ワークツリーを作成する。cwd は対象 Git リポジトリのパス。
421
+ 作成に失敗した場合、プロジェクトルート・既存ブランチ衝突・設定の不備は WorktreeRuntimeError
422
+ */
423
+ export function createWorktree(cwd, diagnostics, options = {}) {
424
+ // 1. メインWT検出 & プロジェクトルート
425
+ const mainWorktree = findMainWorktree(cwd);
426
+ const projectRoot = detectProjectRoot(cwd);
427
+ // 1.1 必須設定ファイルの存在チェック(無ければ早期エラー、init を促す)
428
+ const { configPath, spec } = loadCopyExcludeSpecOrRaise(mainWorktree, diagnostics);
429
+ // 1.2 container rebuild 後の stale worktree メタデータを事前に掃除する。
430
+ // `.git/worktrees/<name>/` だけ残って実体が消えているケース(rebuild や手動 rm -rf のあと)で、add が衝突エラーになるのを防ぐ
431
+ runGit(['worktree', 'prune'], { cwd: mainWorktree });
432
+ // 1.5 リポジトリ登録チェック(アクティブプロジェクト配下か確認)
433
+ const { repository, config, remote } = requireRegisteredRepository(cwd);
434
+ // 2. 名前決定(プロジェクトセットへの自動参加)
435
+ const repositoryDirectoryName = path.basename(mainWorktree);
436
+ const name = options.name ?? getNextSetName(projectRoot, repositoryDirectoryName, { claimed: claimedSetNames(mainWorktree) });
437
+ // 3. ベースブランチ決定(プロジェクト設定の develop_branch を使用)
438
+ const baseBranch = options.baseBranch ?? defaultBaseBranch(config, repository);
439
+ // 4. パス計算: <project_root>/<name>/<repo_dir_name>
440
+ const worktreePath = options.path === undefined ? path.join(projectRoot, name, repositoryDirectoryName) : normalizePath(options.path);
441
+ // dry-run時はここで結果を返す
442
+ if (options.isDryRun === true) {
443
+ return { name, path: worktreePath, branch: name, baseBranch, copiedFiles: [], linkedFiles: [], setupResult: undefined };
444
+ }
445
+ // 5. git worktree add
446
+ addGitWorktree(cwd, worktreePath, name, { remote, baseBranch }, options.isExistingBranchAllowed === true);
447
+ recordWorktreeName(worktreePath, name, diagnostics);
448
+ // 6〜8. シンボリックリンク作成・未追跡ファイルコピー・セットアップコマンド実行
449
+ const worktreeConfig = loadWorktreeConfigOrRaise(configPath);
450
+ const linking = options.shouldLink === false
451
+ ? { linkedFiles: [], symlinkedPaths: [] }
452
+ : createWorktreeSymlinks(worktreeConfig, projectRoot, worktreePath, diagnostics);
453
+ const copiedFiles = options.shouldCopy === false ? [] : copyUntrackedToWorktree(mainWorktree, worktreePath, spec, linking.symlinkedPaths);
454
+ const setupResult = runEffectiveSetup(options.setupCommand, worktreeConfig, worktreePath, diagnostics);
455
+ return { name, path: worktreePath, branch: name, baseBranch, copiedFiles, linkedFiles: linking.linkedFiles, setupResult };
456
+ }
457
+ /**
458
+ `git worktree add` を実行し、既存ブランチ衝突ガードも含めて処理する。
459
+ cwd は対象 Git リポジトリのパス(メイン WT でもサブ WT でも可)。
460
+ 既存ブランチの upstream 不一致、または git worktree add 失敗時は WorktreeRuntimeError
461
+ */
462
+ function addGitWorktree(cwd, worktreePath, name, base, isExistingBranchAllowed) {
463
+ const { remote, baseBranch } = base;
464
+ let hasBranch = runGit(['show-ref', '--verify', '--quiet', `refs/heads/${name}`], { cwd }).exitCode === 0;
465
+ if (hasBranch && !isExistingBranchAllowed) {
466
+ const currentUpstream = pythonStrip(runGit(['for-each-ref', '--format=%(upstream:short)', `refs/heads/${name}`], { cwd }).stdout);
467
+ const expectedUpstream = baseBranch === '' ? undefined : `${remote}/${baseBranch}`;
468
+ if ((currentUpstream === '' ? undefined : currentUpstream) !== expectedUpstream) {
469
+ throw new WorktreeRuntimeError(`branch '${name}' already exists and its upstream differs from the expected one `
470
+ + `(current: ${currentUpstream === '' ? '(unset)' : currentUpstream}, expected: ${expectedUpstream ?? 'None'}): `
471
+ + 'pass --allow-existing-branch to reuse it');
472
+ }
473
+ // upstream 一致かつ bind なし → prune に取り残された孤児ブランチとみなし除去
474
+ const worktreeOfBranch = runGit(['for-each-ref', '--format=%(worktreepath)', `refs/heads/${name}`], { cwd });
475
+ if (worktreeOfBranch.exitCode === 0 && pythonStrip(worktreeOfBranch.stdout) === '') {
476
+ runGit(['branch', '-D', name], { cwd });
477
+ hasBranch = false;
478
+ }
479
+ }
480
+ const gitArguments = hasBranch ? ['worktree', 'add', worktreePath, name] : ['worktree', 'add', worktreePath, '-b', name];
481
+ if (!hasBranch && baseBranch !== '')
482
+ gitArguments.push('--track', `${remote}/${baseBranch}`);
483
+ const result = runGit(gitArguments, { cwd });
484
+ if (result.exitCode !== 0)
485
+ throw new WorktreeRuntimeError(`failed to create the worktree: ${result.stderr}`);
486
+ }
487
+ // worktree の記録。ディレクトリが無い、toplevel が別(.git の消えた跡)なら空。GIT_* は外して読む
488
+ function recordedNameOf(worktreePath) {
489
+ if (!isDirectory(worktreePath))
490
+ return '';
491
+ const toplevel = gitToplevel({ cwd: worktreePath, stripGitEnvironment: true });
492
+ if (toplevel === undefined || resolveRealPath(toplevel) !== resolveRealPath(worktreePath))
493
+ return '';
494
+ const result = runGit(['rev-parse', '--path-format=absolute', '--git-path', WORKTREE_NAME_RECORD], { cwd: worktreePath, stripGitEnvironment: true });
495
+ const recordPath = pythonStrip(result.stdout);
496
+ return recordPath !== '' && result.exitCode === 0 ? readRecord(recordPath) : '';
497
+ }
498
+ /**
499
+ 名前から削除対象の worktree を探す(メインを除く)。記録の名前、置き場所 `<root>/<name>/<repo>`、ブランチ名の順に、段ごとに全件を見る
500
+ */
501
+ function findWorktreePathByName(cwd, name) {
502
+ const candidates = getWorktreeList(cwd).slice(1);
503
+ const recorded = candidates.find(info => recordedNameOf(info.path) === name);
504
+ if (recorded !== undefined)
505
+ return recorded.path;
506
+ let expected;
507
+ try {
508
+ const repositoryName = path.basename(resolveRealPath(findMainWorktree(cwd)));
509
+ expected = path.join(detectProjectRoot(cwd), name, repositoryName);
510
+ }
511
+ catch (error) {
512
+ if (!(error instanceof WorktreeRuntimeError))
513
+ throw error;
514
+ }
515
+ const placed = expected === undefined ? undefined : candidates.find(info => resolveRealPath(info.path) === resolveRealPath(expected));
516
+ return placed?.path ?? candidates.find(info => info.branch === name)?.path;
517
+ }
518
+ /**
519
+ ワークツリーを削除する。name は worktree add が付けた名前(wtN)か、checkout しているブランチ名。
520
+ WT が見つからない・削除に失敗した場合は WorktreeRuntimeError。
521
+ ローカルブランチを消せなかったときは、その理由を返す。成功時と shouldKeepBranch は undefined
522
+ */
523
+ export function removeWorktree(cwd, name, diagnostics, options = {}) {
524
+ // 1. WTパスを特定
525
+ const worktreePath = findWorktreePathByName(cwd, name);
526
+ if (worktreePath === undefined)
527
+ throw new WorktreeRuntimeError(`worktree not found: ${name}`);
528
+ // 2. git worktree remove
529
+ const gitArguments = ['worktree', 'remove', worktreePath];
530
+ if (options.isForced === true)
531
+ gitArguments.push('--force');
532
+ const removed = runGit(gitArguments, { cwd });
533
+ if (removed.exitCode !== 0)
534
+ throw new WorktreeRuntimeError(`failed to remove the worktree: ${removed.stderr}`);
535
+ // 3. ブランチ削除(ローカルブランチ)
536
+ let branchError;
537
+ if (options.shouldKeepBranch !== true) {
538
+ const branchResult = runGit(['branch', '-D', name], { cwd });
539
+ if (branchResult.exitCode !== 0)
540
+ branchError = pythonStrip(branchResult.stderr) || `git branch -D exited with ${String(branchResult.exitCode)}`;
541
+ }
542
+ // 4. プロジェクトルート配下の <name> ディレクトリが空なら rmdir
543
+ removeEmptySetDirectory(cwd, name, diagnostics);
544
+ return branchError;
545
+ }
546
+ function removeEmptySetDirectory(cwd, name, diagnostics) {
547
+ let projectRoot;
548
+ try {
549
+ projectRoot = detectProjectRoot(cwd);
550
+ }
551
+ catch (error) {
552
+ if (error instanceof WorktreeRuntimeError)
553
+ return;
554
+ throw error;
555
+ }
556
+ const groupDirectory = path.join(projectRoot, name);
557
+ if (!isDirectory(groupDirectory) || readdirSync(groupDirectory).length > 0)
558
+ return;
559
+ try {
560
+ rmdirSync(groupDirectory);
561
+ }
562
+ catch (error) {
563
+ const converted = toOsError(error);
564
+ diagnostics.warning(`failed to remove the set directory: ${groupDirectory}: ${converted instanceof Error ? converted.message : String(converted)}`);
565
+ }
566
+ }
567
+ //# sourceMappingURL=worktree.js.map
@@ -0,0 +1,33 @@
1
+ import type { CallToolResult } from '@modelcontextprotocol/server';
2
+ import type { CommandIo } from '../commands/registry.js';
3
+ export interface CommandOutcome {
4
+ readonly exitCode: number;
5
+ readonly stdout: string;
6
+ readonly stderr: string;
7
+ }
8
+ export interface CollectedIo {
9
+ /**
10
+ readLine を持たない。標準入力の無い io は、入力の終端と同じ扱い
11
+ */
12
+ readonly io: CommandIo;
13
+ readonly stdout: () => string;
14
+ readonly stderr: () => string;
15
+ }
16
+ /**
17
+ stdout・stderr に書かれた文字列を集める io
18
+ */
19
+ export declare function collectIo(): CollectedIo;
20
+ /**
21
+ 結果の _meta で、終了コードと stdout・stderr を載せるキー。モデルには届かず、SDK のクライアントには届く
22
+ */
23
+ export declare const OUTCOME_META_KEY = "io.github.pecotcraft/outcome";
24
+ /**
25
+ content は stdout、続けて stderr(あれば)。stdout・stderr が空で終了コード 0 なら空。
26
+ structuredContent は付けない(Claude Code が content を落とし、Copilot CLI は二重に渡すため)。終了コードと 2 つの出力は _meta に入れる
27
+ */
28
+ export declare function toToolResult(outcome: Readonly<CommandOutcome>): CallToolResult;
29
+ /**
30
+ コマンドを呼ぶ前に入力を断った結果。終了コードが無いので _meta は付けない
31
+ */
32
+ export declare function toRejectedResult(message: string): CallToolResult;
33
+ //# sourceMappingURL=result.d.ts.map
@@ -0,0 +1,52 @@
1
+ /**
2
+ stdout・stderr に書かれた文字列を集める io
3
+ */
4
+ export function collectIo() {
5
+ const out = [];
6
+ const error = [];
7
+ return {
8
+ io: {
9
+ stdout: (text) => {
10
+ out.push(text);
11
+ },
12
+ stderr: (text) => {
13
+ error.push(text);
14
+ },
15
+ },
16
+ stdout: () => out.join(''),
17
+ stderr: () => error.join(''),
18
+ };
19
+ }
20
+ /**
21
+ 結果の _meta で、終了コードと stdout・stderr を載せるキー。モデルには届かず、SDK のクライアントには届く
22
+ */
23
+ export const OUTCOME_META_KEY = 'io.github.pecotcraft/outcome';
24
+ function textBlock(text) {
25
+ return { type: 'text', text };
26
+ }
27
+ // 2 個目の本文。stderr に、終了コードが 0 でなければ `exit code: <n>` の行を足す
28
+ function diagnosticText(outcome) {
29
+ if (outcome.exitCode === 0)
30
+ return outcome.stderr;
31
+ const separator = outcome.stderr === '' || outcome.stderr.endsWith('\n') ? '' : '\n';
32
+ return `${outcome.stderr}${separator}exit code: ${String(outcome.exitCode)}\n`;
33
+ }
34
+ /**
35
+ content は stdout、続けて stderr(あれば)。stdout・stderr が空で終了コード 0 なら空。
36
+ structuredContent は付けない(Claude Code が content を落とし、Copilot CLI は二重に渡すため)。終了コードと 2 つの出力は _meta に入れる
37
+ */
38
+ export function toToolResult(outcome) {
39
+ const diagnostic = diagnosticText(outcome);
40
+ return {
41
+ content: [...outcome.stdout === '' ? [] : [textBlock(outcome.stdout)], ...diagnostic === '' ? [] : [textBlock(diagnostic)]],
42
+ ...outcome.exitCode !== 0 && { isError: true },
43
+ _meta: { [OUTCOME_META_KEY]: { exitCode: outcome.exitCode, stdout: outcome.stdout, stderr: outcome.stderr } },
44
+ };
45
+ }
46
+ /**
47
+ コマンドを呼ぶ前に入力を断った結果。終了コードが無いので _meta は付けない
48
+ */
49
+ export function toRejectedResult(message) {
50
+ return { content: [{ type: 'text', text: message }], isError: true };
51
+ }
52
+ //# sourceMappingURL=result.js.map