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:
parent
96eda4ed6b
commit
d5a81f9195
14 changed files with 255 additions and 163 deletions
|
|
@ -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))
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -69,7 +69,7 @@ pub(crate) fn forge_git_url(token: &str, repo: &str) -> String {
|
|||
/// reach *another* agent's config. `main` is fast-forward-only — hive-c0re
|
||||
/// never force-pushes; the `push_config` mirror runs best-effort until the
|
||||
/// PR-merge flow retires it.
|
||||
const CONFIG_ORG: &str = "agent-configs";
|
||||
pub(crate) const CONFIG_ORG: &str = "agent-configs";
|
||||
/// Forgejo org hosting the operator-curated shared docs/skills repo
|
||||
/// that every agent gets read-only access to. Agents use it as a
|
||||
/// common reference without the operator having to bake content into
|
||||
|
|
@ -294,3 +294,70 @@ pub async fn ensure_all() {
|
|||
sync_agent(name, core_token.as_deref()).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Ensure a Forgejo pull_request org-webhook for `agent-configs` exists and
|
||||
/// points at hive-c0re's `/webhook/config-pr` endpoint. Idempotent — lists
|
||||
/// existing hooks first and skips creation when one is already targeting the
|
||||
/// correct URL. `dashboard_port` is the TCP port hive-c0re's dashboard listens
|
||||
/// on (default 7000); the webhook URL is
|
||||
/// `http://127.0.0.1:<port>/webhook/config-pr`.
|
||||
///
|
||||
/// An org-level hook covers every repo in `agent-configs` automatically,
|
||||
/// so no per-repo setup is needed as new agents are provisioned.
|
||||
///
|
||||
/// Called at startup alongside `knowledge::ensure_webhook`. No-op when the
|
||||
/// core token is absent (forge not yet provisioned).
|
||||
pub async fn ensure_config_pr_webhook(core_token: &str, dashboard_port: u16) -> Result<()> {
|
||||
use forgejo_api::structs::{CreateHookOption, CreateHookOptionConfig, CreateHookOptionType};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const HTTP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
|
||||
let target_url = format!("http://127.0.0.1:{dashboard_port}/webhook/config-pr");
|
||||
let client = api(core_token)?;
|
||||
|
||||
// List existing org hooks — skip creation if ours is already there.
|
||||
// Best-effort: a listing failure falls through to the create attempt.
|
||||
let listed = tokio::time::timeout(HTTP_TIMEOUT, client.org_list_hooks(CONFIG_ORG).all())
|
||||
.await
|
||||
.map_err(anyhow::Error::from)
|
||||
.and_then(|r| r.map_err(anyhow::Error::from));
|
||||
match listed {
|
||||
Ok(hooks) => {
|
||||
let already_exists = hooks.iter().any(|h| {
|
||||
h.config
|
||||
.as_ref()
|
||||
.and_then(|c| c.get("url"))
|
||||
.map(String::as_str)
|
||||
== Some(target_url.as_str())
|
||||
});
|
||||
if already_exists {
|
||||
tracing::debug!(%target_url, "forge: config-pr webhook already configured");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::debug!(error = %e, "forge: listing config-pr hooks failed; attempting create");
|
||||
}
|
||||
}
|
||||
|
||||
let hook = CreateHookOption {
|
||||
active: Some(true),
|
||||
authorization_header: None,
|
||||
branch_filter: None,
|
||||
config: CreateHookOptionConfig {
|
||||
content_type: "json".to_owned(),
|
||||
url: Url::parse(&target_url).context("parse config-pr webhook target url")?,
|
||||
additional: BTreeMap::new(),
|
||||
},
|
||||
events: Some(vec!["pull_request".to_owned()]),
|
||||
r#type: CreateHookOptionType::Forgejo,
|
||||
};
|
||||
tokio::time::timeout(HTTP_TIMEOUT, client.org_create_hook(CONFIG_ORG, hook))
|
||||
.await
|
||||
.map_err(anyhow::Error::from)
|
||||
.and_then(|r| r.map_err(anyhow::Error::from))
|
||||
.with_context(|| format!("create config-pr webhook on org {CONFIG_ORG}"))?;
|
||||
tracing::info!(%target_url, "forge: config-pr webhook created on org {CONFIG_ORG}");
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -303,17 +303,22 @@ async fn cmd_serve(
|
|||
tokio::spawn(async move {
|
||||
forge::ensure_all().await;
|
||||
});
|
||||
// Knowledge webhook setup: ensure the Forgejo push webhook for
|
||||
// `internal/knowledge` exists so `pull()` fires on merge. Runs
|
||||
// after forge::ensure_all so the core token + repo are present.
|
||||
// Webhook setup: ensure Forgejo webhooks are registered for both
|
||||
// `internal/knowledge` (push → git pull) and the `agent-configs` org
|
||||
// (pull_request → queue MergeConfigPr approval). Both run after
|
||||
// forge::ensure_all so the core token + repos + org are present.
|
||||
// No-op when the core token or forge are absent.
|
||||
let webhook_port = dashboard_port;
|
||||
tokio::spawn(async move {
|
||||
if let Some(token) = forge::core_token()
|
||||
&& let Err(e) = knowledge::ensure_webhook(&token, webhook_port).await
|
||||
{
|
||||
let Some(token) = forge::core_token() else {
|
||||
return;
|
||||
};
|
||||
if let Err(e) = knowledge::ensure_webhook(&token, webhook_port).await {
|
||||
tracing::warn!(error = ?e, "knowledge: ensure_webhook failed");
|
||||
}
|
||||
if let Err(e) = forge::ensure_config_pr_webhook(&token, webhook_port).await {
|
||||
tracing::warn!(error = ?e, "forge: ensure_config_pr_webhook failed");
|
||||
}
|
||||
});
|
||||
// Knowledge periodic pull: hourly fallback in case the webhook is
|
||||
// missed (e.g. hive-c0re was down during a push). First fires at
|
||||
|
|
|
|||
|
|
@ -1,8 +1,13 @@
|
|||
//! Config-approval request handlers: `RequestInitConfig` /
|
||||
//! `RequestApplyCommit` / `RequestMergeConfigPr` / `RequestUpdateMetaInputs`,
|
||||
//! `RequestApplyCommit` / `RequestUpdateMetaInputs`,
|
||||
//! plus the shared submit helpers (`submit_init_config` / `submit_apply_commit`
|
||||
//! / `submit_merge_config_pr`) and the commit-sha shape check
|
||||
//! (`validate_commit_ref`).
|
||||
//!
|
||||
//! `submit_merge_config_pr` is called from the dashboard webhook handler
|
||||
//! (`dashboard::webhook`) — agents no longer need an MCP tool for this;
|
||||
//! opening a config PR on `agent-configs/<agent>` is enough to trigger
|
||||
//! hive-c0re's webhook-driven queue path.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
|
|
@ -107,35 +112,6 @@ pub(super) fn handle_request_update_meta_inputs(
|
|||
AgentResponse::Ok
|
||||
}
|
||||
|
||||
/// `RequestMergeConfigPr` — queue a `MergeConfigPr` approval for a PR on an
|
||||
/// agent's `agent-configs/<agent>` forge repo. The target must be in the
|
||||
/// caller's subtree. hive-c0re fetches the PR head sha at submission time;
|
||||
/// that sha is stored as `fetched_sha` and forms the drift gate in the
|
||||
/// approve handler: if the PR head moves between submission and approval,
|
||||
/// the approve handler aborts without making any changes.
|
||||
pub(super) async fn handle_request_merge_config_pr(
|
||||
coord: &Arc<Coordinator>,
|
||||
agent: &str,
|
||||
target_agent: &str,
|
||||
pr_number: u64,
|
||||
description: Option<&str>,
|
||||
) -> AgentResponse {
|
||||
if let Some(err) = super::require_descendant(agent, target_agent, "request_merge_config_pr for")
|
||||
{
|
||||
return err;
|
||||
}
|
||||
tracing::info!(%agent, %target_agent, %pr_number, "request_merge_config_pr");
|
||||
match submit_merge_config_pr(coord, target_agent, pr_number, description, agent).await {
|
||||
Ok(id) => {
|
||||
tracing::info!(%id, %target_agent, %pr_number, "merge_config_pr approval queued");
|
||||
AgentResponse::Ok
|
||||
}
|
||||
Err(e) => AgentResponse::Err {
|
||||
message: format!("{e:#}"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Submit-time half of the PR-merge flow: fetch the PR head sha from the
|
||||
/// forge, queue the approval row, and emit the `approval_added` event so the
|
||||
/// dashboard shows the pending card immediately.
|
||||
|
|
@ -146,7 +122,7 @@ pub(super) async fn handle_request_merge_config_pr(
|
|||
/// this does NOT fetch the commit into the applied repo at submission time
|
||||
/// (that happens inside the approve handler, step 2, after the drift check).
|
||||
/// No flake pre-flight either — eval-verify happens at approval time too.
|
||||
async fn submit_merge_config_pr(
|
||||
pub(crate) async fn submit_merge_config_pr(
|
||||
coord: &Arc<Coordinator>,
|
||||
agent: &str,
|
||||
pr_number: u64,
|
||||
|
|
@ -172,7 +148,7 @@ async fn submit_merge_config_pr(
|
|||
{
|
||||
anyhow::bail!(
|
||||
"PR #{pr_number} on {repo} is closed or already merged — \
|
||||
request_merge_config_pr requires an open PR"
|
||||
merge_config_pr requires an open PR"
|
||||
);
|
||||
}
|
||||
// Fetch the current PR head sha — becomes the "reviewed" sha.
|
||||
|
|
|
|||
|
|
@ -25,12 +25,12 @@ mod lifecycle_handlers;
|
|||
mod reminders;
|
||||
mod schedules;
|
||||
|
||||
pub(crate) use config_approvals::{submit_init_config, submit_merge_config_pr};
|
||||
pub(crate) use schedules::filter_ghost_schedule_targets;
|
||||
pub use schedules::schedule_to_wire_public;
|
||||
|
||||
use config_approvals::{
|
||||
handle_request_apply_commit, handle_request_init_config, handle_request_merge_config_pr,
|
||||
handle_request_update_meta_inputs,
|
||||
handle_request_apply_commit, handle_request_init_config, handle_request_update_meta_inputs,
|
||||
};
|
||||
use lifecycle_handlers::{
|
||||
handle_kill, handle_list_descendants, handle_restart, handle_start, handle_update,
|
||||
|
|
@ -579,23 +579,6 @@ async fn dispatch(req: &AgentRequest, agent: &str, coord: &Arc<Coordinator>) ->
|
|||
)
|
||||
.await
|
||||
}
|
||||
AgentRequest::RequestMergeConfigPr {
|
||||
agent: target_agent,
|
||||
pr_number,
|
||||
description,
|
||||
} => {
|
||||
if let Some(err) = require_group(agent, "approvals", "request merge_config_pr") {
|
||||
return err;
|
||||
}
|
||||
handle_request_merge_config_pr(
|
||||
coord,
|
||||
agent,
|
||||
target_agent,
|
||||
*pr_number,
|
||||
description.as_deref(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
// Agent-state queries: own subtree is free; other agents + the
|
||||
// hive-wide `"*"` sweep require `QueryAgentState`.
|
||||
AgentRequest::GetLooseEnds { agent: target } => {
|
||||
|
|
|
|||
Loading…
Reference in a new issue