Skip to content

feat(github-workflow): add auto-create-pr hook#46

Open
masseater wants to merge 6 commits intomasterfrom
feat/auto-create-pr
Open

feat(github-workflow): add auto-create-pr hook#46
masseater wants to merge 6 commits intomasterfrom
feat/auto-create-pr

Conversation

@masseater
Copy link
Copy Markdown
Owner

@masseater masseater commented Apr 6, 2026

Summary

  • git push 後に PR が存在しない場合、gh pr create --fill で自動的に PR を作成する PostToolUse hook を追加
  • 作成結果(タイトル・URL)を additionalContext で AI に報告
  • デフォルトブランチへの push や既存 PR がある場合はスキップ

Test plan

  • feature ブランチで git push した際に PR が自動作成されることを確認
  • 既に PR がある場合はスキップされることを確認
  • master への push ではスキップされることを確認

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Automatic pull request creation after code push, skipping the default branch and avoiding duplicate PRs.
  • Documentation

    • Added documentation entry describing the new auto-create-PR workflow hook.
  • Tests

    • Added tests covering success, skip, defer, and failure flows for the auto-create-PR behavior.
  • Chores

    • Bumped plugin version to 0.0.10.

masseater and others added 3 commits April 6, 2026 19:54
Automatically creates a PR via `gh pr create --fill` after git push
when no PR exists for the branch, and reports the result back to the AI.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 6, 2026

Warning

Rate limit exceeded

@masseater has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 11 minutes and 26 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 11 minutes and 26 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1d2b6c8a-ef19-4076-bc7b-792319402c97

📥 Commits

Reviewing files that changed from the base of the PR and between d91ab1d and 383adcc.

📒 Files selected for processing (2)
  • apps/ops-harbor/vitest.config.ts
  • packages/ops-harbor-core/vitest.config.ts
📝 Walkthrough

Walkthrough

Bumps github-workflow plugin to v0.0.10 and adds a new PostToolUse hook auto-create-pr that reacts to git push commands, skips default/HEAD branches or existing PRs, and creates a PR via the GitHub CLI, returning success/failure context (supports deferred PR creation).

Changes

