feat(#2377): forge-webhook-triggered config-PR merge flow

Replace the request_merge_config_pr MCP tool with a Forgejo
pull_request webhook on the agent-configs org. Agents now open a
config PR normally; hive-c0re auto-queues the MergeConfigPr approval
from the webhook event — no extra tool call needed.

Changes:
- dashboard/webhook.rs: add POST /webhook/config-pr handler
  - parses Forgejo pull_request payload (opened/synchronize)
  - strips agent-configs/<agent> prefix to extract agent name
  - calls submit_merge_config_pr → queues dashboard approval card
  - always 200 to prevent Forgejo retries; errors logged at warn
- dashboard/mod.rs: wire /webhook/config-pr route
- forge/mod.rs: add ensure_config_pr_webhook() — idempotent org-level
  hook registration on agent-configs at startup; CONFIG_ORG now
  pub(crate) for webhook handler
- main.rs: call ensure_config_pr_webhook alongside knowledge webhook
- socket_server/config_approvals.rs: drop handle_request_merge_config_pr;
  make submit_merge_config_pr pub(crate) for webhook handler
- socket_server/mod.rs: re-export submit_merge_config_pr; drop dispatch arm
- hive-sh4re/src/lib.rs: remove AgentRequest::RequestMergeConfigPr
  wire type; drop from ToolGroup::Approvals tool list
- hive-ag3nt/src/mcp/: drop request_merge_config_pr tool + args struct
- docs: update approvals.md (webhook trigger), conventions.md (tool
  group), agent-hierarchy.md, tools/lifecycle.md

Hardening from #2375-merge-config-pr-hardening branch preserved:
- pr_is_open check at queue time (rejects closed/merged PRs)
- atomic fetched_sha INSERT via submit_kind(fetched_sha: Some(&sha))

Approve-handler machinery unchanged (run_merge_config_pr,
ff_push_to_main, fetch_pr_head_into_applied, mark_pr_merged).
This commit is contained in:
atlas 2026-07-11 10:50:24 +02:00 committed by mara
commit d5a81f9195
14 changed files with 255 additions and 163 deletions

View file

@ -160,9 +160,10 @@ pub async fn serve(port: u16, coord: Arc<Coordinator>) -> Result<()> {
post(schedules::post_rebuild_queue_cancel),
)
.route("/webhook/knowledge", post(webhook::post_webhook_knowledge))
.route("/webhook/config-pr", post(webhook::post_webhook_config_pr))
// Backend routes — the frontend calls these `/api/` paths. The
// transitional bare top-level aliases were removed once the
// frontend migrated. `/webhook/knowledge` keeps its own prefix
// frontend migrated. `/webhook/*` keeps its own prefix
// (forge-driven, not the SPA).
.route("/api/approve/{id}", post(approvals::post_approve))
.route("/api/deny/{id}", post(approvals::post_deny))

View file

@ -1,15 +1,27 @@
//! Forgejo push-webhook endpoint for the `internal/knowledge` repo.
//! Forgejo webhook endpoints.
//!
//! Loopback-only; on a push to `main` of the knowledge repo it triggers a
//! read-only `git pull` on the local clone so agents see up-to-date
//! documents on their next turn.
//! - **`/webhook/knowledge`** — push events on `internal/knowledge` trigger a
//! `git pull` on the local clone so agents see up-to-date docs.
//! - **`/webhook/config-pr`** — pull_request events on any `agent-configs/*`
//! repo queue a [`hive_sh4re::ApprovalKind::MergeConfigPr`] approval row
//! so the operator can review + approve the merge from the dashboard.
//!
//! Both endpoints are loopback-only (the axum listener binds
//! `127.0.0.1:<port>`) and have no signature verification (the risk is low:
//! loopback access implies host compromise already, and the config-PR path
//! still requires the operator to approve on the dashboard).
use axum::{
extract::State,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde::Deserialize;
use super::AppState;
// ── knowledge webhook ──────────────────────────────────────────────────────────
/// Minimal Forgejo push-webhook payload — only the fields we care about.
#[derive(Deserialize)]
pub(super) struct PushWebhookPayload {
@ -62,3 +74,133 @@ pub(super) async fn post_webhook_knowledge(
});
(StatusCode::OK, "ok").into_response()
}
// ── config-PR webhook ──────────────────────────────────────────────────────────
/// Minimal Forgejo pull_request-webhook payload.
///
/// Forgejo fires this for actions: `opened`, `closed`, `reopened`,
/// `synchronize`, `assigned`, `unassigned`, `label_updated`,
/// `label_cleared`, `milestoned`, `demilestoned`, `review_requested`,
/// `review_request_removed`, `auto_merge_enabled`, `auto_merge_disabled`.
/// We only act on `opened` and `synchronize`.
#[derive(Deserialize)]
pub(super) struct PrWebhookPayload {
/// What triggered this event (`opened`, `closed`, `synchronize`, …).
action: Option<String>,
/// PR index on the repo.
number: Option<u64>,
pull_request: Option<PrWebhookPr>,
repository: Option<PrWebhookRepo>,
}
#[derive(Deserialize)]
struct PrWebhookPr {
head: Option<PrWebhookHead>,
}
#[derive(Deserialize)]
struct PrWebhookHead {
sha: Option<String>,
}
#[derive(Deserialize)]
struct PrWebhookRepo {
full_name: Option<String>,
}
/// POST `/webhook/config-pr` — Forgejo pull_request webhook for
/// `agent-configs/*` repos.
///
/// On `opened` or `synchronize` for an `agent-configs/<agent>` PR:
/// fetches the current PR head sha, queues a `MergeConfigPr` approval row,
/// and emits the `ApprovalAdded` event so the dashboard card appears
/// immediately.
///
/// All other actions (closed, label changes, etc.) are silently ignored —
/// the operator can deny a pending approval if the PR is later closed.
///
/// Always returns HTTP 200 (even on queue failure) so Forgejo does not
/// retry the delivery. Failures are logged at `warn` level.
///
/// Expected Forgejo webhook configuration:
/// - URL: `http://127.0.0.1:<dashboard_port>/webhook/config-pr`
/// - Content type: `application/json`
/// - Events: "Pull Request" only
/// - Organisation: `agent-configs` (org-level hook covers all config repos)
///
/// hive-c0re registers this hook automatically at startup via
/// [`crate::forge::ensure_config_pr_webhook`].
pub(super) async fn post_webhook_config_pr(
State(state): State<AppState>,
axum::extract::Json(payload): axum::extract::Json<PrWebhookPayload>,
) -> Response {
let action = payload.action.as_deref().unwrap_or("");
// Only act on newly-opened or force-updated PRs.
if action != "opened" && action != "synchronize" {
tracing::debug!(action, "webhook/config-pr: ignoring action");
return (StatusCode::OK, "ignored").into_response();
}
let full_name = payload
.repository
.as_ref()
.and_then(|r| r.full_name.as_deref())
.unwrap_or("");
// Expect `agent-configs/<agent>`.
let agent = match full_name.strip_prefix(&format!("{}/", crate::forge::CONFIG_ORG)) {
Some(name) if !name.is_empty() && !name.contains('/') => name,
_ => {
tracing::debug!(
full_name,
"webhook/config-pr: ignoring non-config-repo event"
);
return (StatusCode::OK, "ignored").into_response();
}
};
let pr_number = match payload.number {
Some(n) if n > 0 => n,
_ => {
tracing::warn!(full_name, "webhook/config-pr: missing or zero PR number");
return (StatusCode::OK, "ignored").into_response();
}
};
// The payload already carries the head sha — use it as an early hint for
// logging, but the canonical sha comes from `submit_merge_config_pr`'s
// fresh forge API call so we don't trust a potentially-stale payload sha.
let payload_sha = payload
.pull_request
.as_ref()
.and_then(|pr| pr.head.as_ref())
.and_then(|h| h.sha.as_deref())
.unwrap_or("<unknown>");
tracing::info!(
%full_name, %agent, %pr_number, %payload_sha, %action,
"webhook/config-pr: queuing MergeConfigPr approval"
);
// Queue the approval. The description surfaces the action and PR number
// on the dashboard card so the operator has context without opening the
// forge PR.
let description = format!("PR #{pr_number} on {full_name} ({action})");
if let Err(e) = crate::socket_server::submit_merge_config_pr(
&state.coord,
agent,
pr_number,
Some(&description),
"forge", // submitter — identifies the webhook path in the audit trail
)
.await
{
tracing::warn!(
%agent, %pr_number, error = ?e,
"webhook/config-pr: failed to queue MergeConfigPr approval"
);
}
(StatusCode::OK, "ok").into_response()
}