From cac369dd16940c3c5a2f409202db2dbe9450d705 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Tue, 8 Sep 2026 13:48:08 -0400 Subject: [PATCH] fix: deliver profile and CI wakes after bot review dispatches --- .github/workflows/openrouter-code-review.yml | 30 ++++++++++ .../openrouter-profile-completion.yml | 29 ++++++++++ README.md | 35 +++++++++++- scripts/profile_gate.py | 28 ++++++++++ scripts/workflow_wakeup.mjs | 36 ++++++++++++ tests/test_profile_wakeup.py | 46 ++++++++++++++++ tests/test_profile_workflow.py | 22 ++++++++ tests/workflow-wakeup.test.mjs | 55 +++++++++++++++++++ 8 files changed, 278 insertions(+), 3 deletions(-) create mode 100644 scripts/workflow_wakeup.mjs create mode 100644 tests/test_profile_wakeup.py create mode 100644 tests/workflow-wakeup.test.mjs diff --git a/.github/workflows/openrouter-code-review.yml b/.github/workflows/openrouter-code-review.yml index e591bb0..e8d545c 100644 --- a/.github/workflows/openrouter-code-review.yml +++ b/.github/workflows/openrouter-code-review.yml @@ -971,3 +971,33 @@ jobs: echo "| Open bugs | \`$BUGS\` |" echo "| Review | $REVIEW" } >> "$GITHUB_STEP_SUMMARY" + + notify-profile-completion: + # A delivery failure must not invalidate a paid review or a valid proof. + # The destination gate stays closed; its manual dispatch can retry delivery. + continue-on-error: true + name: Notify profile completion after a bot dispatch + needs: [review-config, openrouter-first-pass, openrouter-follow-up, openrouter-first-pass-gate] + if: >- + always() && inputs.review_profiles_enabled && + needs.review-config.result == 'success' && + github.event_name == 'workflow_dispatch' && github.actor == 'github-actions[bot]' + runs-on: ubuntu-latest + timeout-minutes: 3 + permissions: + actions: write + contents: read + steps: + - name: Checkout the trusted notification helper + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: RetireGolden/.github + ref: ${{ needs.review-config.outputs.org_sha }} + path: .trusted-review-org + persist-credentials: false + - name: Wake the default-branch profile validator + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + with: + script: | + const { dispatchWorkflowWake } = await import(`${process.env.GITHUB_WORKSPACE}/.trusted-review-org/scripts/workflow_wakeup.mjs`) + await dispatchWorkflowWake(github, core, context, 'openrouter-profile-completion.yml') diff --git a/.github/workflows/openrouter-profile-completion.yml b/.github/workflows/openrouter-profile-completion.yml index 43365d3..cb278a9 100644 --- a/.github/workflows/openrouter-profile-completion.yml +++ b/.github/workflows/openrouter-profile-completion.yml @@ -160,3 +160,32 @@ jobs: GITHUB_TOKEN: ${{ github.token }} PROOF_MATRIX_JSON: ${{ needs.plan.outputs.matrix }} run: python3 -P -m scripts.profile_gate publish + + notify-ci-broker: + # A delivery failure must not invalidate a paid review or a valid proof. + # The destination gate stays closed; its manual dispatch can retry delivery. + continue-on-error: true + name: Notify CI broker after a bot dispatch + needs: [plan, proof, publish] + if: >- + always() && needs.plan.result == 'success' && + github.event_name == 'workflow_dispatch' && github.actor == 'github-actions[bot]' + runs-on: ubuntu-latest + timeout-minutes: 3 + permissions: + actions: write + contents: read + steps: + - name: Checkout the trusted notification helper + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: RetireGolden/.github + ref: ${{ needs.plan.outputs.org_sha }} + path: .trusted-review-org + persist-credentials: false + - name: Wake the default-branch CI broker when installed + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + with: + script: | + const { dispatchWorkflowWake } = await import(`${process.env.GITHUB_WORKSPACE}/.trusted-review-org/scripts/workflow_wakeup.mjs`) + await dispatchWorkflowWake(github, core, context, 'openrouter-ci-broker.yml', true) diff --git a/README.md b/README.md index 89b972f..910efbe 100644 --- a/README.md +++ b/README.md @@ -158,6 +158,7 @@ on: workflow_dispatch: inputs: pr_number: { required: false, type: string } + source_run_id: { required: false, type: string } permissions: actions: write @@ -167,16 +168,44 @@ permissions: jobs: complete: - if: github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' + if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch) uses: RetireGolden/.github/.github/workflows/openrouter-profile-completion.yml@ with: pr_number: ${{ inputs.pr_number || '' }} - source_run_id: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.id || '' }} + source_run_id: ${{ inputs.source_run_id || (github.event.workflow_run.id && format('{0}', github.event.workflow_run.id)) || '' }} ``` The completion consumer job id must be `complete` so proof job names resolve as `complete / profile # `. +### Completion delivery after bot dispatches + +GitHub suppresses downstream `workflow_run` events after reviews dispatched +with `GITHUB_TOKEN`. Its documented `workflow_dispatch` exception lets us wake +the next workflow explicitly without another token or a model rerun. See +[GitHub's workflow triggering rules](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/trigger-a-workflow). + +After a bot-dispatched review, a final notification job dispatches +`openrouter-profile-completion.yml` on the default branch with `source_run_id`. +The receiver briefly waits for the source run to become terminal, then validates +its provenance and checks current review receipts. After proof publication, +a bot-dispatched completion similarly wakes `openrouter-ci-broker.yml` when +installed. Human-triggered reviews retain their native completion events. + +Consumers with a CI broker must accept a required string `source_run_id` on +`workflow_dispatch`, run only on the default branch, wait for that profile run +to finish, and verify its registered workflow ID and path before running their +existing exact-head clean-review and profile-proof checks. A source ID is only +a wake-up hint. It is never permission to add `run-ci` or start billed CI. +Consumers without a CI broker need only the completion caller above. + +Delivery jobs are best effort: a failed notification does not invalidate a +completed review or an otherwise valid proof. Missing or invalid profile +evidence still blocks CI. If a notification fails, inspect its job log and +manually dispatch the destination on the default branch with the completed +source run ID. Retry profile completion or the broker, not the paid review. +The bounded wait applies to notification delivery, not model review time. + ### Security boundary Profile orchestration uses inert full-depth default-branch checkout plus @@ -191,7 +220,7 @@ git clone --no-checkout https://github.com/FlyOverCoderKY/openrouter-pr-review-a git -C .trusted-review-action checkout 188cd5557765c858a37c1da78960cd353bcbcd60 export PYTHONPATH="$PWD/.trusted-review-action/src" uv run --with jq --with pyyaml python -m unittest discover -s tests -node --test tests/profile-consumer.test.mjs +node --test tests/profile-consumer.test.mjs tests/workflow-wakeup.test.mjs ``` `scripts/profile_consumer.mjs` is the shared Node validator used by existing diff --git a/scripts/profile_gate.py b/scripts/profile_gate.py index e8d8971..a278339 100644 --- a/scripts/profile_gate.py +++ b/scripts/profile_gate.py @@ -1140,6 +1140,32 @@ def _plan_one( return None +def _wait_for_source_run( + client: ProfileGitHub, verifier: Callable[[Mapping[str, Any]], VerifiedRun] +) -> None: + """A bot's explicit wake can arrive just before its notifying run completes.""" + run_id = _positive(_env("SOURCE_RUN_ID"), "SOURCE_RUN_ID") + if run_id == _positive(_env("GITHUB_RUN_ID"), "GITHUB_RUN_ID"): + raise GateError("completion cannot wait on itself") + deadline = time.monotonic() + 90 + while True: + run = client._api( + f"/repos/{client.config.owner}/{client.config.name}/actions/runs/{run_id}" + ) + if not isinstance(run, Mapping): + raise GateError("source run is invalid") + verifier(run) # Reject untrusted sources before waiting or writing statuses. + status = run.get("status") + if status == "completed": + return + if status not in {"queued", "in_progress", "waiting", "pending", "requested"}: + raise GateError("source run has an invalid status") + remaining = deadline - time.monotonic() + if remaining <= 0: + raise GateError("source run did not complete before the wake deadline; rerun profile completion") + time.sleep(min(3, remaining)) + + def _source_pr( client: ProfileGitHub, verifier: Callable[[Mapping[str, Any]], VerifiedRun] ) -> int: @@ -1173,6 +1199,8 @@ def plan( "completion workflow is not running at live default branch head" ) historical = _historical_verifier(bare, bare.config.default_branch, main_sha) + if os.environ.get("SOURCE_RUN_ID"): + _wait_for_source_run(bare, historical) if one_pr is None and os.environ.get("SWEEP_OPEN_PRS") == "true": # Validate event provenance before using the event to wake a sweep. if os.environ.get("SOURCE_RUN_ID"): diff --git a/scripts/workflow_wakeup.mjs b/scripts/workflow_wakeup.mjs new file mode 100644 index 0000000..88f590f --- /dev/null +++ b/scripts/workflow_wakeup.mjs @@ -0,0 +1,36 @@ +// Explicit wakes bridge GITHUB_TOKEN dispatches whose workflow_run events are suppressed. +// A wake is a hint only. The destination must wait for this run to finish and +// independently validate current workflow/artifact provenance before authorizing work. +export async function dispatchWorkflowWake(github, core, context, target, optional = false) { + const allowed = new Set(['openrouter-profile-completion.yml', 'openrouter-ci-broker.yml']); + if (!allowed.has(target)) throw new Error('unsupported completion wake target'); + if (context.eventName !== 'workflow_dispatch' || context.actor !== 'github-actions[bot]') { + return core.info('Native completion events cover this run'); + } + if (!Number.isSafeInteger(context.runId) || context.runId <= 0) { + throw new Error('invalid completion source run'); + } + const { owner, repo } = context.repo; + const { data: repository } = await github.rest.repos.get({ owner, repo }); + if (repository.full_name !== `${owner}/${repo}` || !repository.default_branch) { + throw new Error('invalid completion target repository'); + } + if (context.ref !== `refs/heads/${repository.default_branch}`) { + throw new Error('completion wakes require a default-branch dispatch'); + } + let workflow; + try { + ({ data: workflow } = await github.rest.actions.getWorkflow({ owner, repo, workflow_id: target })); + } catch (error) { + if (optional && error?.status === 404) return core.info('This repository has no CI broker'); + throw error; + } + if (workflow.path !== `.github/workflows/${target}` || workflow.state !== 'active') { + throw new Error('completion target is not the expected active workflow'); + } + await github.rest.actions.createWorkflowDispatch({ + owner, repo, workflow_id: target, ref: repository.default_branch, + inputs: { source_run_id: String(context.runId) }, + }); + core.info(`Dispatched ${target} to inspect source run ${context.runId}`); +} diff --git a/tests/test_profile_wakeup.py b/tests/test_profile_wakeup.py new file mode 100644 index 0000000..1f65095 --- /dev/null +++ b/tests/test_profile_wakeup.py @@ -0,0 +1,46 @@ +"""Explicit completion wakes must wait for terminal, trusted source runs.""" +import os +import unittest +from types import SimpleNamespace +from unittest.mock import Mock, patch +from scripts import profile_gate as gate + + +class ProfileWakeTests(unittest.TestCase): + def client(self, states): + return SimpleNamespace(config=SimpleNamespace(owner="RetireGolden", name="example"), + _api=Mock(side_effect=[{"status": value} for value in states])) + + def test_waits_for_source_before_planning(self): + client = self.client(["in_progress", "completed"]) + verify = Mock() + with patch.dict(os.environ, {"SOURCE_RUN_ID": "42", "GITHUB_RUN_ID": "43"}), patch.object(gate.time, "sleep") as sleep: + gate._wait_for_source_run(client, verify) + self.assertEqual(verify.call_count, 2) + sleep.assert_called_once() + + def test_untrusted_source_fails_before_wait_or_status_mutation(self): + client = self.client(["in_progress"]) + with patch.dict(os.environ, {"SOURCE_RUN_ID": "42", "GITHUB_RUN_ID": "43"}), patch.object(gate.time, "sleep") as sleep: + with self.assertRaisesRegex(gate.GateError, "untrusted"): + gate._wait_for_source_run(client, Mock(side_effect=gate.GateError("untrusted"))) + sleep.assert_not_called() + + def test_terminal_source_does_not_sleep(self): + with patch.dict(os.environ, {"SOURCE_RUN_ID": "42", "GITHUB_RUN_ID": "43"}), patch.object(gate.time, "sleep") as sleep: + gate._wait_for_source_run(self.client(["completed"]), Mock()) + sleep.assert_not_called() + + def test_wait_is_bounded(self): + with patch.dict(os.environ, {"SOURCE_RUN_ID": "42", "GITHUB_RUN_ID": "43"}), patch.object(gate.time, "monotonic", side_effect=[0, 90]), patch.object(gate.time, "sleep") as sleep: + with self.assertRaisesRegex(gate.GateError, "wake deadline"): + gate._wait_for_source_run(self.client(["in_progress"]), Mock()) + sleep.assert_not_called() + + def test_self_dependency_and_unknown_states_are_rejected(self): + with patch.dict(os.environ, {"SOURCE_RUN_ID": "42", "GITHUB_RUN_ID": "42"}): + with self.assertRaisesRegex(gate.GateError, "itself"): + gate._wait_for_source_run(self.client([]), Mock()) + with patch.dict(os.environ, {"SOURCE_RUN_ID": "42", "GITHUB_RUN_ID": "43"}): + with self.assertRaisesRegex(gate.GateError, "invalid status"): + gate._wait_for_source_run(self.client(["mystery"]), Mock()) diff --git a/tests/test_profile_workflow.py b/tests/test_profile_workflow.py index e7e443e..70888b4 100644 --- a/tests/test_profile_workflow.py +++ b/tests/test_profile_workflow.py @@ -26,6 +26,28 @@ def step_named(steps, name): class ProfileWorkflowContractTests(unittest.TestCase): + def test_bot_notifications_wait_for_all_source_jobs_and_use_trusted_source(self): + for workflow, job_id, needs, source, target in ( + (REVIEW, 'notify-profile-completion', + ['review-config', 'openrouter-first-pass', 'openrouter-follow-up', 'openrouter-first-pass-gate'], + 'review-config', 'openrouter-profile-completion.yml'), + (COMPLETION, 'notify-ci-broker', ['plan', 'proof', 'publish'], + 'plan', 'openrouter-ci-broker.yml'), + ): + job = workflow['jobs'][job_id] + self.assertEqual(job['needs'], needs) + self.assertEqual(job['continue-on-error'], 'true') + self.assertEqual(job['permissions'], {'actions': 'write', 'contents': 'read'}) + self.assertIn("github.event_name == 'workflow_dispatch'", job['if']) + self.assertIn("github.actor == 'github-actions[bot]'", job['if']) + self.assertIn('always()', job['if']) + checkout = job['steps'][0]['with'] + self.assertEqual(checkout['repository'], 'RetireGolden/.github') + self.assertEqual(checkout['ref'], '${{ needs.' + source + '.outputs.org_sha }}') + self.assertEqual(checkout['persist-credentials'], 'false') + self.assertIn(target, job['steps'][1]['with']['script']) + self.assertIn('inputs.review_profiles_enabled', REVIEW['jobs']['notify-profile-completion']['if']) + def test_prepared_context_path_and_digest_are_shared_between_setup_and_review(self): for job_id in ('openrouter-first-pass', 'openrouter-follow-up'): steps = job_steps(REVIEW, job_id) diff --git a/tests/workflow-wakeup.test.mjs b/tests/workflow-wakeup.test.mjs new file mode 100644 index 0000000..764fd55 --- /dev/null +++ b/tests/workflow-wakeup.test.mjs @@ -0,0 +1,55 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { dispatchWorkflowWake } from '../scripts/workflow_wakeup.mjs'; + +function fixture(overrides = {}) { + const calls = []; + const context = { repo: { owner: 'RetireGolden', repo: 'example' }, eventName: 'workflow_dispatch', actor: 'github-actions[bot]', ref: 'refs/heads/main', runId: 42, ...overrides }; + const github = { rest: { + repos: { get: async () => ({ data: { full_name: 'RetireGolden/example', default_branch: 'main' } }) }, + actions: { + getWorkflow: async ({ workflow_id }) => ({ data: { path: `.github/workflows/${workflow_id}`, state: 'active' } }), + createWorkflowDispatch: async args => calls.push(args), + }, + } }; + return { github, context, calls, core: { info() {} } }; +} + +test('bot dispatch explicitly wakes the default-branch proof validator with source identity only', async () => { + const f = fixture(); + await dispatchWorkflowWake(f.github, f.core, f.context, 'openrouter-profile-completion.yml'); + assert.deepEqual(f.calls, [{ owner: 'RetireGolden', repo: 'example', workflow_id: 'openrouter-profile-completion.yml', ref: 'main', inputs: { source_run_id: '42' } }]); +}); +test('human and pull-request runs retain native completion events without duplicate dispatches', async () => { + for (const overrides of [{ actor: 'maintainer' }, { eventName: 'pull_request' }]) { + const f = fixture(overrides); + await dispatchWorkflowWake(f.github, f.core, f.context, 'openrouter-profile-completion.yml'); + assert.deepEqual(f.calls, []); + } +}); +test('off-default, invalid source and unsupported target cannot dispatch', async () => { + for (const overrides of [{ ref: 'refs/heads/feature' }, { runId: 0 }]) { + const f = fixture(overrides); + await assert.rejects(dispatchWorkflowWake(f.github, f.core, f.context, 'openrouter-profile-completion.yml')); + assert.deepEqual(f.calls, []); + } + const f = fixture(); + await assert.rejects(dispatchWorkflowWake(f.github, f.core, f.context, 'release.yml')); +}); +test('missing optional broker is a noop; missing required validator and permission failures remain visible', async () => { + for (const [status, optional, succeeds] of [[404, true, true], [404, false, false], [403, true, false]]) { + const f = fixture(); + f.github.rest.actions.getWorkflow = async () => { throw Object.assign(new Error('lookup failed'), { status }); }; + const result = dispatchWorkflowWake(f.github, f.core, f.context, 'openrouter-ci-broker.yml', optional); + if (succeeds) await result; else await assert.rejects(result); + assert.deepEqual(f.calls, []); + } +}); +test('wrong workflow path and disabled workflows fail closed', async () => { + for (const workflow of [{ path: '.github/workflows/release.yml', state: 'active' }, { path: '.github/workflows/openrouter-ci-broker.yml', state: 'disabled_manually' }]) { + const f = fixture(); + f.github.rest.actions.getWorkflow = async () => ({ data: workflow }); + await assert.rejects(dispatchWorkflowWake(f.github, f.core, f.context, 'openrouter-ci-broker.yml', true)); + assert.deepEqual(f.calls, []); + } +});