Cohort / File(s) Summary
Version Updates
\.claude-plugin/marketplace.json, plugins/github-workflow/plugin.json
Bumped github-workflow plugin version from 0.0.90.0.10.
Documentation
plugins/github-workflow/AGENTS.md
Added auto-create-pr hook entry (PostToolUse, Bash).
Hook Implementation
plugins/github-workflow/hooks/entry/auto-create-pr.ts
New Bun-based hook: detects git push, obtains branch, skips HEAD/default branch or existing PR, defers and runs gh pr create --fill --head <branch>, captures output, fetches PR title, and emits hookSpecificOutput.additionalContext.
Hook Registration
plugins/github-workflow/hooks/hooks.json
Registered the new entry script into the PostToolUse Bash hook pipeline.
Tests
plugins/github-workflow/hooks/auto-create-pr.test.ts
New Vitest suite covering non-push, non-git, default-branch, existing-PR, deferred-success, and deferred-failure flows; installs mocked Bun spawn behavior and hook registration.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant HookRunner as Hook Runner
    participant Git as Git (local)
    participant GH as GitHub CLI (gh)
    participant Scheduler as Deferred Scheduler

    HookRunner->>Git: inspect current branch (git rev-parse --abbrev-ref HEAD)
    alt branch missing or HEAD
        HookRunner-->>HookRunner: exit success (no-op)
    else branch present
        HookRunner->>GH: query default branch (gh repo view --json defaultBranchRef)
        GH-->>HookRunner: default branch info
        alt branch == default
            HookRunner-->>HookRunner: exit success (skip default)
        else
            HookRunner->>GH: check for existing PR (gh pr view --head <branch>)
            alt PR exists
                HookRunner-->>HookRunner: exit success (PR exists)
            else no PR
                HookRunner->>Scheduler: defer async PR creation task (timeout 30s)
                Scheduler->>GH: run gh pr create --fill --head <branch>
                alt gh pr create succeeds
                    GH-->>Scheduler: stdout (PR URL)
                    Scheduler->>GH: gh pr view --json title,url
                    GH-->>Scheduler: PR details
                    Scheduler-->>HookRunner: deferred success with additionalContext (Created PR + URL/title)
                else fails
                    GH-->>Scheduler: stderr/exit non-zero
                    Scheduler-->>HookRunner: deferred failure with additionalContext (Failed to create PR + output)
                end
            end
        end
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 In branches where pushes softly tread,
I sniff and skip where defaults spread.
If no PR blooms, I hop and try,
A tiny PR under the sky—
Hooray! A merge to make code fly. ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(github-workflow): add auto-create-pr hook' clearly and concisely summarizes the main change: introducing a new auto-create-pr hook to the github-workflow plugin.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/auto-create-pr

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@plugins/github-workflow/hooks/entry/auto-create-pr.ts`:
- Around line 38-69: The createPr function can leave spawned processes (proc and
viewProc) running if the surrounding context.defer times out; modify createPr to
create an AbortController (or receive an AbortSignal from the defer) and pass
its signal to Bun.spawn calls for both proc and viewProc, and ensure you
abort/kill the controller when the defer timeout triggers (or on Promise.race
timeout) so proc.kill()/viewProc.kill() (or controller.abort()) is invoked to
terminate hanging subprocesses; update the Bun.spawn invocations in createPr to
include the signal option and handle abort errors appropriately so you always
clean up subprocesses on timeout or error.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 82eb5316-d06e-44b3-a219-49919fd165c1

📥 Commits

Reviewing files that changed from the base of the PR and between 98dfe1d and 895b95f.

📒 Files selected for processing (5)
  • .claude-plugin/marketplace.json
  • plugins/github-workflow/AGENTS.md
  • plugins/github-workflow/hooks/entry/auto-create-pr.ts
  • plugins/github-workflow/hooks/hooks.json
  • plugins/github-workflow/plugin.json

Comment on lines +38 to +69
async function createPr(branch: string): Promise<PrCreateResult> {
const proc = Bun.spawn(["gh", "pr", "create", "--fill", "--head", branch], {
stdout: "pipe",
stderr: "pipe",
});
await proc.exited;

const stdout = (await new Response(proc.stdout).text()).trim();
const stderr = (await new Response(proc.stderr).text()).trim();

if (proc.exitCode !== 0) {
return { created: false, url: null, title: null, error: stderr || "Unknown error" };
}

// gh pr create --fill outputs the PR URL on success
const url = stdout;

// Fetch the title from the created PR
let title: string | null = null;
try {
const viewProc = Bun.spawn(["gh", "pr", "view", branch, "--json", "title", "--jq", ".title"], {
stdout: "pipe",
stderr: "pipe",
});
await viewProc.exited;
title = (await new Response(viewProc.stdout).text()).trim() || null;
} catch {
// title is optional
}

return { created: true, url, title, error: null };
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Subprocess may outlive the defer timeout.

The context.defer wrapper enforces a 30-second timeout, but if gh pr create hangs, the spawned process continues running in the background after the timeout rejects. Consider explicitly killing the process on timeout to avoid resource leaks.

♻️ Suggested approach with AbortSignal
-async function createPr(branch: string): Promise<PrCreateResult> {
-  const proc = Bun.spawn(["gh", "pr", "create", "--fill", "--head", branch], {
+async function createPr(branch: string, signal?: AbortSignal): Promise<PrCreateResult> {
+  const proc = Bun.spawn(["gh", "pr", "create", "--fill", "--head", branch], {
     stdout: "pipe",
     stderr: "pipe",
   });
+
+  signal?.addEventListener("abort", () => proc.kill(), { once: true });
+
   await proc.exited;

Then pass an AbortController signal from the defer block and abort it on timeout. Alternatively, you could use Promise.race with a timeout that kills the process.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@plugins/github-workflow/hooks/entry/auto-create-pr.ts` around lines 38 - 69,
The createPr function can leave spawned processes (proc and viewProc) running if
the surrounding context.defer times out; modify createPr to create an
AbortController (or receive an AbortSignal from the defer) and pass its signal
to Bun.spawn calls for both proc and viewProc, and ensure you abort/kill the
controller when the defer timeout triggers (or on Promise.race timeout) so
proc.kill()/viewProc.kill() (or controller.abort()) is invoked to terminate
hanging subprocesses; update the Bun.spawn invocations in createPr to include
the signal option and handle abort errors appropriately so you always clean up
subprocesses on timeout or error.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
plugins/github-workflow/hooks/auto-create-pr.test.ts (1)

56-59: defer options are currently unverified.

At Line 56-Line 59, the mock drops the second defer argument, so the test at Line 166-Line 168 won’t catch regressions where timeout options stop being passed.

