@pecot/workflow-mcp 8.0.1-dev.54 → 8.0.1-dev.56

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pecot-w",
3
- "version": "8.0.1-dev.54",
3
+ "version": "8.0.1-dev.56",
4
4
  "description": "pecot-w (pecot-workflow) workflow automation plugin for Claude Code - skills, hooks, agents, and commands for AI-assisted development",
5
5
  "author": {
6
6
  "name": "pecot"
@@ -16,6 +16,10 @@ export interface CommandIo {
16
16
  */
17
17
  readonly surface?: 'cli' | 'mcp';
18
18
  /**
19
+ MCP の要求の取り消し。MCP だけが渡す
20
+ */
21
+ readonly signal?: Readonly<AbortSignal>;
22
+ /**
19
23
  失敗の原因の名前を受け取る。MCP だけが渡す
20
24
  */
21
25
  readonly failureKind?: (kind: FailureKind) => void;
@@ -3,9 +3,10 @@
3
3
  import { z } from 'zod';
4
4
  import { describeApiError } from '../domain/api-error-detail.js';
5
5
  import { getDevelopBranch } from '../domain/config.js';
6
+ import { FORCE_PUSH_COMMAND } from '../domain/pull-request.js';
6
7
  import { describeGone, describeRestackCheck, RESTACK_PATH } from '../domain/restack.js';
7
8
  import { FLAG_PECOT_RESTACK, formatRestackProgress, interpretRestackProgress } from '../domain/state.js';
8
- import { abortRebase, conflictedFiles, continueRebase, fetchRemote, forkPoint, gitStdout, hasSameTree, isAncestor, isRebaseInProgress, mergeBase, pushWithLease, rebaseOnto, remoteOnlyChanges, resetHardTo, resolveCommit, } from '../infra/git.js';
9
+ import { abortRebase, conflictedFiles, continueRebase, fetchRemote, forkPoint, gitStdout, hasSameTree, isAncestor, isRebaseInProgress, mergeBase, PUSH_TIMEOUT_MILLISECONDS, pushWithLease, rebaseOnto, remoteOnlyChanges, resetHardTo, resolveCommit, } from '../infra/git.js';
9
10
  import { readBaseRecord, readFlag, removeFlag, writeBaseRecord, writeFlag } from '../infra/state-store.js';
10
11
  import { defineCommand } from './command-definition.js';
11
12
  import { commandHint, hinted } from './command-hint.js';
@@ -19,6 +20,7 @@ import { readBaseOrInfer, warnUnresolved } from './base-reading.js';
19
20
  import { USAGE_EXIT_CODE } from './usage-error.js';
20
21
  const CONFLICT_EXIT_CODE = 3;
21
22
  const UNCOMMITTED_EXIT_CODE = 2;
23
+ const MILLISECONDS_PER_SECOND = 1000;
22
24
  // 文の中にロングオプションを書けない(lint)ので、git の引数から組む
23
25
  const SKIP_COMMAND = ['git', 'rebase', '--skip'].join(' ');
24
26
  const PR_RESTACK_OUTPUT = z.strictObject({
@@ -70,8 +72,24 @@ function isSyncedWithRemote(cwd, progress) {
70
72
  const remoteBranch = `${progress.remote}/${progress.branch}`;
71
73
  return progress.leaseSha !== undefined && mergeBase(cwd, progress.ontoSha, remoteBranch) === progress.ontoSha && hasSameTree(cwd, 'HEAD', remoteBranch);
72
74
  }
75
+ // 時間切れは打ち直しても同じところで止まるので、手で push してから打つ道を示す
76
+ function describePushFailure(push, remote, branch) {
77
+ const unchanged = `${branch} is restacked locally and the base record is unchanged`;
78
+ switch (push.reason) {
79
+ case 'timed-out': {
80
+ return hinted `push timed out after ${String(PUSH_TIMEOUT_MILLISECONDS / MILLISECONDS_PER_SECOND)} seconds\n${unchanged}\npush the branch yourself: ${FORCE_PUSH_COMMAND} ${remote} ${branch}\nthen run: ${commandHint(RESTACK_PATH)}`;
81
+ }
82
+ case 'cancelled': {
83
+ // MCP の取り消しには応答が送られない。誰にも届かないが、記録を書かずに止める扱いとして持つ
84
+ return hinted `push was cancelled\n${unchanged}\nrun again: ${commandHint(RESTACK_PATH)}`;
85
+ }
86
+ case 'rejected': {
87
+ return hinted `push was rejected: ${push.stderr.trim()}\n${unchanged}\nrun again: ${commandHint(RESTACK_PATH)}`;
88
+ }
89
+ }
90
+ }
73
91
  // rebase が終わった後。remote が載せ直し済みで木が同じなら合わせ、違えば push し、base の記録を書き直す
74
- function finishRestack(out, cwd, progress) {
92
+ async function finishRestack(out, cwd, progress, signal) {
75
93
  const { remote, branch, ontoBranch, leaseSha } = progress;
76
94
  const remoteBranch = `${remote}/${branch}`;
77
95
  if (leaseSha !== undefined && remoteOnlyCommits(cwd, progress, remoteBranch).length > 0) {
@@ -83,10 +101,10 @@ function finishRestack(out, cwd, progress) {
83
101
  if (isSynced)
84
102
  resetHardTo(cwd, remoteBranch);
85
103
  else if (leaseSha !== undefined) {
86
- const push = pushWithLease(cwd, remote, branch, leaseSha);
104
+ const push = await pushWithLease(cwd, remote, branch, leaseSha, { signal });
87
105
  if (!push.pushed) {
88
106
  removeFlag(FLAG_PECOT_RESTACK);
89
- stopWith(out, hinted `push was rejected: ${push.stderr.trim()}\n${branch} is restacked locally and the base record is unchanged\nrun again: ${commandHint(RESTACK_PATH)}`, 'git-unresolved');
107
+ stopWith(out, describePushFailure(push, remote, branch), 'git-unresolved');
90
108
  }
91
109
  }
92
110
  const record = { branch: ontoBranch, sha: mergeBase(cwd, 'HEAD', `${remote}/${ontoBranch}`) ?? progress.ontoSha, stackedOn: progress.stackedOn };
@@ -96,7 +114,7 @@ function finishRestack(out, cwd, progress) {
96
114
  out.done({ verb: 'update', target: isSynced ? `${branch} synced with ${remoteBranch}` : `${branch} restacked on ${ontoBranch}` });
97
115
  }
98
116
  // --continue と --abort。途中の記録だけを読む。記録が無ければ、利用者が始めた rebase を動かさずに止まる
99
- function resumeRestack(out, cwd, mode, isDryRun) {
117
+ async function resumeRestack(out, cwd, mode, isDryRun, signal) {
100
118
  const reading = interpretRestackProgress(readFlag(FLAG_PECOT_RESTACK));
101
119
  if (reading.kind === 'malformed')
102
120
  stopWith(out, `.pecot-restack is malformed: ${reading.content}`, 'content-invalid');
@@ -124,7 +142,7 @@ function resumeRestack(out, cwd, mode, isDryRun) {
124
142
  }
125
143
  if (isRebasing && continueRebase(cwd) === 'conflict')
126
144
  stopOnConflict(out, cwd, progress);
127
- finishRestack(out, cwd, progress);
145
+ await finishRestack(out, cwd, progress, signal);
128
146
  }
129
147
  function currentBranch(cwd) {
130
148
  return gitStdout(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd })?.trim();
@@ -177,7 +195,7 @@ async function runRestack(input, io) {
177
195
  stopWith(out, 'give only one of check, continue and abort', 'invalid-input', USAGE_EXIT_CODE);
178
196
  const cwd = '.';
179
197
  if (input.continue || input.abort) {
180
- resumeRestack(out, cwd, input.abort ? 'abort' : 'continue', input.dry_run);
198
+ await resumeRestack(out, cwd, input.abort ? 'abort' : 'continue', input.dry_run, io.signal);
181
199
  return;
182
200
  }
183
201
  const { currentBranch: branch, remoteName: remote, location } = validatePullRequestContext(cwd, out);
@@ -227,7 +245,7 @@ async function runRestack(input, io) {
227
245
  out.planned({ verb: 'update', target: isSynced ? `${branch} synced with ${remote}/${branch}` : `${branch} restacked on ${decision.base}` });
228
246
  return;
229
247
  }
230
- finishRestack(out, cwd, progress);
248
+ await finishRestack(out, cwd, progress, io.signal);
231
249
  return;
232
250
  }
233
251
  if (decision.kind !== 'moved' && decision.kind !== 'merged') {
@@ -245,7 +263,7 @@ async function runRestack(input, io) {
245
263
  writeFlag(FLAG_PECOT_RESTACK, formatRestackProgress(progress));
246
264
  stopOnConflict(out, cwd, progress);
247
265
  }
248
- finishRestack(out, cwd, progress);
266
+ await finishRestack(out, cwd, progress, io.signal);
249
267
  }
250
268
  const prRestack = defineCommand({
251
269
  path: RESTACK_PATH,
@@ -191,6 +191,7 @@ export interface PushStatus {
191
191
  ahead と behind のコミット数から、push の状態の文を作る
192
192
  */
193
193
  export declare function describePushStatus(remote: string, branch: string, ahead: number, behind: number): PushStatus;
194
+ export declare const FORCE_PUSH_COMMAND: string;
194
195
  /**
195
196
  diverged の直し方。fast-forward でない push は拒まれるので、取り込むか、書き換えたなら lease 付きで上書きする
196
197
  */
@@ -260,7 +260,7 @@ export function describePushStatus(remote, branch, ahead, behind) {
260
260
  }
261
261
  // 文の中にロングオプションを書けない(lint)ので、git の引数から組む
262
262
  const PULL_REBASE_COMMAND = ['git', 'pull', '--rebase'].join(' ');
263
- const FORCE_PUSH_COMMAND = ['git', 'push', '--force-with-lease'].join(' ');
263
+ export const FORCE_PUSH_COMMAND = ['git', 'push', '--force-with-lease'].join(' ');
264
264
  /**
265
265
  diverged の直し方。fast-forward でない push は拒まれるので、取り込むか、書き換えたなら lease 付きで上書きする
266
266
  */
@@ -40,6 +40,17 @@ export declare class GitCommandError extends BaseError {
40
40
  }
41
41
  export declare const MAX_OUTPUT_BYTES: number;
42
42
  /**
43
+ 取り消しで止めたときの exitCode
44
+ */
45
+ export declare const GIT_CANCELLED = -3;
46
+ /**
47
+ runGit の非同期版。待つ間もイベントループを止めない。
48
+ 時間切れか signal の中断で、git を pre-push のフックごと止め、exitCode が GIT_TIMED_OUT か GIT_CANCELLED の結果を返す
49
+ */
50
+ export declare function runGitAsync(arguments_: readonly string[], options?: Readonly<Omit<GitOptions, 'stripGitEnvironment' | 'check'>> & {
51
+ readonly signal?: Readonly<AbortSignal> | undefined;
52
+ }): Promise<GitResult>;
53
+ /**
43
54
  git を実行する。標準出力・標準エラーは改行を \n に揃えた文字列で返す。
44
55
  git や作業ディレクトリが見つからなければ OsError(code ENOENT)を投げる
45
56
  */
@@ -89,6 +100,10 @@ export declare function activeIssueOf(directory?: string): IssueReference | unde
89
100
  */
90
101
  export declare function remoteRepository(cwd: string | undefined, remote: string): RemoteLocation | undefined;
91
102
  export declare const NON_INTERACTIVE_GIT: Readonly<Record<string, string>>;
103
+ /**
104
+ push の時間切れ。pre-push のフックの時間を含める
105
+ */
106
+ export declare const PUSH_TIMEOUT_MILLISECONDS = 600000;
92
107
  export interface FetchResult {
93
108
  readonly succeeded: boolean;
94
109
  readonly stderr: string;
@@ -97,6 +112,7 @@ export type PushResult = {
97
112
  readonly pushed: true;
98
113
  } | {
99
114
  readonly pushed: false;
115
+ readonly reason: 'rejected' | 'timed-out' | 'cancelled';
100
116
  readonly stderr: string;
101
117
  };
102
118
  export type RebaseOutcome = 'done' | 'conflict';
@@ -161,10 +177,14 @@ export declare function changesSharedWith(cwd: string, head: string, other: stri
161
177
  */
162
178
  export declare function hasSameTree(cwd: string, a: string, b: string): boolean;
163
179
  export declare function resetHardTo(cwd: string, reference: string): void;
180
+ export interface PushOptions {
181
+ readonly signal?: Readonly<AbortSignal> | undefined;
182
+ readonly timeoutMilliseconds?: number | undefined;
183
+ }
164
184
  /**
165
- remote の branch が expectedSha のときだけ、手元の branch で置き換える。拒まれたか失敗したら stderr を返す
185
+ remote の branch が expectedSha のときだけ、手元の branch で置き換える。拒まれたか、時間切れか、取り消されたら、その理由と stderr を返す
166
186
  */
167
- export declare function pushWithLease(cwd: string, remote: string, branch: string, expectedSha: string): PushResult;
187
+ export declare function pushWithLease(cwd: string, remote: string, branch: string, expectedSha: string, options?: Readonly<PushOptions>): Promise<PushResult>;
168
188
  export type RemoteHead = {
169
189
  readonly isReachable: true;
170
190
  readonly sha: string | undefined;
@@ -1,6 +1,6 @@
1
- // git コマンド実行の唯一の窓口。git の subprocess 呼び出しはすべて runGit を経由する。
1
+ // git コマンド実行の唯一の窓口。git の subprocess 呼び出しはすべて runGit か runGitAsync を経由する。
2
2
  // 値を返す helper(gitToplevel 等)は、失敗時に undefined を返す。
3
- import { spawnSync } from 'node:child_process';
3
+ import { spawn, spawnSync } from 'node:child_process';
4
4
  import { existsSync } from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import { activeIssueFromBranch } from '../domain/branch-name.js';
@@ -37,6 +37,89 @@ function withoutGitVariables() {
37
37
  return Object.fromEntries(Object.entries(process.env).filter((entry) => entry[1] !== undefined && !entry[0].startsWith('GIT_')));
38
38
  }
39
39
  /**
40
+ 取り消しで止めたときの exitCode
41
+ */
42
+ export const GIT_CANCELLED = -3;
43
+ // detached の git は端末の Ctrl-C を受けないので、受けたらグループごと止めてから既定の動きに戻す
44
+ const FORWARDED_SIGNALS = ['SIGINT', 'SIGTERM'];
45
+ function killGroup(pid) {
46
+ if (pid === undefined)
47
+ return;
48
+ try {
49
+ // detached の git はプロセスグループの頭なので、負の pid でフックの孫までまとめて止める
50
+ process.kill(-pid, 'SIGKILL');
51
+ }
52
+ catch {
53
+ // 既に終わっている
54
+ }
55
+ }
56
+ /**
57
+ runGit の非同期版。待つ間もイベントループを止めない。
58
+ 時間切れか signal の中断で、git を pre-push のフックごと止め、exitCode が GIT_TIMED_OUT か GIT_CANCELLED の結果を返す
59
+ */
60
+ export async function runGitAsync(arguments_, options = {}) {
61
+ const timeout = options.timeoutMilliseconds === undefined ? undefined : AbortSignal.timeout(options.timeoutMilliseconds);
62
+ const stops = [options.signal, timeout].filter(signal => signal !== undefined);
63
+ const stop = stops.length === 0 ? undefined : AbortSignal.any(stops);
64
+ const child = spawn('git', [...arguments_], {
65
+ cwd: options.cwd,
66
+ // interface-env: none
67
+ env: options.env === undefined ? undefined : { ...process.env, ...options.env },
68
+ stdio: [childStdin(), 'pipe', 'pipe'],
69
+ detached: true,
70
+ });
71
+ const stdout = [];
72
+ const stderr = [];
73
+ child.stdout.setEncoding('utf8').on('data', (chunk) => {
74
+ stdout.push(chunk);
75
+ });
76
+ child.stderr.setEncoding('utf8').on('data', (chunk) => {
77
+ stderr.push(chunk);
78
+ });
79
+ const closed = new Promise((resolve) => {
80
+ child.on('close', () => {
81
+ resolve();
82
+ });
83
+ });
84
+ const kill = () => {
85
+ killGroup(child.pid);
86
+ };
87
+ const forward = (signal) => {
88
+ killGroup(child.pid);
89
+ for (const name of FORWARDED_SIGNALS)
90
+ process.removeListener(name, forward);
91
+ process.kill(process.pid, signal);
92
+ };
93
+ stop?.addEventListener('abort', kill, { once: true });
94
+ for (const name of FORWARDED_SIGNALS)
95
+ process.on(name, forward);
96
+ const ended = await new Promise((resolve) => {
97
+ child.on('error', (error) => {
98
+ resolve({ kind: 'error', error });
99
+ });
100
+ // 'close' は stdio を持つ孫(フック)が終わるまで出ないので、git の終わりは 'exit' で受ける
101
+ child.on('exit', (code) => {
102
+ resolve({ kind: 'exit', code: code ?? undefined });
103
+ });
104
+ });
105
+ stop?.removeEventListener('abort', kill);
106
+ for (const name of FORWARDED_SIGNALS)
107
+ process.removeListener(name, forward);
108
+ if (ended.kind === 'error')
109
+ throw toOsError(ended.error);
110
+ // 止めずに終わったなら、出力を読み切る。止めたなら、残ったパイプを捨てる
111
+ if (ended.code === 0 || stop?.aborted !== true)
112
+ await closed;
113
+ else {
114
+ child.stdout.destroy();
115
+ child.stderr.destroy();
116
+ }
117
+ const output = { stdout: normalizeNewlines(stdout.join('')), stderr: normalizeNewlines(stderr.join('')) };
118
+ if (ended.code === 0 || stop?.aborted !== true)
119
+ return { exitCode: ended.code ?? -1, ...output };
120
+ return { exitCode: options.signal?.aborted === true ? GIT_CANCELLED : GIT_TIMED_OUT, ...output };
121
+ }
122
+ /**
40
123
  git を実行する。標準出力・標準エラーは改行を \n に揃えた文字列で返す。
41
124
  git や作業ディレクトリが見つからなければ OsError(code ENOENT)を投げる
42
125
  */
@@ -153,8 +236,12 @@ export function remoteRepository(cwd, remote) {
153
236
  }
154
237
  // 端末で尋ねさせない。ssh は GIT_SSH_COMMAND で BatchMode にすると利用者の GIT_SSH と core.sshCommand を上書きするので、askpass を失敗させる
155
238
  export const NON_INTERACTIVE_GIT = { GIT_TERMINAL_PROMPT: '0', SSH_ASKPASS: 'false', SSH_ASKPASS_REQUIRE: 'force' };
156
- // fetch・push は、認証の入力を待たずに、この時間で諦める
239
+ // fetch は、この時間で諦める
157
240
  const REMOTE_TIMEOUT_MILLISECONDS = 60_000;
241
+ /**
242
+ push の時間切れ。pre-push のフックの時間を含める
243
+ */
244
+ export const PUSH_TIMEOUT_MILLISECONDS = 600_000;
158
245
  const PEEL_TO_COMMIT = '^{commit}';
159
246
  /**
160
247
  `git fetch <remote>`。失敗・時間切れは succeeded が false
@@ -263,12 +350,17 @@ export function hasSameTree(cwd, a, b) {
263
350
  export function resetHardTo(cwd, reference) {
264
351
  runGit(['reset', '--quiet', '--hard', reference], { cwd, check: true });
265
352
  }
353
+ function pushFailure(exitCode) {
354
+ if (exitCode === GIT_TIMED_OUT)
355
+ return 'timed-out';
356
+ return exitCode === GIT_CANCELLED ? 'cancelled' : 'rejected';
357
+ }
266
358
  /**
267
- remote の branch が expectedSha のときだけ、手元の branch で置き換える。拒まれたか失敗したら stderr を返す
359
+ remote の branch が expectedSha のときだけ、手元の branch で置き換える。拒まれたか、時間切れか、取り消されたら、その理由と stderr を返す
268
360
  */
269
- export function pushWithLease(cwd, remote, branch, expectedSha) {
270
- const result = runGit(['push', `--force-with-lease=${branch}:${expectedSha}`, remote, branch], { cwd, env: NON_INTERACTIVE_GIT, timeoutMilliseconds: REMOTE_TIMEOUT_MILLISECONDS });
271
- return result.exitCode === 0 ? { pushed: true } : { pushed: false, stderr: result.stderr };
361
+ export async function pushWithLease(cwd, remote, branch, expectedSha, options = {}) {
362
+ const result = await runGitAsync(['push', `--force-with-lease=${branch}:${expectedSha}`, remote, branch], { cwd, env: NON_INTERACTIVE_GIT, timeoutMilliseconds: options.timeoutMilliseconds ?? PUSH_TIMEOUT_MILLISECONDS, signal: options.signal });
363
+ return result.exitCode === 0 ? { pushed: true } : { pushed: false, reason: pushFailure(result.exitCode), stderr: result.stderr };
272
364
  }
273
365
  // ls-remote は、ref が無いと終了コード 2 を返す
274
366
  const LS_REMOTE_NOT_FOUND = 2;
@@ -80,7 +80,7 @@ function unavailableResult(reason) {
80
80
  function unexpectedMessage(error) {
81
81
  return error instanceof Error ? error.message : String(error);
82
82
  }
83
- async function invoke(definition, raw, options) {
83
+ async function invoke(definition, raw, options, signal) {
84
84
  if (options.unavailableReason !== undefined)
85
85
  return unavailableResult(options.unavailableReason);
86
86
  const collected = collectIo();
@@ -94,7 +94,7 @@ async function invoke(definition, raw, options) {
94
94
  if (preparation.kind === 'rejected')
95
95
  return toRejectedResult(preparation.message);
96
96
  try {
97
- exitCode = await preparation.command.run(collected.io);
97
+ exitCode = await preparation.command.run({ ...collected.io, signal });
98
98
  }
99
99
  catch (error) {
100
100
  throw withUsage(error, usageOf(definition));
@@ -168,7 +168,7 @@ MCP サーバを作り、commands のそれぞれをツールとして登録す
168
168
  export function createMcpServer(commands = COMMANDS, options = {}) {
169
169
  const server = new McpServer({ name: MCP_SERVER_NAME, version: readVersion() });
170
170
  for (const definition of commands) {
171
- server.registerTool(definition.toolName, { description: definition.description, inputSchema: passthroughSchema(definition), outputSchema: standardOutputSchema(toolOutputSchema(definition.output)) }, async (arguments_, serverContext) => await inSequence(serverContext.mcpReq.signal, async () => await invoke(definition, arguments_, options)));
171
+ server.registerTool(definition.toolName, { description: definition.description, inputSchema: passthroughSchema(definition), outputSchema: standardOutputSchema(toolOutputSchema(definition.output)) }, async (arguments_, serverContext) => await inSequence(serverContext.mcpReq.signal, async () => await invoke(definition, arguments_, options, serverContext.mcpReq.signal)));
172
172
  }
173
173
  return server;
174
174
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@pecot/workflow-mcp",
3
- "version": "8.0.1-dev.54",
3
+ "version": "8.0.1-dev.56",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@pecot/workflow-mcp",
9
- "version": "8.0.1-dev.54",
9
+ "version": "8.0.1-dev.56",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@modelcontextprotocol/server": "^2.4.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pecot/workflow-mcp",
3
- "version": "8.0.1-dev.54",
3
+ "version": "8.0.1-dev.56",
4
4
  "type": "module",
5
5
  "description": "pecot-workflow MCP server (standalone distribution)",
6
6
  "license": "MIT",