Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .github/workflows/openrouter-code-review.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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')
29 changes: 29 additions & 0 deletions .github/workflows/openrouter-profile-completion.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
35 changes: 32 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ on:
workflow_dispatch:
inputs:
pr_number: { required: false, type: string }
source_run_id: { required: false, type: string }

permissions:
actions: write
Expand All @@ -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@<ORG_WORKFLOW_SHA>
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 #<n> <digest>`.

### 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
Expand All @@ -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
Expand Down
28 changes: 28 additions & 0 deletions scripts/profile_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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"):
Expand Down
36 changes: 36 additions & 0 deletions scripts/workflow_wakeup.mjs
Original file line number Diff line number Diff line change
@@ -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}`);
}
46 changes: 46 additions & 0 deletions tests/test_profile_wakeup.py
Original file line number Diff line number Diff line change
@@ -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())
22 changes: 22 additions & 0 deletions tests/test_profile_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
55 changes: 55 additions & 0 deletions tests/workflow-wakeup.test.mjs
Original file line number Diff line number Diff line change
@@ -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, []);
}
});