Suggested fix
-      defer: vi.fn((fn: () => Promise<unknown>) => {
+      defer: vi.fn((fn: () => Promise<unknown>, _opts?: { timeoutMs?: number }) => {
         deferFn = fn;
         return { type: "defer" };
       }),
@@
     expect(result).toStrictEqual({ type: "defer" });
-    expect(ctx.defer).toHaveBeenCalled();
+    expect(ctx.defer).toHaveBeenCalledWith(
+      expect.any(Function),
+      expect.objectContaining({ timeoutMs: expect.any(Number) }),
+    );

Also applies to: 166-168

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@plugins/github-workflow/hooks/auto-create-pr.test.ts` around lines 56 - 59,
The mock for defer in auto-create-pr.test.ts currently only captures the first
argument and drops the second (timeout options); update the vi.fn mock for defer
to accept both parameters (e.g., (fn, opts)) and store the options in a new
variable (e.g., deferFnOptions) alongside deferFn so the test can inspect them,
and then update the assertion near where defer is expected to be called (the
assertions around the defer usage at lines ~166-168) to verify the captured
options are passed through correctly; refer to the existing mock and the defer
invocation sites to implement and assert the second argument.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@plugins/github-workflow/hooks/auto-create-pr.test.ts`:
- Around line 35-45: The test suite mutates globalThis.Bun via mockBunGlobal
(which captures originalBun) but never restores it; add an afterEach hook that
resets globalThis.Bun back to originalBun and clears or restores any mocked
functions (e.g., restore mockSpawnSync/mockSpawn) so tests do not leak state—use
the captured originalBun from the top-level variable and ensure mockBunGlobal
continues to assign overridden methods only during a test.

---

Nitpick comments:
In `@plugins/github-workflow/hooks/auto-create-pr.test.ts`:
- Around line 56-59: The mock for defer in auto-create-pr.test.ts currently only
captures the first argument and drops the second (timeout options); update the
vi.fn mock for defer to accept both parameters (e.g., (fn, opts)) and store the
options in a new variable (e.g., deferFnOptions) alongside deferFn so the test
can inspect them, and then update the assertion near where defer is expected to
be called (the assertions around the defer usage at lines ~166-168) to verify
the captured options are passed through correctly; refer to the existing mock
and the defer invocation sites to implement and assert the second argument.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 73f00033-ff83-4921-b72a-f927a21da589

📥 Commits

Reviewing files that changed from the base of the PR and between 895b95f and d91ab1d.

📒 Files selected for processing (1)
  • plugins/github-workflow/hooks/auto-create-pr.test.ts

Comment on lines +35 to +45
const originalBun = globalThis.Bun;

function mockBunGlobal(overrides: { spawnSync?: typeof mockSpawnSync; spawn?: typeof mockSpawn }) {
Object.assign(globalThis, {
Bun: {
...originalBun,
spawnSync: overrides.spawnSync ?? mockSpawnSync,
spawn: overrides.spawn ?? mockSpawn,
},
});
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Restore globalThis.Bun and mock state after each test.

At Line 38-Line 44, the suite mutates a global and never restores it. This can pollute later tests and cause order-dependent failures.

Suggested fix
-import { describe, expect, test, vi } from "vitest";
+import { afterEach, describe, expect, test, vi } from "vitest";
@@
 const originalBun = globalThis.Bun;
+
+afterEach(() => {
+  mockExecFileSync.mockReset();
+  mockSpawnSync.mockReset();
+  mockSpawn.mockReset();
+  Object.assign(globalThis, { Bun: originalBun });
+});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@plugins/github-workflow/hooks/auto-create-pr.test.ts` around lines 35 - 45,
The test suite mutates globalThis.Bun via mockBunGlobal (which captures
originalBun) but never restores it; add an afterEach hook that resets
globalThis.Bun back to originalBun and clears or restores any mocked functions
(e.g., restore mockSpawnSync/mockSpawn) so tests do not leak state—use the
captured originalBun from the top-level variable and ensure mockBunGlobal
continues to assign overridden methods only during a test.

masseater and others added 2 commits April 6, 2026 20:26
github.ts, prompt.ts, and index.ts have no tests and were dragging
coverage below the 80% threshold, failing CI across all branches.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Server-side and UI component files have no tests; scoping coverage
to model and lib directories prevents false threshold failures.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant