Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix(github): stop reporting merge/close/update success when nothing happened (#4425)

Aaditya88349655ebc2
diff --git a/v3/@claude-flow/cli/__tests__/github-tools-false-success-4424.test.ts b/v3/@claude-flow/cli/__tests__/github-tools-false-success-4424.test.ts
new file mode 100644
index 0000000000..7024c6d788
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/github-tools-false-success-4424.test.ts
@@ -0,0 +1,121 @@
+/**
+ * #4424: github_pr_manage merge/close and github_issue_track update/close
+ * reported success when nothing happened on GitHub:
+ * - a failed `gh` call fell through to the local JSON store and returned
+ * { success: true, source: 'local-store' };
+ * - the local fallback matched with `key.includes(String(n))` against
+ * `pr-<Date.now()>` keys and returned success whether or not it matched;
+ * - github_pr_manage never passed owner/repo to `gh` (fixed for issues in #2963).
+ *
+ * Mocks `node:child_process` like github-issue-track-repo-flag-2963.test.ts so
+ * the exact `gh` argv and failures can be controlled; the local store lives in
+ * a temp CLAUDE_FLOW_CWD.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const execFileSyncMock = vi.fn();
+const execSyncMock = vi.fn();
+
+vi.mock('node:child_process', () => ({
+ execFileSync: (...args: unknown[]) => execFileSyncMock(...args),
+ execSync: (...args: unknown[]) => execSyncMock(...args),
+}));
+
+const originalProjectCwd = process.env.CLAUDE_FLOW_CWD;
+let storePath: string;
+
+function seedStore(prs: Record<string, object>, issues: Record<string, object>) {
+ writeFileSync(storePath, JSON.stringify({ repos: {}, prs, issues, version: '3.0.0' }));
+}
+const readStore = () => JSON.parse(readFileSync(storePath, 'utf-8'));
+// execFileSync throws with the child's stderr attached; that text must reach the caller.
+const GH_STDERR = 'X Pull request #12 is not mergeable: the merge commit cannot be cleanly created.';
+const ghFails = () => execFileSyncMock.mockImplementation(() => { throw Object.assign(new Error('Command failed: gh'), { stderr: `${GH_STDERR}\n` }); });
+
+async function tool(name: string) {
+ const { githubTools } = await import('../src/mcp-tools/github-tools.js');
+ const t = githubTools.find((c) => c.name === name)!;
+ return (input: Record<string, unknown>) => t.handler(input) as Promise<Record<string, unknown>>;
+}
+
+beforeEach(() => {
+ execFileSyncMock.mockReset();
+ execSyncMock.mockReset();
+ const scratch = mkdtempSync(join(tmpdir(), 'ruflo-4424-'));
+ process.env.CLAUDE_FLOW_CWD = scratch;
+ mkdirSync(join(scratch, '.claude-flow', 'github'), { recursive: true });
+ storePath = join(scratch, '.claude-flow', 'github', 'store.json');
+ // Local record whose timestamp id contains "12": the old includes() lookup matched prNumber 12.
+ seedStore(
+ { 'pr-1786319612345': { id: 'pr-1786319612345', title: 'local', status: 'open', branch: 'b', createdAt: 'x' } },
+ { 'issue-1786319612345': { id: 'issue-1786319612345', title: 'local', status: 'open', labels: [], createdAt: 'x' } },
+ );
+});
+
+afterEach(() => {
+ if (originalProjectCwd === undefined) delete process.env.CLAUDE_FLOW_CWD;
+ else process.env.CLAUDE_FLOW_CWD = originalProjectCwd;
+});
+
+describe('with gh installed (#4424)', () => {
+ beforeEach(() => { execSyncMock.mockReturnValue('gh version 2.0.0'); });
+
+ it.each([
+ ['github_pr_manage', { action: 'merge', prNumber: 12 }],
+ ['github_pr_manage', { action: 'close', prNumber: 12 }],
+ ['github_issue_track', { action: 'close', issueNumber: 12 }],
+ ['github_issue_track', { action: 'update', issueNumber: 12, title: 'renamed' }],
+ ])('%s %o fails when gh fails, and leaves the local store alone', async (name, input) => {
+ ghFails();
+ const r = await (await tool(name))(input);
+ // Baseline: { success: true, source: 'local-store' } and the pr-…12… record mutated.
+ expect(r.success).toBe(false);
+ expect(r.source).toBe('gh-cli');
+ expect(String(r.error)).toMatch(/failed: /);
+ expect(String(r.error)).toContain(GH_STDERR);
+ expect(readStore().prs['pr-1786319612345'].status).toBe('open');
+ expect(readStore().issues['issue-1786319612345']).toMatchObject({ status: 'open', title: 'local' });
+ });
+
+ it.each(['merge', 'close'])('pr %s passes --repo owner/repo to gh (as #2963 does for issues)', async (action) => {
+ execFileSyncMock.mockReturnValue('');
+ const r = await (await tool('github_pr_manage'))({ action, prNumber: 7, owner: 'acme', repo: 'widgets' });
+ expect(r.success).toBe(true);
+ const [file, argv] = execFileSyncMock.mock.calls[0] as [string, string[]];
+ expect(file).toBe('gh');
+ expect(argv.slice(0, 3)).toEqual(['pr', action, '7']);
+ expect(argv[argv.indexOf('--repo') + 1]).toBe('acme/widgets');
+ });
+
+ it('a successful gh merge is still reported as merged (control)', async () => {
+ execFileSyncMock.mockReturnValue('');
+ const r = await (await tool('github_pr_manage'))({ action: 'merge', prNumber: 7 });
+ expect(r).toMatchObject({ success: true, _real: true, action: 'merged', prNumber: 7 });
+ expect(r.mergedAt).toEqual(expect.any(String));
+ });
+});
+
+describe('without gh, local-store mode (#4424)', () => {
+ beforeEach(() => { execSyncMock.mockImplementation(() => { throw new Error('gh: command not found'); }); });
+
+ it.each([
+ ['github_pr_manage', { action: 'merge', prNumber: 12 }],
+ ['github_issue_track', { action: 'close', issueNumber: 12 }],
+ ])('%s %o fails when no local record has that exact id', async (name, input) => {
+ const r = await (await tool(name))(input);
+ expect(r.success).toBe(false);
+ expect(r.source).toBe('local-store');
+ expect(readStore().prs['pr-1786319612345'].status).toBe('open');
+ expect(readStore().issues['issue-1786319612345'].status).toBe('open');
+ });
+
+ it('updates the local record whose id matches exactly (control)', async () => {
+ seedStore({ 'pr-5': { id: 'pr-5', title: 'local', status: 'open', branch: 'b', createdAt: 'x' } }, {});
+ const merged = await (await tool('github_pr_manage'))({ action: 'merge', prNumber: 5 });
+ expect(merged).toMatchObject({ success: true, source: 'local-store', action: 'merged', prNumber: 5 });
+ expect(readStore().prs['pr-5'].status).toBe('merged');
+ });
+});
diff --git a/v3/@claude-flow/cli/src/mcp-tools/github-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/github-tools.ts
index 6fd5b6e341..2d3b69ec2b 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/github-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/github-tools.ts
@@ -98,16 +98,25 @@ function run(cmd: string, cwd?: string): string | null {
* strings stay literal.
*/
function runArgv(file: string, args: string[], cwd?: string): string | null {
+ const r = runArgvResult(file, args, cwd);
+ return 'out' in r ? r.out : null;
+}
+
+/** runArgv that keeps the failure text (stderr, else the error message) for reporting. */
+function runArgvResult(file: string, args: string[], cwd?: string): { out: string } | { error: string } {
try {
- return execFileSync(file, args, {
- encoding: 'utf-8',
- timeout: 15000,
- cwd: cwd || getProjectCwd(),
- stdio: ['pipe', 'pipe', 'pipe'],
- shell: false,
- }).trim();
- } catch {
- return null;
+ return {
+ out: execFileSync(file, args, {
+ encoding: 'utf-8',
+ timeout: 15000,
+ cwd: cwd || getProjectCwd(),
+ stdio: ['pipe', 'pipe', 'pipe'],
+ shell: false,
+ }).trim(),
+ };
+ } catch (err) {
+ const e = err as { stderr?: string | Buffer; message?: string };
+ return { error: String(e.stderr ?? '').trim() || e.message || 'unknown error' };
}
}
@@ -251,10 +260,13 @@ export const githubTools: MCPTool[] = [
const store = loadGitHubStore();
const action = (input.action as string) || 'list';
const gh = hasGhCli();
+ // #4424: like #2963 for issues — owner/repo were validated but never
+ // passed to `gh`, so PR actions (including merge/close) hit the cwd's repo.
+ const repoArgs: string[] = input.owner && input.repo ? ['--repo', `${input.owner}/${input.repo}`] : [];
if (action === 'list') {
if (gh) {
- const raw = run('gh pr list --state all --limit 20 --json number,title,state,headRefName,createdAt');
+ const raw = runArgv('gh', ['pr', 'list', '--state', 'all', '--limit', '20', '--json', 'number,title,state,headRefName,createdAt', ...repoArgs]);
if (raw) {
try {
const prs = JSON.parse(raw);
@@ -282,6 +294,7 @@ export const githubTools: MCPTool[] = [
'--base', baseBranch,
'--head', headBranch,
'--body', body,
+ ...repoArgs,
]);
if (result) {
return { success: true, _real: true, action: 'created', url: result };
@@ -304,6 +317,7 @@ export const githubTools: MCPTool[] = [
const raw = runArgv('gh', [
'pr', 'view', String(prNumber),
'--json', 'number,title,state,body,additions,deletions,changedFiles,reviews,mergeable,statusCheckRollup',
+ ...repoArgs,
]);
if (raw) {
try {
@@ -314,31 +328,26 @@ export const githubTools: MCPTool[] = [
return { success: false, error: prNumber ? 'gh CLI not available or PR not found. Install gh: https://cli.github.com' : 'prNumber is required (positive integer) for review.' };
}
- if (action === 'merge') {
- const prNumber = toPositiveInt(input.prNumber);
- if (gh && prNumber) {
- const result = runArgv('gh', ['pr', 'merge', String(prNumber), '--merge']);
- if (result !== null) {
- return { success: true, _real: true, action: 'merged', prNumber, mergedAt: new Date().toISOString() };
- }
- }
- // Fallback: local store
- const prKey = prNumber ? Object.keys(store.prs).find(k => k.includes(String(prNumber))) : undefined;
- if (prKey && store.prs[prKey]) { store.prs[prKey].status = 'merged'; saveGitHubStore(store); }
- return { success: true, source: 'local-store', action: 'merged', prNumber, mergedAt: new Date().toISOString() };
- }
-
- if (action === 'close') {
+ if (action === 'merge' || action === 'close') {
+ // #4424: a failed `gh` call, or a local fallback that matched nothing,
+ // used to be reported as success. Fail instead; offline, only update a
+ // local record whose id is exactly `pr-<prNumber>`.
const prNumber = toPositiveInt(input.prNumber);
- if (gh && prNumber) {
- const result = runArgv('gh', ['pr', 'close', String(prNumber)]);
- if (result !== null) {
- return { success: true, _real: true, action: 'closed', prNumber, closedAt: new Date().toISOString() };
+ if (!prNumber) return { success: false, error: `prNumber is required (positive integer) for ${action}.` };
+ const status = action === 'merge' ? 'merged' : 'closed';
+ if (gh) {
+ const argv = action === 'merge' ? ['pr', 'merge', String(prNumber), '--merge'] : ['pr', 'close', String(prNumber)];
+ const r = runArgvResult('gh', [...argv, ...repoArgs]);
+ if ('error' in r) {
+ return { success: false, source: 'gh-cli', error: `gh pr ${action} ${prNumber} failed: ${r.error}` };
}
+ return { success: true, _real: true, action: status, prNumber, [`${status}At`]: new Date().toISOString() };
}
- const prKey = prNumber ? Object.keys(store.prs).find(k => k.includes(String(prNumber))) : undefined;
- if (prKey && store.prs[prKey]) { store.prs[prKey].status = 'closed'; saveGitHubStore(store); }
- return { success: true, source: 'local-store', action: 'closed', prNumber, closedAt: new Date().toISOString() };
+ const pr = store.prs[`pr-${prNumber}`];
+ if (!pr) return { success: false, source: 'local-store', error: `gh CLI not available and no local PR pr-${prNumber}` };
+ pr.status = status;
+ saveGitHubStore(store);
+ return { success: true, source: 'local-store', action: status, prNumber, [`${status}At`]: new Date().toISOString() };
}
return { success: false, error: 'Unknown action' };
@@ -416,42 +425,40 @@ export const githubTools: MCPTool[] = [
return { success: true, source: 'local-store', action: 'created', issue };
}
- if (action === 'update') {
+ if (action === 'update' || action === 'close') {
+ // #4424: same contract as github_pr_manage merge/close — a failed `gh`
+ // call or an unmatched local fallback is a failure, not a success.
const issueNumber = toPositiveInt(input.issueNumber);
- if (gh && issueNumber) {
- const argv = ['issue', 'edit', String(issueNumber)];
- if (input.title) argv.push('--title', input.title as string);
- if (input.labels) {
- const labels = sanitizeLabels(input.labels);
- if (labels === null) return { success: false, error: 'labels contains disallowed characters' };
- if (labels.length > 0) argv.push('--add-label', labels.join(','));
- }
- if (argv.length > 3) {
- const result = runArgv('gh', [...argv, ...repoArgs]);
- if (result !== null) return { success: true, _real: true, action: 'updated', issueNumber };
+ if (!issueNumber) return { success: false, error: `issueNumber is required (positive integer) for ${action}.` };
+ const labels = input.labels === undefined ? undefined : sanitizeLabels(input.labels);
+ if (labels === null) return { success: false, error: 'labels contains disallowed characters' };
+ if (gh) {
+ const argv = ['issue', action === 'update' ? 'edit' : 'close', String(issueNumber)];
+ if (action === 'update') {
+ if (input.title) argv.push('--title', input.title as string);
+ if (labels && labels.length > 0) argv.push('--add-label', labels.join(','));
+ if (argv.length === 3) return { success: false, error: 'update requires title or labels' };
}
- }
- const issueKey = issueNumber ? Object.keys(store.issues).find(k => k.includes(String(issueNumber))) : undefined;
- if (issueKey && store.issues[issueKey]) {
- if (input.title) store.issues[issueKey].title = input.title as string;
- if (input.labels) {
- const labels = sanitizeLabels(input.labels);
- if (labels !== null) store.issues[issueKey].labels = labels;
+ const r = runArgvResult('gh', [...argv, ...repoArgs]);
+ if ('error' in r) {
+ return { success: false, source: 'gh-cli', error: `gh issue ${argv[1]} ${issueNumber} failed: ${r.error}` };
}
- saveGitHubStore(store);
+ return action === 'update'
+ ? { success: true, _real: true, action: 'updated', issueNumber }
+ : { success: true, _real: true, action: 'closed', issueNumber, closedAt: new Date().toISOString() };
}
- return { success: true, source: 'local-store', action: 'updated', issueNumber };
- }
-
- if (action === 'close') {
- const issueNumber = toPositiveInt(input.issueNumber);
- if (gh && issueNumber) {
- const result = runArgv('gh', ['issue', 'close', String(issueNumber), ...repoArgs]);
- if (result !== null) return { success: true, _real: true, action: 'closed', issueNumber, closedAt: new Date().toISOString() };
+ const issue = store.issues[`issue-${issueNumber}`];
+ if (!issue) return { success: false, source: 'local-store', error: `gh CLI not available and no local issue issue-${issueNumber}` };
+ if (action === 'close') {
+ issue.status = 'closed';
+ } else {
+ if (input.title) issue.title = input.title as string;
+ if (labels) issue.labels = labels;
}
- const issueKey = issueNumber ? Object.keys(store.issues).find(k => k.includes(String(issueNumber))) : undefined;
- if (issueKey && store.issues[issueKey]) { store.issues[issueKey].status = 'closed'; saveGitHubStore(store); }
- return { success: true, source: 'local-store', action: 'closed', issueNumber, closedAt: new Date().toISOString() };
+ saveGitHubStore(store);
+ return action === 'update'
+ ? { success: true, source: 'local-store', action: 'updated', issueNumber }
+ : { success: true, source: 'local-store', action: 'closed', issueNumber, closedAt: new Date().toISOString() };
}
return { success: false, error: 'Unknown action' };