diff --git a/README.md b/README.md index b4f08dd..ab30d24 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ AI が実装し、人が承認する。`develop` へは必須チェックが通 | `.github/workflows/agent-apm-bump.yml` | kit の新しいタグに合わせて、`apm.yml` のスキルの版を上げ、`apm.lock.yaml` を更新する PR を作る再利用ワークフロー (Dependabot の APM 版。書き換えは `scripts/ci/apm-bump.mjs`) | `uses: ...@` | | `.github/workflows/agent-release-summary.yml` | リリースの PR (`develop → main`) の本文に、確認事項の要約 (含まれる Issue、マイグレーション、認証・依存・CI の変更) を書く再利用ワークフロー (要約は `scripts/ci/release-summary.mjs`、設定の例は `templates/.github/release-summary.json`) | `uses: ...@` | | `actions/changed/` | 指定したパスに変更があるかを返すアクション (変更がないときに重いジョブを飛ばす) | `uses: ...@` | +| `actions/delete-merged-branch/` | マージした PR の head のブランチを消すアクション。後片付けの後に置き、`delete_branch_on_merge: false` と組にする (判定は `scripts/ci/delete-merged-branch.mjs`、呼ぶジョブに `contents: write` が要る) | `uses: ...@` | | `templates/AGENTS.section.md` | `AGENTS.md` に貼る運用の節 | コピー | | `templates/.github/branch-protection.json` | ブランチ保護の必須チェックの設定の例 | コピー | | `templates/.claude/settings.json` | 危険なコマンドの deny | コピー | diff --git a/actions/delete-merged-branch/action.yml b/actions/delete-merged-branch/action.yml new file mode 100644 index 0000000..7cfc32d --- /dev/null +++ b/actions/delete-merged-branch/action.yml @@ -0,0 +1,26 @@ +name: Delete merged branch +description: >- + マージした PR の head のブランチを消す。後片付け (Preview の削除など) のステップの後に置き、 + 後片付けに失敗したらブランチが残って気づけるようにする。マージせずに閉じた PR、守るブランチ、 + fork の PR のブランチは消さない。もう消えているときは成功にする。 + pull_request (closed) のイベントで呼び、ジョブに contents: write を与えること。checkout は要らない。 + +inputs: + protected-branches: + description: 消さないブランチ (空白区切り) + required: false + default: develop main + token: + description: contents の書き込みを持つ token + required: false + default: ${{ github.token }} + +runs: + using: composite + steps: + - shell: bash + env: + GH_TOKEN: ${{ inputs.token }} + PROTECTED_BRANCHES: ${{ inputs.protected-branches }} + SCRIPT: ${{ github.action_path }}/../../scripts/ci/delete-merged-branch.mjs + run: node "$SCRIPT" diff --git a/docs/SETUP.md b/docs/SETUP.md index 819ac83..eb38797 100644 --- a/docs/SETUP.md +++ b/docs/SETUP.md @@ -85,6 +85,24 @@ dependencies: - `main`: 上に加えて、管理者にも必須チェックを強制する (`develop` では、管理者は迂回できる)。`develop → main` の PR は人がマージする。 - `agent/*`・`feature/*` は保護しない。 - リポジトリの設定で、自動マージを許可し、マージの後にブランチを消す。消したくないときは、設定ファイルで `"delete_branch_on_merge": false` にする (例: CI が後片付けを済ませてから、自分でブランチを消す)。 +- 後片付けの後でブランチを消すには、アクションの `actions/delete-merged-branch` を、後片付けのステップの後に置く。後片付けに失敗すればこのステップまで進まず、ブランチが残るので気づける。消すのはマージした PR の head のブランチだけで、マージせずに閉じた PR、守るブランチ (入力の `protected-branches`、既定 `develop main`)、fork の PR のブランチは消さない。もう消えていれば成功にし、ほかのエラー (権限がないなど) で失敗する。呼ぶジョブには `contents: write` が要る。checkout は要らない。 + + ```yaml + # .github/workflows/cleanup.yml + on: + pull_request: + types: [closed] + jobs: + cleanup: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + # - (Preview の削除などの後片付け) + - uses: HyuuNyackman/agent-dev-kit/actions/delete-merged-branch@<コミット SHA> # v1.x.y + with: + protected-branches: develop main # 省略すると develop main + ``` 適用は、スキルの `branch-protection` で行う ([`skills/branch-protection/SKILL.md`](../skills/branch-protection/SKILL.md))。`apm.yml` に `HyuuNyackman/agent-dev-kit/skills/branch-protection` を足して `apm install` し、必須チェックの名前を `.github/branch-protection.json` (例: `templates/.github/branch-protection.json`) に書いて、リポジトリの管理者が手元で実行する。CI からは実行しない。 diff --git a/scripts/ci/delete-merged-branch.mjs b/scripts/ci/delete-merged-branch.mjs new file mode 100644 index 0000000..aac6844 --- /dev/null +++ b/scripts/ci/delete-merged-branch.mjs @@ -0,0 +1,78 @@ +// マージした PR の head のブランチを消す。後片付け (Preview の削除など) の後のステップで呼ぶ。 +// +// node scripts/ci/delete-merged-branch.mjs +// +// 環境変数: +// GITHUB_EVENT_PATH pull_request (closed) のイベントの JSON +// GITHUB_REPOSITORY このリポジトリ (owner/name) +// PROTECTED_BRANCHES 消さないブランチ (空白区切り、既定 `develop main`) +// GH_TOKEN contents: write を持つ token (gh が読む) +// +// 消さないもの: マージせずに閉じた PR、守るブランチ、fork の PR (head が別のリポジトリ)。 +// もう消えている (Reference does not exist) ときは成功。それ以外のエラーで失敗する。 +import { execFile } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import { pathToFileURL } from 'node:url'; + +export const DEFAULT_PROTECTED = ['develop', 'main']; + +/** 空白区切りの文字列を、ブランチ名の配列にする。空なら既定。 */ +export function parseProtected(value) { + const names = (value ?? '').split(/\s+/).filter(Boolean); + return names.length > 0 ? names : DEFAULT_PROTECTED; +} + +/** イベントの PR から、消すかを決める。{ delete, ref, reason } を返す。 */ +export function decide({ pullRequest, repo, protectedBranches = DEFAULT_PROTECTED }) { + if (!pullRequest) return { delete: false, reason: 'PR のイベントではありません。' }; + const ref = pullRequest.head?.ref ?? ''; + if (!pullRequest.merged) return { delete: false, ref, reason: `マージせずに閉じた PR です: ${ref}` }; + if (!ref) return { delete: false, ref, reason: 'head のブランチがわかりません。' }; + const headRepo = pullRequest.head?.repo?.full_name; + if (headRepo !== repo) return { delete: false, ref, reason: `fork の PR です: ${headRepo ?? '(消えた fork)'}:${ref}` }; + if (protectedBranches.includes(ref)) return { delete: false, ref, reason: `守るブランチです: ${ref}` }; + return { delete: true, ref, reason: `マージした PR のブランチです: ${ref}` }; +} + +/** ref を消す API のパス。ブランチ名の `/` は区切りのまま残す。 */ +export function refPath(repo, ref) { + return `repos/${repo}/git/refs/heads/${ref.split('/').map(encodeURIComponent).join('/')}`; +} + +/** + * ブランチを消す。deleteRef(path) は { ok, output } を返す関数 (既定は gh api)。 + * { ok, message } を返す。もう消えているときは ok。 + */ +export async function deleteBranch({ repo, ref, deleteRef = ghDelete }) { + const { ok, output } = await deleteRef(refPath(repo, ref)); + if (ok) return { ok: true, message: `消した: ${ref}` }; + if (/Reference does not exist/.test(output)) return { ok: true, message: `もう消えている: ${ref}` }; + return { ok: false, message: `消せなかった: ${ref}\n${output}` }; +} + +function ghDelete(path) { + return new Promise((resolve) => { + execFile('gh', ['api', '-X', 'DELETE', path], (error, stdout, stderr) => { + resolve({ ok: !error, output: `${stdout}${stderr}`.trim() || String(error?.message ?? '') }); + }); + }); +} + +async function main() { + const event = JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8')); + const repo = process.env.GITHUB_REPOSITORY; + const decision = decide({ + pullRequest: event.pull_request, + repo, + protectedBranches: parseProtected(process.env.PROTECTED_BRANCHES), + }); + if (!decision.delete) { + console.log(`消さない: ${decision.reason}`); + return; + } + const result = await deleteBranch({ repo, ref: decision.ref }); + console.log(result.message); + if (!result.ok) process.exit(1); +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) await main(); diff --git a/scripts/ci/delete-merged-branch.test.mjs b/scripts/ci/delete-merged-branch.test.mjs new file mode 100644 index 0000000..c8c5ce8 --- /dev/null +++ b/scripts/ci/delete-merged-branch.test.mjs @@ -0,0 +1,83 @@ +// node --test scripts/ci/ で実行する (jest の対象外)。 +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { decide, deleteBranch, parseProtected, refPath } from './delete-merged-branch.mjs'; + +const REPO = 'my-org/my-project'; + +function pr({ merged = true, ref = 'feature/x', headRepo = REPO } = {}) { + return { merged, head: { ref, repo: headRepo === null ? null : { full_name: headRepo } } }; +} + +test('マージした PR、head が feature/x: 消す', () => { + const d = decide({ pullRequest: pr(), repo: REPO }); + assert.equal(d.delete, true); + assert.equal(d.ref, 'feature/x'); +}); + +test('マージせずに閉じた PR: 消さない', () => { + assert.equal(decide({ pullRequest: pr({ merged: false }), repo: REPO }).delete, false); +}); + +test('head が develop: 消さない', () => { + assert.equal(decide({ pullRequest: pr({ ref: 'develop' }), repo: REPO }).delete, false); + assert.equal(decide({ pullRequest: pr({ ref: 'main' }), repo: REPO }).delete, false); +}); + +test('守るブランチは入力で変えられる', () => { + const protectedBranches = parseProtected('main release'); + assert.deepEqual(protectedBranches, ['main', 'release']); + assert.equal(decide({ pullRequest: pr({ ref: 'release' }), repo: REPO, protectedBranches }).delete, false); + assert.equal(decide({ pullRequest: pr({ ref: 'develop' }), repo: REPO, protectedBranches }).delete, true); +}); + +test('守るブランチの入力が空なら develop main', () => { + assert.deepEqual(parseProtected(''), ['develop', 'main']); + assert.deepEqual(parseProtected(undefined), ['develop', 'main']); +}); + +test('fork の PR: 消さない', () => { + assert.equal(decide({ pullRequest: pr({ headRepo: 'someone/my-project' }), repo: REPO }).delete, false); + assert.equal(decide({ pullRequest: pr({ headRepo: null }), repo: REPO }).delete, false); +}); + +test('PR のイベントでなければ消さない', () => { + assert.equal(decide({ pullRequest: undefined, repo: REPO }).delete, false); +}); + +test('ref のパスは / を残し、ほかの文字はエンコードする', () => { + assert.equal(refPath(REPO, 'feature/abc-12'), `repos/${REPO}/git/refs/heads/feature/abc-12`); + assert.equal(refPath(REPO, 'a#b'), `repos/${REPO}/git/refs/heads/a%23b`); +}); + +test('消せたら成功', async () => { + let called; + const r = await deleteBranch({ + repo: REPO, + ref: 'feature/x', + deleteRef: async (path) => ((called = path), { ok: true, output: '' }), + }); + assert.equal(r.ok, true); + assert.equal(called, `repos/${REPO}/git/refs/heads/feature/x`); +}); + +test('もう消えている: 成功', async () => { + const r = await deleteBranch({ + repo: REPO, + ref: 'feature/x', + deleteRef: async () => ({ ok: false, output: 'gh: Reference does not exist (HTTP 422)' }), + }); + assert.equal(r.ok, true); + assert.match(r.message, /もう消えている/); +}); + +test('権限がない (403): 失敗', async () => { + const r = await deleteBranch({ + repo: REPO, + ref: 'feature/x', + deleteRef: async () => ({ ok: false, output: 'gh: Resource not accessible by integration (HTTP 403)' }), + }); + assert.equal(r.ok, false); + assert.match(r.message, /HTTP 403/); +});