Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
261f02439b | ||
|
|
5cfb33eeed | ||
|
|
72415497aa | ||
|
|
4636987469 | ||
|
|
b8a3927c43 | ||
|
|
4468e86e2d | ||
|
|
0f035ce1e9 | ||
|
|
39fe0f306a | ||
|
|
5b062dca55 |
61 changed files with 2740 additions and 1914 deletions
|
|
@ -32,8 +32,9 @@ hand-maintained per-file tree drifts out of sync with the code.
|
|||
the meta flake, lifecycle (`nixos-container` shellouts), gateway /
|
||||
forge / matrix provisioning, per-container stats, and the axum
|
||||
operator dashboard (`dashboard.rs`). Largest crate.
|
||||
- **`hive-ag3nt/`** — in-container harness; one `hive` binary for every
|
||||
agent. Turn-loop *policy* layer (`turn.rs`) over the `hive-claude`
|
||||
- **`hive-ag3nt/`** — in-container harness; three sibling binaries for
|
||||
every agent (`hive-agent` serve loop, `hive-agent-mcp`,
|
||||
`hive-agent-wake`). Turn-loop *policy* layer (`turn.rs`) over the `hive-claude`
|
||||
driver, embedded MCP server (`mcp.rs`) + its claude launch-config layer
|
||||
(`mcp_config.rs`: tool-group/capability → `--allowedTools`, `--mcp-config`
|
||||
render), per-agent web UI (`web_ui/` module dir), event + turn-stats
|
||||
|
|
|
|||
93
Cargo.lock
generated
93
Cargo.lock
generated
|
|
@ -630,6 +630,16 @@ version = "0.4.2"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation"
|
||||
version = "0.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation"
|
||||
version = "0.10.1"
|
||||
|
|
@ -862,6 +872,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
|
||||
dependencies = [
|
||||
"powerfmt",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -924,6 +935,15 @@ version = "1.16.0"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
|
||||
|
||||
[[package]]
|
||||
name = "encoding_rs"
|
||||
version = "0.8.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
|
|
@ -1057,6 +1077,27 @@ version = "0.1.5"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
|
||||
|
||||
[[package]]
|
||||
name = "forgejo-api"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4c51fffa047d5836a4d89179a20b21b7e41ad97e713104752169d819b83c9158"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"bytes",
|
||||
"futures",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"soft_assert",
|
||||
"thiserror 1.0.69",
|
||||
"time",
|
||||
"tokio",
|
||||
"url",
|
||||
"urlencoding",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "form_urlencoded"
|
||||
version = "1.2.2"
|
||||
|
|
@ -1338,6 +1379,7 @@ dependencies = [
|
|||
"anyhow",
|
||||
"axum",
|
||||
"clap",
|
||||
"forgejo-api",
|
||||
"futures-util",
|
||||
"hive-claude",
|
||||
"hive-sh4re",
|
||||
|
|
@ -1348,11 +1390,13 @@ dependencies = [
|
|||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"time",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
"tower-http",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -1384,6 +1428,7 @@ dependencies = [
|
|||
"clap",
|
||||
"clap-markdown",
|
||||
"clap_complete",
|
||||
"forgejo-api",
|
||||
"hive-sh4re",
|
||||
"libc",
|
||||
"listenfd",
|
||||
|
|
@ -1398,6 +1443,7 @@ dependencies = [
|
|||
"tokio-stream",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -1417,9 +1463,12 @@ version = "0.1.0"
|
|||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
"forgejo-api",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"time",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -1631,9 +1680,11 @@ dependencies = [
|
|||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"socket2",
|
||||
"system-configuration",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
"windows-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -3018,6 +3069,7 @@ checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
|
|||
dependencies = [
|
||||
"base64",
|
||||
"bytes",
|
||||
"encoding_rs",
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
|
|
@ -3030,6 +3082,7 @@ dependencies = [
|
|||
"hyper-util",
|
||||
"js-sys",
|
||||
"log",
|
||||
"mime",
|
||||
"mime_guess",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
|
|
@ -3457,7 +3510,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"core-foundation",
|
||||
"core-foundation 0.10.1",
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
"security-framework-sys",
|
||||
|
|
@ -3689,6 +3742,12 @@ dependencies = [
|
|||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "soft_assert"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5097ec7ea7218135541ad96348f1441d0c616537dd4ed9c47205920c35d7d97"
|
||||
|
||||
[[package]]
|
||||
name = "spki"
|
||||
version = "0.7.3"
|
||||
|
|
@ -3786,6 +3845,27 @@ dependencies = [
|
|||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "system-configuration"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"core-foundation 0.9.4",
|
||||
"system-configuration-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "system-configuration-sys"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
|
|
@ -4596,6 +4676,17 @@ version = "0.2.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-registry"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
"windows-result",
|
||||
"windows-strings",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.4.1"
|
||||
|
|
|
|||
|
|
@ -68,6 +68,14 @@ reqwest = { version = "0.12", default-features = false, features = [
|
|||
"json",
|
||||
"rustls-tls",
|
||||
] }
|
||||
forgejo-api = { version = "0.11", default-features = false, features = [
|
||||
"rustls-tls",
|
||||
] }
|
||||
url = "2"
|
||||
time = { version = "0.3", default-features = false, features = [
|
||||
"formatting",
|
||||
"parsing",
|
||||
] }
|
||||
petgraph = { version = "0.8", default-features = false, features = ["std"] }
|
||||
matrix-sdk = { version = "0.14", default-features = false, features = [
|
||||
"rustls-tls",
|
||||
|
|
|
|||
|
|
@ -214,7 +214,8 @@ nspawn agent. Open questions, not yet wired:
|
|||
|
||||
## Harness systemd unit shape
|
||||
|
||||
One harness binary (`hive`), one `harness-base.nix` template, one
|
||||
One harness serve binary (`hive-agent`, with its `hive-agent-mcp` /
|
||||
`hive-agent-wake` siblings), one `harness-base.nix` template, one
|
||||
service unit (`systemd.services.hive-ag3nt`) for all agents. There
|
||||
is no longer a separate manager service name or role distinction in
|
||||
the harness — privilege differences live server-side in the broker
|
||||
|
|
@ -259,7 +260,8 @@ bit set` regardless of `hyperhive.user.passwordlessSudo`.
|
|||
|
||||
### `serviceConfig` highlights
|
||||
|
||||
- `ExecStart = pkgs.hyperhive/bin/hive serve` — single binary.
|
||||
- `ExecStart = pkgs.hyperhive/bin/hive-agent` — same binary for
|
||||
every agent.
|
||||
- `Restart = on-failure`, `RestartSec = 2` — keeps the harness
|
||||
resilient across transient crashes without thundering retries.
|
||||
- `RuntimeDirectory = "hive-config"` → `/run/hive-config/` owned by
|
||||
|
|
|
|||
|
|
@ -71,7 +71,12 @@ Two things live in the `agent-configs` Forgejo organization:
|
|||
The `hive-forge` CLI (separate workspace crate, see
|
||||
[`README.md`](../README.md) file map) wraps the Forgejo REST API
|
||||
with the per-agent token; agents call it for issue / PR / comment
|
||||
ops as if it were a peer.
|
||||
ops as if it were a peer. All REST calls across the workspace
|
||||
(`hive-forge` verbs, hive-c0re provisioning, this poller) go through
|
||||
the typed `forgejo-api` crate; only non-`/api/v1` web-router routes
|
||||
(attachment / artifact downloads, log streaming) and the poller's
|
||||
enrichment fetches of server-provided subject URLs stay on raw
|
||||
reqwest.
|
||||
|
||||
## Notification poller (`hive-ag3nt/src/forge_notify.rs`)
|
||||
|
||||
|
|
@ -146,11 +151,14 @@ one path still marked-read directly (no read-before-comment value).
|
|||
|
||||
The poller starts disabled and stays that way for any of:
|
||||
|
||||
- `HIVE_FORGE_URL` not set (no forge configured for this hive).
|
||||
- `HIVE_FORGE_URL` not set (no forge configured for this hive), or
|
||||
not parseable as a URL.
|
||||
- `<state>/forge-token` missing or empty (agent has no forge
|
||||
account — pre-provisioning or destroy-without-purge race).
|
||||
- Initial `reqwest::Client::builder` fails (extremely unlikely;
|
||||
treated as fatal-to-the-task only).
|
||||
- Initial client construction fails (the typed `forgejo-api` client
|
||||
for the API calls, or the plain reqwest client kept for the
|
||||
best-effort enrichment fetches of server-provided subject URLs;
|
||||
both extremely unlikely; treated as fatal-to-the-task only).
|
||||
|
||||
Disabled = the spawned task returns immediately. All other failure
|
||||
modes (HTTP errors, parse errors, mark-read failures) are
|
||||
|
|
|
|||
|
|
@ -5,7 +5,8 @@ claude has access to in return.
|
|||
|
||||
## The loop
|
||||
|
||||
Each agent harness (`hive serve` — one binary for all agents) runs:
|
||||
Each agent harness (`hive-agent` — one serve-loop binary for all
|
||||
agents) runs:
|
||||
|
||||
1. Long-poll `Recv` on its socket. The host-side broker
|
||||
(`broker.rs::recv_blocking_batch`) returns immediately if there's
|
||||
|
|
@ -51,38 +52,37 @@ Each agent harness (`hive serve` — one binary for all agents) runs:
|
|||
|
||||
## Harness binary shape
|
||||
|
||||
One `hive` binary for all agents. The earlier split into
|
||||
`hive-ag3nt` + `hive-m1nd` was collapsed because the privilege
|
||||
boundary lives server-side at the broker socket
|
||||
(`/run/hive/mcp.sock`): `ManagerRequest` calls are refused by the
|
||||
standard agent socket regardless of who sends them.
|
||||
Three sibling binaries out of the one `hive-ag3nt` crate, all
|
||||
role-agnostic. (The earlier split into `hive-ag3nt` + `hive-m1nd`
|
||||
was collapsed because the privilege boundary lives server-side at
|
||||
the broker socket (`/run/hive/mcp.sock`): `ManagerRequest` calls are
|
||||
refused by the standard agent socket regardless of who sends them.)
|
||||
|
||||
Three subcommands:
|
||||
|
||||
- `serve` — long-running harness loop (the inbox poll +
|
||||
- `hive-agent` — long-running harness loop (the inbox poll +
|
||||
claude-pump + ack/requeue cycle described above).
|
||||
- `mcp` — MCP server. Default: stdio child claude spawns via
|
||||
`--mcp-config` per turn. With `--http <addr>`, runs as a persistent
|
||||
streamable-HTTP daemon instead (used by the `hive-mcp-http`
|
||||
systemd unit when `hyperhive.mcp.httpPort` is set).
|
||||
- `wake --from <name> --body <body>` — push a message into our own
|
||||
inbox so the next turn fires with the given body. Used by
|
||||
co-process daemons (matrix bridge, scraper, webhook listeners)
|
||||
to nudge claude on external events. `--body -` reads from stdin.
|
||||
- `hive-agent-mcp` — MCP server. Default: stdio child claude spawns
|
||||
via `--mcp-config` per turn (the serve loop renders the config to
|
||||
point at this sibling of its own `/proc/self/exe`). With
|
||||
`--http <addr>`, runs as a persistent streamable-HTTP daemon
|
||||
instead (used by the `hive-mcp-http` systemd unit when
|
||||
`hyperhive.mcp.httpPort` is set).
|
||||
- `hive-agent-wake --from <name> --body <body>` — push a message into
|
||||
our own inbox so the next turn fires with the given body. Used by
|
||||
co-process helpers (scrapers, webhook listeners) to nudge claude on
|
||||
external events. `--body -` reads from stdin.
|
||||
|
||||
### `Surface` trait + zero-sized type tags
|
||||
|
||||
`AgentRequest` / `AgentResponse` (= `ManagerRequest` / `ManagerResponse` —
|
||||
type aliases) are the wire types. There is one role: agent.
|
||||
`bin/hive.rs` factors the turn loop through a `Surface` trait with one
|
||||
zero-sized impl (`AgentSurface`) wrapping:
|
||||
`bin/hive-agent.rs` factors the turn loop through a `Surface` trait
|
||||
with one zero-sized impl (`AgentSurface`) wrapping:
|
||||
|
||||
- One async method per wire op: `ack_turn`, `requeue_inflight`,
|
||||
`inbox_unread`, `post_turn_counts`, `send_to_parent`,
|
||||
`recv_next`, `wake_external`.
|
||||
`inbox_unread`, `post_turn_counts`, `send_to_parent`, `recv_next`.
|
||||
|
||||
`main()` calls `serve_main::<AgentSurface>` for all roles. The turn
|
||||
loop (`serve_loop` / `handle_turn` / `wake`) has no per-role branches.
|
||||
loop (`serve_loop` / `handle_turn`) has no per-role branches.
|
||||
|
||||
### Boot wiring
|
||||
|
||||
|
|
|
|||
|
|
@ -138,7 +138,7 @@ External MCP servers (and any other in-container process) can
|
|||
inject a wake-up event into the agent's inbox via the per-agent
|
||||
socket at `/run/hive/mcp.sock`. Two equivalent paths:
|
||||
|
||||
- **Shell out to `hive wake --from <label> --body <text>`**
|
||||
- **Shell out to `hive-agent-wake --from <label> --body <text>`**
|
||||
(use `--body -` to read body from stdin). Already on the
|
||||
container's `PATH` since the harness binary is in
|
||||
`systemPackages`. Convenient for shell-script integrations and
|
||||
|
|
|
|||
|
|
@ -10,6 +10,9 @@ workspace = true
|
|||
anyhow.workspace = true
|
||||
axum.workspace = true
|
||||
reqwest.workspace = true
|
||||
forgejo-api.workspace = true
|
||||
url.workspace = true
|
||||
time.workspace = true
|
||||
futures-util = "0.3"
|
||||
clap.workspace = true
|
||||
hive-claude.workspace = true
|
||||
|
|
@ -28,9 +31,8 @@ tracing-subscriber.workspace = true
|
|||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
[[bin]]
|
||||
# Unified harness binary for all agents. Privilege boundary is
|
||||
# Three sibling harness binaries for all agents (auto-discovered from
|
||||
# `src/bin/`): `hive-agent` (serve loop), `hive-agent-mcp` (MCP
|
||||
# server), `hive-agent-wake` (wake CLI). Privilege boundary is
|
||||
# enforced server-side at the socket (tool groups / manager surface).
|
||||
# See `docs/turn-loop.md::Harness binary shape`.
|
||||
name = "hive"
|
||||
path = "src/bin/hive.rs"
|
||||
|
|
|
|||
43
hive-ag3nt/src/bin/hive-agent-mcp.rs
Normal file
43
hive-ag3nt/src/bin/hive-agent-mcp.rs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
//! MCP-server binary. Default is stdio — spawned by `claude` via
|
||||
//! `--mcp-config`; tools dispatch through `/run/hive/mcp.sock` back into
|
||||
//! the hyperhive broker. Pass `--http <addr>` to instead run a long-lived
|
||||
//! streamable-http listener (persistent daemon, the `hive-mcp-http`
|
||||
//! systemd unit) that claude reconnects to each turn, avoiding the
|
||||
//! per-turn stdio re-registration race. Sibling of `hive-agent` (the
|
||||
//! serve loop that renders the `--mcp-config` blob pointing here) and
|
||||
//! `hive-agent-wake`.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::Parser;
|
||||
use hive_ag3nt::{DEFAULT_SOCKET, mcp};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "hive-agent-mcp", about = "hyperhive MCP server")]
|
||||
struct Cli {
|
||||
/// Path to the per-agent MCP socket (bind-mounted from the host).
|
||||
#[arg(long, default_value = DEFAULT_SOCKET)]
|
||||
socket: PathBuf,
|
||||
|
||||
/// Serve over streamable-http on this address (e.g.
|
||||
/// `127.0.0.1:8790`) instead of stdio. Bind loopback only.
|
||||
#[arg(long)]
|
||||
http: Option<std::net::SocketAddr>,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
|
||||
)
|
||||
.init();
|
||||
|
||||
let cli = Cli::parse();
|
||||
match cli.http {
|
||||
Some(addr) => mcp::serve_http(cli.socket, addr).await,
|
||||
None => mcp::serve_agent_stdio(cli.socket).await,
|
||||
}
|
||||
}
|
||||
60
hive-ag3nt/src/bin/hive-agent-wake.rs
Normal file
60
hive-ag3nt/src/bin/hive-agent-wake.rs
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
//! Wake CLI: inject a wake-up event into this container's harness inbox
|
||||
//! so the next turn fires with the given body. Intended for extra MCP
|
||||
//! servers / helpers (scraper, webhook listener, etc.) that need to
|
||||
//! nudge claude on external events; the built-in daemons (matrix, bash)
|
||||
//! talk to the socket directly instead. Sibling of `hive-agent` and
|
||||
//! `hive-agent-mcp`.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::Parser;
|
||||
use hive_ag3nt::{DEFAULT_SOCKET, client};
|
||||
use hive_sh4re::{AgentRequest, AgentResponse};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "hive-agent-wake", about = "hyperhive harness wake signal")]
|
||||
struct Cli {
|
||||
/// Path to the per-agent MCP socket (bind-mounted from the host).
|
||||
#[arg(long, default_value = DEFAULT_SOCKET)]
|
||||
socket: PathBuf,
|
||||
|
||||
#[arg(long)]
|
||||
from: String,
|
||||
|
||||
/// Body of the wake message. Pass `-` to read from stdin.
|
||||
#[arg(long)]
|
||||
body: String,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
|
||||
)
|
||||
.init();
|
||||
|
||||
let cli = Cli::parse();
|
||||
let body = if cli.body == "-" {
|
||||
let mut buf = String::new();
|
||||
std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf)?;
|
||||
buf
|
||||
} else {
|
||||
cli.body
|
||||
};
|
||||
let resp: AgentResponse = client::request(
|
||||
&cli.socket,
|
||||
&AgentRequest::Wake {
|
||||
from: cli.from,
|
||||
body,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
match resp {
|
||||
AgentResponse::Ok => Ok(()),
|
||||
AgentResponse::Err { message } => anyhow::bail!("wake: {message}"),
|
||||
other => anyhow::bail!("wake: unexpected response {other:?}"),
|
||||
}
|
||||
}
|
||||
|
|
@ -1,7 +1,9 @@
|
|||
//! Unified hyperhive harness binary. Dispatches one of three subcommands
|
||||
//! (`serve` / `mcp` / `wake`). There is one role: agent. The `Surface`
|
||||
//! Harness serve-loop binary. Long-polls the broker inbox and drives one
|
||||
//! claude turn per message. There is one role: agent. The `Surface`
|
||||
//! trait + `AgentSurface` zero-sized type tag keeps the turn loop
|
||||
//! generic and testable. Architecture lives in
|
||||
//! generic and testable. Siblings: `hive-agent-mcp` (the MCP server this
|
||||
//! loop points claude at) and `hive-agent-wake` (external wake CLI).
|
||||
//! Architecture lives in
|
||||
//! [`docs/turn-loop.md::Harness binary shape`](../../../docs/turn-loop.md).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
|
@ -9,58 +11,23 @@ use std::sync::{Arc, Mutex};
|
|||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::{Parser, Subcommand};
|
||||
use clap::Parser;
|
||||
use hive_ag3nt::events::{Bus, LiveEvent, TurnState};
|
||||
use hive_ag3nt::login::{self, LoginState};
|
||||
use hive_ag3nt::turn_stats::TurnStats;
|
||||
use hive_ag3nt::{
|
||||
DEFAULT_SOCKET, DEFAULT_WEB_PORT, client, mcp, plugins, serve_common, turn, web_ui,
|
||||
};
|
||||
use hive_ag3nt::{DEFAULT_SOCKET, DEFAULT_WEB_PORT, client, plugins, serve_common, turn, web_ui};
|
||||
use hive_sh4re::{AgentRequest, AgentResponse, HelperEvent, SYSTEM_SENDER};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "hive", about = "hyperhive harness")]
|
||||
#[command(name = "hive-agent", about = "hyperhive harness serve loop")]
|
||||
struct Cli {
|
||||
/// Path to the per-agent MCP socket (bind-mounted from the host).
|
||||
#[arg(long, global = true, default_value = DEFAULT_SOCKET)]
|
||||
#[arg(long, default_value = DEFAULT_SOCKET)]
|
||||
socket: PathBuf,
|
||||
|
||||
#[command(subcommand)]
|
||||
cmd: Cmd,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Cmd {
|
||||
/// Run the long-lived harness loop. Polls inbox; replies via
|
||||
/// `claude --print` when available.
|
||||
Serve {
|
||||
/// Inbox poll interval in milliseconds.
|
||||
#[arg(long, default_value_t = 1000)]
|
||||
poll_ms: u64,
|
||||
},
|
||||
/// Run the MCP server. Default is stdio — spawned by `claude` via
|
||||
/// `--mcp-config`; tools dispatch through `/run/hive/mcp.sock` back
|
||||
/// into the hyperhive broker. Pass `--http <addr>` to instead run a
|
||||
/// long-lived streamable-http listener (persistent daemon) that
|
||||
/// claude reconnects to each turn, avoiding the per-turn stdio
|
||||
/// re-registration race.
|
||||
Mcp {
|
||||
/// Serve over streamable-http on this address (e.g.
|
||||
/// `127.0.0.1:8790`) instead of stdio. Bind loopback only.
|
||||
#[arg(long)]
|
||||
http: Option<std::net::SocketAddr>,
|
||||
},
|
||||
/// Inject a wake-up event into this harness's inbox so the next
|
||||
/// turn fires with the given body. Intended for extra MCP servers
|
||||
/// / helpers (matrix bridge, scraper, webhook listener, etc.) that
|
||||
/// need to nudge claude on external events.
|
||||
Wake {
|
||||
#[arg(long)]
|
||||
from: String,
|
||||
/// Body of the wake message. Pass `-` to read from stdin.
|
||||
#[arg(long)]
|
||||
body: String,
|
||||
},
|
||||
/// Inbox poll interval in milliseconds.
|
||||
#[arg(long, default_value_t = 1000)]
|
||||
poll_ms: u64,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
|
|
@ -73,15 +40,7 @@ async fn main() -> Result<()> {
|
|||
.init();
|
||||
|
||||
let cli = Cli::parse();
|
||||
|
||||
match cli.cmd {
|
||||
Cmd::Serve { poll_ms } => serve_main::<AgentSurface>(&cli.socket, poll_ms).await,
|
||||
Cmd::Mcp { http } => match http {
|
||||
Some(addr) => mcp::serve_http(cli.socket, addr).await,
|
||||
None => mcp::serve_agent_stdio(cli.socket).await,
|
||||
},
|
||||
Cmd::Wake { from, body } => wake::<AgentSurface>(&cli.socket, from, body).await,
|
||||
}
|
||||
serve_main::<AgentSurface>(&cli.socket, cli.poll_ms).await
|
||||
}
|
||||
|
||||
// ---------- shared turn helpers ----------
|
||||
|
|
@ -261,13 +220,6 @@ trait Surface {
|
|||
/// generic `serve_loop` doesn't need the per-role Response enum
|
||||
/// at all.
|
||||
fn recv_next(socket: &Path) -> impl Future<Output = RecvOutcome>;
|
||||
|
||||
/// External `wake` subcommand (the `hive wake` CLI command, used
|
||||
/// by co-process daemons like matrix to push events into the
|
||||
/// harness inbox). Errors out via `anyhow::bail!` so the calling
|
||||
/// binary surfaces them on stderr.
|
||||
fn wake_external(socket: &Path, from: String, body: String)
|
||||
-> impl Future<Output = Result<()>>;
|
||||
}
|
||||
|
||||
// ---------- AgentSurface ----------
|
||||
|
|
@ -383,16 +335,6 @@ impl Surface for AgentSurface {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wake_external(socket: &Path, from: String, body: String) -> Result<()> {
|
||||
let resp: AgentResponse =
|
||||
client::request(socket, &AgentRequest::Wake { from, body }).await?;
|
||||
match resp {
|
||||
AgentResponse::Ok => Ok(()),
|
||||
AgentResponse::Err { message } => anyhow::bail!("wake: {message}"),
|
||||
other => anyhow::bail!("wake: unexpected response {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- generic turn loop ----------
|
||||
|
|
@ -673,20 +615,6 @@ async fn handle_turn<S: Surface>(
|
|||
}
|
||||
}
|
||||
|
||||
/// External `hive wake` subcommand — push a message into our own
|
||||
/// inbox so the next turn fires with the given body. Reads the body
|
||||
/// from stdin when `body == "-"`.
|
||||
async fn wake<S: Surface>(socket: &Path, from: String, body: String) -> Result<()> {
|
||||
let body = if body == "-" {
|
||||
let mut buf = String::new();
|
||||
std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf)?;
|
||||
buf
|
||||
} else {
|
||||
body
|
||||
};
|
||||
S::wake_external(socket, from, body).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod continue_tests {
|
||||
use super::{TurnControl, should_self_continue, synthetic_continue};
|
||||
|
|
@ -24,9 +24,18 @@ use std::fmt::Write as _;
|
|||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use forgejo_api::structs::{
|
||||
NotificationThread, NotifyGetListQuery, NotifyReadThreadQuery, NotifySubjectType,
|
||||
};
|
||||
use forgejo_api::{Auth, Forgejo, ForgejoError};
|
||||
use time::OffsetDateTime;
|
||||
use time::format_description::well_known::Rfc3339;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
const POLL_INTERVAL_SECS: u64 = 30;
|
||||
/// Per-request cap applied to every forge call — natively on the reqwest
|
||||
/// enrichment client, via `tokio::time::timeout` around the typed
|
||||
/// `forgejo-api` client (which exposes no timeout knob of its own).
|
||||
const HTTP_TIMEOUT_SECS: u64 = 10;
|
||||
/// Page size of the unread-notifications fetch. This is also the hard
|
||||
/// bound on the persisted delivery-dedupe cursor: each poll prunes the
|
||||
|
|
@ -52,7 +61,7 @@ const TOKEN_RETRY_MAX: u32 = 20;
|
|||
/// claim it's "new" — see docs/forge.md, "new vs activity on".
|
||||
const NEW_ITEM_TOLERANCE_SECS: i64 = 120;
|
||||
|
||||
/// Spawn point: called once from `hive serve`. Returns immediately if the forge is not
|
||||
/// Spawn point: called once from the `hive-agent` serve loop. Returns immediately if the forge is not
|
||||
/// configured. Otherwise loops forever, polling every
|
||||
/// `POLL_INTERVAL_SECS` seconds. Errors are never fatal.
|
||||
///
|
||||
|
|
@ -97,6 +106,27 @@ pub async fn run(socket: PathBuf) {
|
|||
}
|
||||
};
|
||||
|
||||
// Typed Forgejo client for the API calls with stable shapes (identity
|
||||
// probe, notification list, mark-read). The plain reqwest client below
|
||||
// stays for the best-effort enrichment fetches of `subject.url` /
|
||||
// `latest_comment_url`: those follow server-provided URLs whose payload
|
||||
// shape is heterogeneous (issue vs comment vs review), which the typed
|
||||
// client cannot express (its `Endpoint` trait is sealed).
|
||||
let base_url = match url::Url::parse(&forge_url) {
|
||||
Ok(u) => u,
|
||||
Err(e) => {
|
||||
warn!("forge_notify: invalid HIVE_FORGE_URL {forge_url}: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let forge = match Forgejo::new(Auth::Token(&token), base_url) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
warn!("forge_notify: failed to build forge client: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let client = match reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(HTTP_TIMEOUT_SECS))
|
||||
.build()
|
||||
|
|
@ -111,13 +141,15 @@ pub async fn run(socket: PathBuf) {
|
|||
// Fetch own login once for self-notification filtering. Falls back
|
||||
// to empty string on failure — no filtering (safe degradation; see
|
||||
// `docs/forge.md::Self-notification filtering`).
|
||||
let own_login = {
|
||||
let url = format!("{forge_url}/api/v1/user");
|
||||
fetch_json(&client, &url, &token)
|
||||
.await
|
||||
.and_then(|v| v["login"].as_str().map(std::borrow::ToOwned::to_owned))
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let own_login = tokio::time::timeout(
|
||||
Duration::from_secs(HTTP_TIMEOUT_SECS),
|
||||
forge.user_get_current().send(),
|
||||
)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(Result::ok)
|
||||
.and_then(|u| u.login)
|
||||
.unwrap_or_default();
|
||||
if own_login.is_empty() {
|
||||
warn!("forge_notify: could not resolve own login — self-notification filtering disabled");
|
||||
} else {
|
||||
|
|
@ -160,15 +192,7 @@ pub async fn run(socket: PathBuf) {
|
|||
|
||||
loop {
|
||||
interval.tick().await;
|
||||
poll_once(
|
||||
&client,
|
||||
&forge_url,
|
||||
&token,
|
||||
&socket,
|
||||
&mut delivered,
|
||||
&own_login,
|
||||
)
|
||||
.await;
|
||||
poll_once(&forge, &client, &token, &socket, &mut delivered, &own_login).await;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -188,14 +212,16 @@ async fn fetch_json(client: &reqwest::Client, url: &str, token: &str) -> Option<
|
|||
}
|
||||
|
||||
/// Map a Forgejo notification `subject.type` to a human-readable label.
|
||||
/// Known values: "Pull", "Issue", "Commit", "Repository". Any unknown
|
||||
/// type is passed through as-is so new Forgejo types degrade gracefully
|
||||
/// rather than silently collapsing into a generic label.
|
||||
fn notif_type_label(t: &str) -> &str {
|
||||
/// `Commit` / `Repository` keep their API names, matching the old raw
|
||||
/// pass-through of types we don't relabel; a missing type degrades to
|
||||
/// `?` like every other absent field.
|
||||
fn notif_type_label(t: Option<NotifySubjectType>) -> &'static str {
|
||||
match t {
|
||||
"Pull" => "PR",
|
||||
"Issue" => "issue",
|
||||
other => other,
|
||||
Some(NotifySubjectType::Pull) => "PR",
|
||||
Some(NotifySubjectType::Issue) => "issue",
|
||||
Some(NotifySubjectType::Commit) => "Commit",
|
||||
Some(NotifySubjectType::Repository) => "Repository",
|
||||
None => "?",
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -349,14 +375,19 @@ fn review_state_label(state: &str) -> Option<&str> {
|
|||
async fn format_notification(
|
||||
client: &reqwest::Client,
|
||||
token: &str,
|
||||
notif: &serde_json::Value,
|
||||
notif: &PolledNotification,
|
||||
own_login: &str,
|
||||
) -> Option<String> {
|
||||
let title = notif["subject"]["title"].as_str().unwrap_or("?");
|
||||
let notif_type = notif["subject"]["type"].as_str().unwrap_or("?");
|
||||
let html_url = notif["subject"]["html_url"]
|
||||
.as_str()
|
||||
.unwrap_or_else(|| notif["subject"]["url"].as_str().unwrap_or(""));
|
||||
let subj = notif.thread.subject.as_ref();
|
||||
let title = subj.and_then(|s| s.title.as_deref()).unwrap_or("?");
|
||||
let subject_type = subj.and_then(|s| s.r#type);
|
||||
// forgejo-api maps a blank `html_url` (Go marshals empty strings) to
|
||||
// `None`, so the API-url fallback also covers present-but-empty —
|
||||
// deliberate: a fetchable API link beats the raw-HTTP predecessor's
|
||||
// empty `url:` line.
|
||||
let html_url = subj
|
||||
.and_then(|s| s.html_url.as_ref().or(s.url.as_ref()))
|
||||
.map_or("", url::Url::as_str);
|
||||
|
||||
// Extract issue/PR number from the html_url. URL ends with /issues/N or
|
||||
// /pulls/N (possibly followed by #anchor for comments). Best-effort.
|
||||
|
|
@ -369,19 +400,24 @@ async fn format_notification(
|
|||
.unwrap_or_default();
|
||||
|
||||
// Repo slug for multi-repo disambiguation. Falls back gracefully when absent.
|
||||
let repo = notif["repository"]["full_name"]
|
||||
.as_str()
|
||||
let repo = notif
|
||||
.thread
|
||||
.repository
|
||||
.as_ref()
|
||||
.and_then(|r| r.full_name.as_deref())
|
||||
.map(|r| format!(" {r}"))
|
||||
.unwrap_or_default();
|
||||
|
||||
// API URLs for fetching content
|
||||
let subject_api_url = notif["subject"]["url"].as_str().unwrap_or("");
|
||||
let comment_api_url = notif["subject"]["latest_comment_url"]
|
||||
.as_str()
|
||||
.unwrap_or("");
|
||||
let comment_html_url = notif["subject"]["latest_comment_html_url"]
|
||||
.as_str()
|
||||
.unwrap_or("");
|
||||
let subject_api_url = subj
|
||||
.and_then(|s| s.url.as_ref())
|
||||
.map_or("", url::Url::as_str);
|
||||
let comment_api_url = subj
|
||||
.and_then(|s| s.latest_comment_url.as_ref())
|
||||
.map_or("", url::Url::as_str);
|
||||
let comment_html_url = subj
|
||||
.and_then(|s| s.latest_comment_html_url.as_ref())
|
||||
.map_or("", url::Url::as_str);
|
||||
|
||||
// Always fetch subject detail for assignee/reviewer metadata so
|
||||
// the meta suffix can show current ownership without a follow-up
|
||||
|
|
@ -394,7 +430,7 @@ async fn format_notification(
|
|||
|
||||
// Forgejo's notification `subject.type` is "Pull" / "Issue", never
|
||||
// "Pull Request".
|
||||
let is_pr = notif_type == "Pull";
|
||||
let is_pr = subject_type == Some(NotifySubjectType::Pull);
|
||||
let meta_suffix = build_meta_suffix(subject.as_ref(), is_pr);
|
||||
|
||||
// Determine whether this notification was triggered by a comment/review or
|
||||
|
|
@ -403,7 +439,7 @@ async fn format_notification(
|
|||
|
||||
let meta = NotifMeta {
|
||||
title,
|
||||
notif_type,
|
||||
subject_type,
|
||||
html_url,
|
||||
num,
|
||||
repo,
|
||||
|
|
@ -422,14 +458,14 @@ async fn format_notification(
|
|||
)
|
||||
.await
|
||||
} else {
|
||||
format_state_change_notification(notif, &meta, own_login)
|
||||
format_state_change_notification(notif.thread.updated_at, ¬if.state, &meta, own_login)
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared notification metadata extracted from the raw Forgejo JSON.
|
||||
/// Shared notification metadata extracted from the polled notification.
|
||||
struct NotifMeta<'a> {
|
||||
title: &'a str,
|
||||
notif_type: &'a str,
|
||||
subject_type: Option<NotifySubjectType>,
|
||||
html_url: &'a str,
|
||||
num: String,
|
||||
repo: String,
|
||||
|
|
@ -522,7 +558,7 @@ async fn format_comment_notification(
|
|||
};
|
||||
let NotifMeta {
|
||||
title,
|
||||
notif_type,
|
||||
subject_type,
|
||||
num,
|
||||
repo,
|
||||
meta_suffix,
|
||||
|
|
@ -547,7 +583,7 @@ async fn format_comment_notification(
|
|||
Some(out)
|
||||
} else {
|
||||
// Regular comment.
|
||||
let kind = format!("comment on {}{num}{repo}", notif_type_label(notif_type));
|
||||
let kind = format!("comment on {}{num}{repo}", notif_type_label(*subject_type));
|
||||
let mut out = format!(
|
||||
"[{kind}] {title}\nurl: {url}\n\n{author}: {body_for_embed}{truncated_mentions}"
|
||||
);
|
||||
|
|
@ -563,17 +599,17 @@ async fn format_comment_notification(
|
|||
/// path applies. Only creations are dropped: a later state change on the
|
||||
/// agent's own subject is driven by someone else and stays a wake.
|
||||
fn format_state_change_notification(
|
||||
notif: &serde_json::Value,
|
||||
event_time: Option<OffsetDateTime>,
|
||||
notif_state: &str,
|
||||
meta: &NotifMeta<'_>,
|
||||
own_login: &str,
|
||||
) -> Option<String> {
|
||||
// Classification uses notif["subject"]["state"] directly — Forgejo
|
||||
// returns "open" / "closed" / "merged" here. We do NOT rely on
|
||||
// fetching the PR/issue detail for `merged`:
|
||||
// Classification uses the raw `subject.state` string extracted in
|
||||
// `parse_notification` — Forgejo returns "open" / "closed" / "merged"
|
||||
// there. We do NOT rely on fetching the PR/issue detail for `merged`:
|
||||
// - `subject.url` points to the *issues* endpoint, which returns
|
||||
// `pull_request.merged`, not top-level `merged`.
|
||||
// - Forgejo API type is "Pull" / "Issue", never "Pull Request".
|
||||
let notif_state = notif["subject"]["state"].as_str().unwrap_or("");
|
||||
|
||||
// "New" = the subject is open (or state is absent). Used below for
|
||||
// the review-request override.
|
||||
|
|
@ -581,7 +617,7 @@ fn format_state_change_notification(
|
|||
|
||||
let NotifMeta {
|
||||
title,
|
||||
notif_type,
|
||||
subject_type,
|
||||
html_url,
|
||||
num,
|
||||
repo,
|
||||
|
|
@ -589,7 +625,7 @@ fn format_state_change_notification(
|
|||
subject,
|
||||
is_pr,
|
||||
} = meta;
|
||||
let label = notif_type_label(notif_type);
|
||||
let label = notif_type_label(*subject_type);
|
||||
// Only claim "new" when the notification actually fired at creation
|
||||
// time. A review submitted with no body carries no
|
||||
// `latest_comment_url`, so it lands here instead of on the comment
|
||||
|
|
@ -598,7 +634,7 @@ fn format_state_change_notification(
|
|||
// on"): agents dismiss it as a
|
||||
// duplicate of the original open notification. When we can't confirm
|
||||
// creation, fall back to a neutral "activity on" label.
|
||||
let looks_new = notification_is_creation(notif, subject.as_ref());
|
||||
let looks_new = notification_is_creation(event_time, subject.as_ref());
|
||||
|
||||
// Self-authored creation filter: skip an agent being woken by its own
|
||||
// freshly-opened issue/PR. The subject payload is already fetched (for
|
||||
|
|
@ -668,81 +704,66 @@ fn format_state_change_notification(
|
|||
/// new item behind the neutral fallback. See docs/forge.md, "new vs
|
||||
/// activity on".
|
||||
fn notification_is_creation(
|
||||
notif: &serde_json::Value,
|
||||
event: Option<OffsetDateTime>,
|
||||
subject: Option<&serde_json::Value>,
|
||||
) -> bool {
|
||||
let created = subject
|
||||
.and_then(|s| s["created_at"].as_str())
|
||||
.and_then(parse_rfc3339_secs);
|
||||
let event = notif["updated_at"].as_str().and_then(parse_rfc3339_secs);
|
||||
.and_then(parse_rfc3339);
|
||||
match (created, event) {
|
||||
(Some(c), Some(e)) => (e - c).abs() <= NEW_ITEM_TOLERANCE_SECS,
|
||||
(Some(c), Some(e)) => (e - c).whole_seconds().abs() <= NEW_ITEM_TOLERANCE_SECS,
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal dependency-free RFC 3339 / ISO 8601 parser → Unix epoch
|
||||
/// seconds. Forgejo emits timestamps like `2026-06-13T11:18:42+02:00`
|
||||
/// or `...Z`, optionally with fractional seconds. We only need
|
||||
/// second-granularity comparison, so the fractional part is skipped.
|
||||
/// Returns `None` on any shape we don't recognise so callers can fall
|
||||
/// back gracefully.
|
||||
fn parse_rfc3339_secs(s: &str) -> Option<i64> {
|
||||
if s.len() < 19 {
|
||||
return None;
|
||||
}
|
||||
let year: i64 = s.get(0..4)?.parse().ok()?;
|
||||
let month: i64 = s.get(5..7)?.parse().ok()?;
|
||||
let day: i64 = s.get(8..10)?.parse().ok()?;
|
||||
let hour: i64 = s.get(11..13)?.parse().ok()?;
|
||||
let minute: i64 = s.get(14..16)?.parse().ok()?;
|
||||
let second: i64 = s.get(17..19)?.parse().ok()?;
|
||||
|
||||
let mut epoch =
|
||||
days_from_civil(year, month, day) * 86_400 + hour * 3_600 + minute * 60 + second;
|
||||
|
||||
// Remainder after seconds: optional `.fff` fraction, then a zone.
|
||||
let mut rest = &s[19..];
|
||||
if let Some(frac) = rest.strip_prefix('.') {
|
||||
let end = frac
|
||||
.find(|c: char| !c.is_ascii_digit())
|
||||
.unwrap_or(frac.len());
|
||||
rest = &frac[end..];
|
||||
}
|
||||
// Zone: `Z`/empty = UTC; otherwise `±HH:MM`. Subtract the offset to
|
||||
// normalise to UTC epoch seconds.
|
||||
if !(rest.is_empty() || rest.starts_with('Z')) {
|
||||
let sign = rest.as_bytes()[0];
|
||||
let off = &rest[1..];
|
||||
// Accept `HH:MM` (Forgejo's form) and bare `HHMM`; minutes optional.
|
||||
// Both fields fail the same way — a present-but-unparseable component
|
||||
// returns `None` rather than one silently defaulting.
|
||||
let (hh, mm) = match off.split_once(':') {
|
||||
Some((h, m)) => (h, m),
|
||||
None => (off.get(0..2)?, off.get(2..4).unwrap_or("00")),
|
||||
};
|
||||
let oh: i64 = hh.parse().ok()?;
|
||||
let om: i64 = if mm.is_empty() { 0 } else { mm.parse().ok()? };
|
||||
let offset = oh * 3_600 + om * 60;
|
||||
match sign {
|
||||
b'+' => epoch -= offset,
|
||||
b'-' => epoch += offset,
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
Some(epoch)
|
||||
/// Parse an RFC 3339 timestamp as Forgejo emits them
|
||||
/// (`2026-06-13T11:18:42+02:00` or `...Z`, optionally with fractional
|
||||
/// seconds). Returns `None` on any shape `time` doesn't recognise so
|
||||
/// callers can fall back gracefully.
|
||||
fn parse_rfc3339(s: &str) -> Option<OffsetDateTime> {
|
||||
OffsetDateTime::parse(s, &Rfc3339).ok()
|
||||
}
|
||||
|
||||
/// Days since the Unix epoch for a proleptic-Gregorian `y-m-d`
|
||||
/// (Howard Hinnant's `days_from_civil`). Valid for all dates Forgejo
|
||||
/// can emit.
|
||||
fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
|
||||
let y = if m <= 2 { y - 1 } else { y };
|
||||
let era = (if y >= 0 { y } else { y - 399 }) / 400;
|
||||
let yoe = y - era * 400;
|
||||
let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
|
||||
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
|
||||
era * 146_097 + doe - 719_468
|
||||
/// One notification from the poll page: the typed thread plus two raw
|
||||
/// fields the typed structs can't carry faithfully.
|
||||
struct PolledNotification {
|
||||
thread: NotificationThread,
|
||||
/// Raw `subject.state`. Forgejo reports `"merged"` for merged PRs
|
||||
/// (`services/convert/notification.go`), which forgejo-api's
|
||||
/// `StateType` (open/closed only) rejects at deserialization — so
|
||||
/// the state is extracted verbatim before the typed parse and
|
||||
/// matched as a string, exactly like the pre-typed code.
|
||||
state: String,
|
||||
/// Raw `updated_at` string, byte-identical to what Forgejo sent, so
|
||||
/// the persisted delivery-dedupe cursor keeps its exact format
|
||||
/// across the typed-client port (no spurious re-deliveries from a
|
||||
/// reformatting round-trip).
|
||||
updated_at: String,
|
||||
}
|
||||
|
||||
/// Parse one notification JSON object: pull out the raw `subject.state`
|
||||
/// and `updated_at` (see [`PolledNotification`]), null the state so the
|
||||
/// closed `StateType` enum can't reject it, and deserialize the rest
|
||||
/// into the typed [`NotificationThread`]. Returns `None` (with a warn)
|
||||
/// for an item the typed struct can't represent — the rest of the page
|
||||
/// still delivers.
|
||||
fn parse_notification(mut value: serde_json::Value) -> Option<PolledNotification> {
|
||||
let state = value["subject"]["state"].as_str().unwrap_or("").to_owned();
|
||||
if let Some(s) = value.get_mut("subject").and_then(|s| s.get_mut("state")) {
|
||||
*s = serde_json::Value::Null;
|
||||
}
|
||||
let updated_at = value["updated_at"].as_str().unwrap_or("").to_owned();
|
||||
match serde_json::from_value::<NotificationThread>(value) {
|
||||
Ok(thread) => Some(PolledNotification {
|
||||
thread,
|
||||
state,
|
||||
updated_at,
|
||||
}),
|
||||
Err(e) => {
|
||||
warn!("forge_notify: notification parse error: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(
|
||||
|
|
@ -752,33 +773,45 @@ fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
|
|||
functions for state shared across all three phases"
|
||||
)]
|
||||
async fn poll_once(
|
||||
forge: &Forgejo,
|
||||
client: &reqwest::Client,
|
||||
forge_url: &str,
|
||||
token: &str,
|
||||
socket: &Path,
|
||||
delivered: &mut HashMap<u64, String>,
|
||||
own_login: &str,
|
||||
) {
|
||||
let url = format!("{forge_url}/api/v1/notifications?all=false&limit={UNREAD_FETCH_LIMIT}");
|
||||
let resp = match client
|
||||
.get(&url)
|
||||
.header("Authorization", format!("token {token}"))
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
debug!("forge_notify: poll request failed: {e}");
|
||||
return;
|
||||
}
|
||||
// Fetch the page as raw JSON (`response_type::<String>`) instead of the
|
||||
// crate's `Vec<NotificationThread>`: one merged-PR notification
|
||||
// (`subject.state = "merged"`, unrepresentable in `StateType`) would
|
||||
// otherwise poison deserialization of the whole page. HTTP-level errors
|
||||
// still surface as `ForgejoError` exactly like the fully-typed call;
|
||||
// `parse_notification` below does the per-item typed parse.
|
||||
let query = NotifyGetListQuery {
|
||||
all: Some(false),
|
||||
..NotifyGetListQuery::default()
|
||||
};
|
||||
let request = forge
|
||||
.notify_get_list(query)
|
||||
.page_size(u32::try_from(UNREAD_FETCH_LIMIT).unwrap_or(u32::MAX))
|
||||
.response_type::<String>();
|
||||
let raw =
|
||||
match tokio::time::timeout(Duration::from_secs(HTTP_TIMEOUT_SECS), request.send()).await {
|
||||
Ok(Ok(raw)) => raw,
|
||||
Ok(Err(ForgejoError::UnexpectedStatusCode(status))) => {
|
||||
debug!("forge_notify: poll status {status}");
|
||||
return;
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
debug!("forge_notify: poll request failed: {e}");
|
||||
return;
|
||||
}
|
||||
Err(_) => {
|
||||
debug!("forge_notify: poll request failed: timed out");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if !resp.status().is_success() {
|
||||
debug!("forge_notify: poll status {}", resp.status());
|
||||
return;
|
||||
}
|
||||
|
||||
let notifications: Vec<serde_json::Value> = match resp.json().await {
|
||||
let values: Vec<serde_json::Value> = match serde_json::from_str(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
warn!("forge_notify: response parse error: {e}");
|
||||
|
|
@ -786,22 +819,25 @@ async fn poll_once(
|
|||
}
|
||||
};
|
||||
|
||||
if notifications.is_empty() {
|
||||
if values.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
debug!(
|
||||
count = notifications.len(),
|
||||
count = values.len(),
|
||||
"forge_notify: delivering notifications"
|
||||
);
|
||||
|
||||
let notifications: Vec<PolledNotification> =
|
||||
values.into_iter().filter_map(parse_notification).collect();
|
||||
|
||||
// Tracks whether the dedupe cursor changed this poll (a new delivery
|
||||
// recorded, or the prune below dropped now-read threads) so we only
|
||||
// rewrite the on-disk cursor when there's something to persist.
|
||||
let mut cursor_dirty = false;
|
||||
|
||||
for notif in ¬ifications {
|
||||
let Some(id) = notif["id"].as_u64() else {
|
||||
let Some(id) = notif.thread.id.and_then(|id| u64::try_from(id).ok()) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
|
|
@ -810,7 +846,7 @@ async fn poll_once(
|
|||
// Skip it silently unless its `updated_at` advanced since the
|
||||
// version we last delivered a wake for (i.e. genuinely new
|
||||
// activity). See the `delivered` cursor note in `run`.
|
||||
let updated_at = notif["updated_at"].as_str().unwrap_or("").to_owned();
|
||||
let updated_at = notif.updated_at.clone();
|
||||
if !should_deliver(delivered, id, &updated_at) {
|
||||
debug!(%id, "forge_notify: skipping (already delivered this version)");
|
||||
continue;
|
||||
|
|
@ -820,7 +856,7 @@ async fn poll_once(
|
|||
|
||||
// None means self-echo — mark read silently, no delivery.
|
||||
let Some(body) = body_opt else {
|
||||
mark_read(client, forge_url, token, id).await;
|
||||
mark_read(forge, id).await;
|
||||
continue;
|
||||
};
|
||||
|
||||
|
|
@ -864,7 +900,7 @@ async fn poll_once(
|
|||
// loud in tests/dev if a future pagination change silently breaks it.
|
||||
let current_ids: HashSet<u64> = notifications
|
||||
.iter()
|
||||
.filter_map(|n| n["id"].as_u64())
|
||||
.filter_map(|n| n.thread.id.and_then(|id| u64::try_from(id).ok()))
|
||||
.collect();
|
||||
let before_prune = delivered.len();
|
||||
delivered.retain(|id, _| current_ids.contains(id));
|
||||
|
|
@ -899,21 +935,31 @@ fn should_deliver(delivered: &HashMap<u64, String>, id: u64, updated_at: &str) -
|
|||
/// deliberately left unread for the read-before-comment guard, and a failed
|
||||
/// delivery is left unread + out of the dedupe cursor so it resurfaces on the
|
||||
/// next poll tick.
|
||||
async fn mark_read(client: &reqwest::Client, forge_url: &str, token: &str, id: u64) {
|
||||
let mark_url = format!("{forge_url}/api/v1/notifications/threads/{id}");
|
||||
match client
|
||||
.patch(&mark_url)
|
||||
.header("Authorization", format!("token {token}"))
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
Err(e) => {
|
||||
async fn mark_read(forge: &Forgejo, id: u64) {
|
||||
let Ok(thread_id) = i64::try_from(id) else {
|
||||
// Thread ids originate from `i64` in the poll parse, so an
|
||||
// unrepresentable value can't actually reach here.
|
||||
return;
|
||||
};
|
||||
// `to_status: None` → Forgejo's default transition (unread → read),
|
||||
// matching the old bare PATCH. The 205 response body is the thread
|
||||
// JSON, which can carry `subject.state = "merged"` — take it as an
|
||||
// opaque `String` (see `poll_once`) so a merged PR doesn't turn a
|
||||
// successful mark-read into a spurious parse error.
|
||||
let request = forge
|
||||
.notify_read_thread(thread_id, NotifyReadThreadQuery { to_status: None })
|
||||
.response_type::<String>();
|
||||
match tokio::time::timeout(Duration::from_secs(HTTP_TIMEOUT_SECS), request.send()).await {
|
||||
Err(_) => {
|
||||
warn!(%id, "forge_notify: mark-read request failed — notification will resurface");
|
||||
}
|
||||
Ok(Err(e @ ForgejoError::ReqwestError(_))) => {
|
||||
warn!(%id, error = ?e, "forge_notify: mark-read request failed — notification will resurface");
|
||||
}
|
||||
Ok(r) if !r.status().is_success() => {
|
||||
warn!(%id, status = %r.status(), "forge_notify: mark-read returned non-2xx — notification will resurface");
|
||||
Ok(Err(e)) => {
|
||||
warn!(%id, error = %e, "forge_notify: mark-read returned non-2xx — notification will resurface");
|
||||
}
|
||||
Ok(_) => {
|
||||
Ok(Ok(_)) => {
|
||||
debug!(%id, "forge_notify: marked read");
|
||||
}
|
||||
}
|
||||
|
|
@ -1129,39 +1175,98 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn parse_rfc3339_secs_handles_offsets_and_z() {
|
||||
// Same instant expressed three ways must parse equal.
|
||||
let utc = parse_rfc3339_secs("2026-06-13T09:18:42Z").unwrap();
|
||||
let plus2 = parse_rfc3339_secs("2026-06-13T11:18:42+02:00").unwrap();
|
||||
let minus5 = parse_rfc3339_secs("2026-06-13T04:18:42-05:00").unwrap();
|
||||
fn parse_rfc3339_handles_offsets_and_z() {
|
||||
// Same instant expressed three ways must parse equal
|
||||
// (`OffsetDateTime` comparison is instant-based).
|
||||
let utc = parse_rfc3339("2026-06-13T09:18:42Z").unwrap();
|
||||
let plus2 = parse_rfc3339("2026-06-13T11:18:42+02:00").unwrap();
|
||||
let minus5 = parse_rfc3339("2026-06-13T04:18:42-05:00").unwrap();
|
||||
assert_eq!(utc, plus2);
|
||||
assert_eq!(utc, minus5);
|
||||
// Fractional seconds are skipped (second granularity).
|
||||
assert_eq!(parse_rfc3339_secs("2026-06-13T09:18:42.512Z").unwrap(), utc);
|
||||
// Fractional seconds parse; second-granularity comparison holds.
|
||||
assert_eq!(
|
||||
parse_rfc3339("2026-06-13T09:18:42.512Z")
|
||||
.unwrap()
|
||||
.unix_timestamp(),
|
||||
utc.unix_timestamp(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_rfc3339_secs_rejects_garbage() {
|
||||
assert!(parse_rfc3339_secs("").is_none());
|
||||
assert!(parse_rfc3339_secs("not-a-date").is_none());
|
||||
assert!(parse_rfc3339_secs("2026-06-13").is_none());
|
||||
fn parse_rfc3339_rejects_garbage() {
|
||||
assert!(parse_rfc3339("").is_none());
|
||||
assert!(parse_rfc3339("not-a-date").is_none());
|
||||
assert!(parse_rfc3339("2026-06-13").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notification_is_creation_flags_fresh_and_later_activity() {
|
||||
// Fresh PR: notification event time == created_at → "new".
|
||||
let fresh = serde_json::json!({ "updated_at": "2026-06-13T11:18:42+02:00" });
|
||||
let subject = serde_json::json!({ "created_at": "2026-06-13T11:18:40+02:00" });
|
||||
assert!(notification_is_creation(&fresh, Some(&subject)));
|
||||
|
||||
// Fresh PR: notification event time == created_at → "new".
|
||||
let fresh = parse_rfc3339("2026-06-13T11:18:42+02:00");
|
||||
assert!(notification_is_creation(fresh, Some(&subject)));
|
||||
|
||||
// Review hours later on the same PR → not a creation.
|
||||
let later = serde_json::json!({ "updated_at": "2026-06-13T14:55:00+02:00" });
|
||||
assert!(!notification_is_creation(&later, Some(&subject)));
|
||||
let later = parse_rfc3339("2026-06-13T14:55:00+02:00");
|
||||
assert!(!notification_is_creation(later, Some(&subject)));
|
||||
|
||||
// Missing timestamps → default to creation (preserve prior behavior).
|
||||
let empty = serde_json::json!({});
|
||||
assert!(notification_is_creation(&empty, None));
|
||||
assert!(notification_is_creation(&empty, Some(&subject)));
|
||||
assert!(notification_is_creation(None, None));
|
||||
assert!(notification_is_creation(None, Some(&subject)));
|
||||
assert!(notification_is_creation(
|
||||
fresh,
|
||||
Some(&serde_json::json!({}))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_notification_tolerates_merged_state() {
|
||||
// forgejo-api's `StateType` has no "merged" variant; the raw
|
||||
// extraction must keep the item parseable AND preserve the
|
||||
// string for the `PR merged` wrapper.
|
||||
let polled = parse_notification(serde_json::json!({
|
||||
"id": 7,
|
||||
"updated_at": "2026-06-13T11:18:42+02:00",
|
||||
"url": "http://forge/api/v1/notifications/threads/7",
|
||||
"subject": {
|
||||
"title": "t",
|
||||
"type": "Pull",
|
||||
"state": "merged",
|
||||
"html_url": "http://forge/o/r/pulls/5",
|
||||
"latest_comment_html_url": "",
|
||||
"latest_comment_url": "",
|
||||
"url": "http://forge/api/v1/repos/o/r/issues/5",
|
||||
},
|
||||
}))
|
||||
.expect("merged-state notification must parse");
|
||||
assert_eq!(polled.state, "merged");
|
||||
// Cursor string is the raw `updated_at`, byte-identical.
|
||||
assert_eq!(polled.updated_at, "2026-06-13T11:18:42+02:00");
|
||||
assert_eq!(polled.thread.id, Some(7));
|
||||
assert_eq!(
|
||||
polled.thread.subject.as_ref().and_then(|s| s.r#type),
|
||||
Some(NotifySubjectType::Pull),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_notification_missing_subject_degrades() {
|
||||
let polled = parse_notification(serde_json::json!({
|
||||
"id": 1,
|
||||
"updated_at": "2026-06-22T16:00:00Z",
|
||||
"url": "",
|
||||
}))
|
||||
.expect("subject-less notification must parse");
|
||||
assert_eq!(polled.state, "");
|
||||
assert!(polled.thread.subject.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_notification_rejects_unrepresentable_item() {
|
||||
// A non-object item can't become a `NotificationThread`; it is
|
||||
// dropped alone instead of failing the page.
|
||||
assert!(parse_notification(serde_json::json!("nonsense")).is_none());
|
||||
}
|
||||
|
||||
/// Build a `NotifMeta` for the state-change formatter tests. The `&str`
|
||||
|
|
@ -1169,7 +1274,7 @@ mod tests {
|
|||
fn state_change_meta(subject: serde_json::Value) -> NotifMeta<'static> {
|
||||
NotifMeta {
|
||||
title: "subject title",
|
||||
notif_type: "Issue",
|
||||
subject_type: Some(NotifySubjectType::Issue),
|
||||
html_url: "http://forge/issues/1",
|
||||
num: " #1".to_owned(),
|
||||
repo: " [agents/x]".to_owned(),
|
||||
|
|
@ -1183,15 +1288,13 @@ mod tests {
|
|||
fn state_change_drops_self_authored_creation() {
|
||||
// No timestamps ⇒ treated as a creation; poster login == own_login.
|
||||
let meta = state_change_meta(serde_json::json!({ "user": { "login": "damocles" } }));
|
||||
let notif = serde_json::json!({ "subject": { "state": "open" } });
|
||||
assert!(format_state_change_notification(¬if, &meta, "damocles").is_none());
|
||||
assert!(format_state_change_notification(None, "open", &meta, "damocles").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_change_keeps_other_authored_creation() {
|
||||
let meta = state_change_meta(serde_json::json!({ "user": { "login": "someone-else" } }));
|
||||
let notif = serde_json::json!({ "subject": { "state": "open" } });
|
||||
assert!(format_state_change_notification(¬if, &meta, "damocles").is_some());
|
||||
assert!(format_state_change_notification(None, "open", &meta, "damocles").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1203,10 +1306,7 @@ mod tests {
|
|||
"user": { "login": "damocles" },
|
||||
"created_at": "2020-01-01T00:00:00Z",
|
||||
}));
|
||||
let notif = serde_json::json!({
|
||||
"subject": { "state": "closed" },
|
||||
"updated_at": "2026-06-22T16:00:00Z",
|
||||
});
|
||||
assert!(format_state_change_notification(¬if, &meta, "damocles").is_some());
|
||||
let event = parse_rfc3339("2026-06-22T16:00:00Z");
|
||||
assert!(format_state_change_notification(event, "closed", &meta, "damocles").is_some());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
//! Shared in-container harness code for the single `hive` binary that
|
||||
//! serves every agent role (the manager is just an agent role, not a
|
||||
//! separate binary).
|
||||
//! Shared in-container harness code for the sibling `hive-agent` /
|
||||
//! `hive-agent-mcp` / `hive-agent-wake` binaries, which serve every
|
||||
//! agent role (the manager is just an agent role, not a separate set
|
||||
//! of binaries).
|
||||
|
||||
pub mod client;
|
||||
pub mod events;
|
||||
|
|
|
|||
|
|
@ -330,13 +330,13 @@ fn load_extra_mcp() -> std::collections::BTreeMap<String, ExtraMcpServer> {
|
|||
}
|
||||
|
||||
/// Render the MCP config blob claude reads from `--mcp-config <path>`.
|
||||
/// `agent_binary` is the path (or PATH-resolvable name) of the `hive-ag3nt`
|
||||
/// executable; `socket` is the hyperhive per-agent socket bind-mounted into
|
||||
/// the container (forwarded to the child as `--socket <path>`). Merges in
|
||||
/// any extra MCP servers declared via `hyperhive.extraMcpServers` in the
|
||||
/// agent's NixOS config.
|
||||
/// `mcp_binary` is the path (or PATH-resolvable name) of the
|
||||
/// `hive-agent-mcp` bridge executable; `socket` is the hyperhive per-agent
|
||||
/// socket bind-mounted into the container (forwarded to the child as
|
||||
/// `--socket <path>`). Merges in any extra MCP servers declared via
|
||||
/// `hyperhive.extraMcpServers` in the agent's NixOS config.
|
||||
#[must_use]
|
||||
pub fn render_claude_config(agent_binary: &str, socket: &std::path::Path) -> String {
|
||||
pub fn render_claude_config(mcp_binary: &str, socket: &std::path::Path) -> String {
|
||||
let mut servers = serde_json::Map::new();
|
||||
// When the harness is configured to run the built-in server as a
|
||||
// persistent streamable-http daemon (loopback port in
|
||||
|
|
@ -353,8 +353,8 @@ pub fn render_claude_config(agent_binary: &str, socket: &std::path::Path) -> Str
|
|||
"url": format!("http://127.0.0.1:{port}/mcp"),
|
||||
}),
|
||||
None => serde_json::json!({
|
||||
"command": agent_binary,
|
||||
"args": ["--socket", socket.display().to_string(), "mcp"],
|
||||
"command": mcp_binary,
|
||||
"args": ["--socket", socket.display().to_string()],
|
||||
"env": {}
|
||||
}),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
//! Pure helpers factored out of the `hive` serve loop (`bin/hive.rs`).
|
||||
//! Pure helpers factored out of the harness serve loop
|
||||
//! (`bin/hive-agent.rs`).
|
||||
//! Only functions with no wire-type dependency live here;
|
||||
//! request/response-flavored helpers (`requeue_inflight`, `ack_turn`, etc.)
|
||||
//! stay in the binary because they touch the request enum variants directly.
|
||||
|
|
@ -60,7 +61,7 @@ pub struct TurnRowArgs<'a> {
|
|||
}
|
||||
|
||||
/// Assemble a `TurnStatRow` from the harness's per-turn state. Lives here
|
||||
/// (rather than inline in the `hive` serve loop) so it stays wire-type-free
|
||||
/// (rather than inline in the serve loop) so it stays wire-type-free
|
||||
/// and unit-testable; the binary just feeds it the post-turn counts.
|
||||
#[must_use]
|
||||
pub fn build_row(args: TurnRowArgs<'_>) -> TurnStatRow {
|
||||
|
|
|
|||
|
|
@ -108,8 +108,9 @@ impl TurnFiles {
|
|||
|
||||
/// Drop the MCP config blob claude reads from `--mcp-config <path>`.
|
||||
/// `socket` is the hyperhive per-container socket (forwarded to the child
|
||||
/// as `--socket <path>`). The MCP subcommand is always `mcp` on the single
|
||||
/// `hive` binary resolved from `/proc/self/exe`.
|
||||
/// as `--socket <path>`). The MCP server is the `hive-agent-mcp` binary
|
||||
/// installed next to the running `hive-agent` (resolved as a sibling of
|
||||
/// `/proc/self/exe`; PATH-resolvable name as the fallback).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
|
|
@ -120,7 +121,8 @@ pub async fn write_mcp_config(socket: &Path) -> Result<PathBuf> {
|
|||
let path = parent.join("claude-mcp-config.json");
|
||||
let exe = std::env::current_exe()
|
||||
.ok()
|
||||
.map_or_else(|| "hive".into(), |p| p.display().to_string());
|
||||
.and_then(|p| Some(p.parent()?.join("hive-agent-mcp")))
|
||||
.map_or_else(|| "hive-agent-mcp".into(), |p| p.display().to_string());
|
||||
let body = mcp_config::render_claude_config(&exe, socket);
|
||||
tokio::fs::write(&path, body).await?;
|
||||
tracing::info!(path = %path.display(), "wrote claude MCP config");
|
||||
|
|
@ -146,7 +148,7 @@ pub async fn write_system_prompt(socket: &Path, label: &str) -> Result<PathBuf>
|
|||
/// `result_kind = "compacted"` in turn stats so the stats page can distinguish
|
||||
/// those turns. Both `Ok(true)` and `Ok(false)` are ack'd; the error cases
|
||||
/// each map to a distinct serve-loop action (see [`emit_turn_end`] and the
|
||||
/// `hive` serve loop).
|
||||
/// `hive-agent` serve loop).
|
||||
pub type TurnOutcome = std::result::Result<bool, TurnError>;
|
||||
|
||||
/// The ways a turn can end without a usable result. Each is deliberately *not*
|
||||
|
|
@ -287,7 +289,7 @@ pub fn make_session(bus: &Bus) -> AgentSession {
|
|||
/// the whole turn is retried a single time before bubbling `AuthFailed` to
|
||||
/// the serve loop (which parks for re-login).
|
||||
///
|
||||
/// Called once per turn by the `hive` serve loop, which owns the shared
|
||||
/// Called once per turn by the `hive-agent` serve loop, which owns the shared
|
||||
/// `session` ([`make_session`]) and threads it in.
|
||||
pub async fn drive_turn(
|
||||
prompt: &str,
|
||||
|
|
|
|||
|
|
@ -12,6 +12,8 @@ chrono.workspace = true
|
|||
base64.workspace = true
|
||||
bcrypt.workspace = true
|
||||
reqwest.workspace = true
|
||||
forgejo-api.workspace = true
|
||||
url.workspace = true
|
||||
clap.workspace = true
|
||||
clap_complete.workspace = true
|
||||
clap-markdown = "0.1"
|
||||
|
|
|
|||
|
|
@ -18,8 +18,11 @@ pub use repos::{
|
|||
};
|
||||
pub use users::{core_token, ensure_user_for, provision_user_token};
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use reqwest::StatusCode;
|
||||
use forgejo_api::{Auth, Forgejo};
|
||||
use url::Url;
|
||||
|
||||
use repos::{ensure_mirrors, ensure_operators_team, ensure_org};
|
||||
use users::{
|
||||
|
|
@ -105,34 +108,20 @@ async fn forge_admin(args: &[&str]) -> Result<String> {
|
|||
Ok(stdout)
|
||||
}
|
||||
|
||||
/// Thin Forgejo REST helper. Sends `method` to `url` with a JSON body
|
||||
/// and `Authorization: token <token>`, returns the HTTP status code.
|
||||
/// All Forgejo API calls that don't shell out to `forgejo admin` go
|
||||
/// through here — one place for auth header, content-type, error
|
||||
/// propagation, and the shared reqwest Client.
|
||||
/// Returns the response status **and body**. The body lets callers log
|
||||
/// *why* Forgejo rejected a request (e.g. the validation message on a
|
||||
/// 422); status-only callers just bind `(status, _)`. Body read is
|
||||
/// best-effort — a read error yields an empty string rather than
|
||||
/// failing the whole call.
|
||||
async fn forge_http(
|
||||
method: reqwest::Method,
|
||||
url: &str,
|
||||
token: &str,
|
||||
body: &str,
|
||||
) -> Result<(StatusCode, String)> {
|
||||
let client = reqwest::Client::new();
|
||||
let resp = client
|
||||
.request(method, url)
|
||||
.header("Authorization", format!("token {token}"))
|
||||
.header("Content-Type", "application/json")
|
||||
.body(body.to_owned())
|
||||
.send()
|
||||
.await
|
||||
.with_context(|| format!("forge HTTP request to {url}"))?;
|
||||
let status = resp.status();
|
||||
let text = resp.text().await.unwrap_or_default();
|
||||
Ok((status, text))
|
||||
/// Typed Forgejo API client for the local forge ([`FORGE_HTTP`]),
|
||||
/// authenticated as `token`. All Forgejo API calls that don't shell
|
||||
/// out to `forgejo admin` go through clients built here — one place
|
||||
/// for the base URL and auth. Tokens differ per call site (core admin
|
||||
/// token vs per-agent tokens), so the token is passed per call; the
|
||||
/// base URL is parsed once. Failures surface as
|
||||
/// `forgejo_api::ForgejoError`, whose Display carries the HTTP status
|
||||
/// and the API's error message (e.g. the validation reason on a 422).
|
||||
pub(crate) fn api(token: &str) -> Result<Forgejo> {
|
||||
static URL: OnceLock<Url> = OnceLock::new();
|
||||
let url = URL
|
||||
.get_or_init(|| Url::parse(FORGE_HTTP).expect("FORGE_HTTP is a valid URL"))
|
||||
.clone();
|
||||
Forgejo::new(Auth::Token(token), url).context("build forgejo api client")
|
||||
}
|
||||
|
||||
/// Whether `ns` is a hive-managed Forgejo namespace that agent-initiated
|
||||
|
|
|
|||
|
|
@ -4,10 +4,12 @@
|
|||
//! boundary; moved verbatim from the `forge` module root.
|
||||
|
||||
use anyhow::Context;
|
||||
use forgejo_api::ForgejoError;
|
||||
use forgejo_api::structs::{MergePullRequestOption, MergePullRequestOptionDo};
|
||||
|
||||
use crate::coordinator::Coordinator;
|
||||
|
||||
use super::{CONFIG_ORG, FORGE_HTTP, core_token, forge_http};
|
||||
use super::{CONFIG_ORG, api, core_token};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PR-based config-flow merge primitives (part of the
|
||||
|
|
@ -242,35 +244,57 @@ pub async fn ff_push_to_main(repo: &str, sha: &str) -> Result<(), ForgeMergeErro
|
|||
}
|
||||
|
||||
/// Mark PR `pr` as **manually merged** at `sha` (Forgejo
|
||||
/// `POST …/pulls/{pr}/merge` with `Do=manually-merged`, `MergeCommitID=sha`).
|
||||
/// `repo_merge_pull_request` with `Do=manually-merged`, `MergeCommitID=sha`).
|
||||
/// `ff_push_to_main` must have already set `main` to `sha` (Forgejo requires
|
||||
/// the branch already be at the merge commit). On a non-2xx, re-reads the PR
|
||||
/// head to distinguish drift (`HeadDrift`) from a generic failure (`Other`) —
|
||||
/// best-effort, since the handler's pre-merge head re-read is the real gate.
|
||||
/// the branch already be at the merge commit). On an API rejection, re-reads
|
||||
/// the PR head to distinguish drift (`HeadDrift`) from a generic failure
|
||||
/// (`Other`) — best-effort, since the handler's pre-merge head re-read is
|
||||
/// the real gate. A transport failure skips the drift re-read (it couldn't
|
||||
/// reach the forge either) and surfaces as `Other` directly.
|
||||
///
|
||||
/// # Errors
|
||||
/// `HeadDrift` if the PR head no longer matches `sha`; `Other` otherwise.
|
||||
pub async fn mark_pr_merged(repo: &str, pr: u64, sha: &str) -> Result<(), ForgeMergeError> {
|
||||
let token = core_token()
|
||||
.ok_or_else(|| ForgeMergeError::Other(anyhow::anyhow!("forge core token absent")))?;
|
||||
let url = format!("{FORGE_HTTP}/api/v1/repos/{repo}/pulls/{pr}/merge");
|
||||
let body = format!(r#"{{"Do":"manually-merged","MergeCommitID":"{sha}"}}"#);
|
||||
let (status, _) = forge_http(reqwest::Method::POST, &url, &token, &body)
|
||||
let (owner, name) = repo.split_once('/').ok_or_else(|| {
|
||||
ForgeMergeError::Other(anyhow::anyhow!("forge repo `{repo}` is not owner/name"))
|
||||
})?;
|
||||
let index = i64::try_from(pr)
|
||||
.map_err(|_| ForgeMergeError::Other(anyhow::anyhow!("PR index {pr} overflows i64")))?;
|
||||
let body = MergePullRequestOption {
|
||||
r#do: MergePullRequestOptionDo::ManuallyMerged,
|
||||
merge_commit_id: Some(sha.to_owned()),
|
||||
merge_message_field: None,
|
||||
merge_title_field: None,
|
||||
delete_branch_after_merge: None,
|
||||
force_merge: None,
|
||||
head_commit_id: None,
|
||||
merge_when_checks_succeed: None,
|
||||
};
|
||||
let client = api(&token).map_err(ForgeMergeError::Other)?;
|
||||
match client
|
||||
.repo_merge_pull_request(owner, name, index, body)
|
||||
.await
|
||||
.context("POST pulls/<pr>/merge (manually-merged)")?;
|
||||
if status.is_success() {
|
||||
return Ok(());
|
||||
}
|
||||
// Best-effort drift detection: if the live head no longer matches `sha`,
|
||||
// that's a head-drift race; otherwise surface as a hard failure.
|
||||
match pr_head_sha(repo, pr).await {
|
||||
Ok(actual) if actual != sha => Err(ForgeMergeError::HeadDrift {
|
||||
expected: sha.to_string(),
|
||||
actual,
|
||||
}),
|
||||
_ => Err(ForgeMergeError::Other(anyhow::anyhow!(
|
||||
"mark PR #{pr} in {repo} manually-merged at {sha} failed: HTTP {status}"
|
||||
))),
|
||||
{
|
||||
Ok(()) => Ok(()),
|
||||
Err(ForgejoError::ReqwestError(e)) => Err(ForgeMergeError::Other(
|
||||
anyhow::Error::from(e).context("POST pulls/<pr>/merge (manually-merged)"),
|
||||
)),
|
||||
Err(e) => {
|
||||
// Best-effort drift detection: if the live head no longer matches
|
||||
// `sha`, that's a head-drift race; otherwise surface as a hard
|
||||
// failure.
|
||||
match pr_head_sha(repo, pr).await {
|
||||
Ok(actual) if actual != sha => Err(ForgeMergeError::HeadDrift {
|
||||
expected: sha.to_string(),
|
||||
actual,
|
||||
}),
|
||||
_ => Err(ForgeMergeError::Other(anyhow::Error::from(e).context(
|
||||
format!("mark PR #{pr} in {repo} manually-merged at {sha}"),
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,99 +1,190 @@
|
|||
//! Repo + org plumbing on the local Forgejo: org / repo creation,
|
||||
//! the meta + shared-docs + knowledge repos, per-agent config-repo
|
||||
//! mirroring (`push_config` / `push_meta`), collaborator grants,
|
||||
//! pull-mirrors, and branch-protection rules. Shared HTTP helpers +
|
||||
//! org-name constants live in the module root (`super`).
|
||||
//! pull-mirrors, and branch-protection rules. The typed API-client
|
||||
//! constructor + org-name constants live in the module root (`super`).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use forgejo_api::structs::{
|
||||
AddCollaboratorOption, AddCollaboratorOptionPermission, CreateBranchProtectionOption,
|
||||
CreateOrgOption, CreateRepoOption, CreateTeamOption, CreateTeamOptionPermission,
|
||||
EditRepoOption, MigrateRepoOptions, MigrateRepoOptionsService, Repository,
|
||||
};
|
||||
use forgejo_api::{ApiErrorKind, ForgejoError};
|
||||
use reqwest::StatusCode;
|
||||
use tokio::process::Command;
|
||||
|
||||
use crate::coordinator::Coordinator;
|
||||
|
||||
use super::{
|
||||
AGENTS_ORG, CONFIG_ORG, FORGE_HTTP, KNOWLEDGE_REPO, OPERATORS_TEAM, SHARED_DOCS_REPO,
|
||||
SHARED_ORG, core_token, forge_http, is_present,
|
||||
SHARED_ORG, api, core_token, is_present,
|
||||
};
|
||||
|
||||
/// JSON body for a private, empty repo defaulting to `main`.
|
||||
fn repo_body(name: &str) -> String {
|
||||
format!(r#"{{"name":"{name}","auto_init":false,"private":true,"default_branch":"main"}}"#)
|
||||
/// Creation options for an empty repo defaulting to `main`.
|
||||
fn repo_option(name: &str, private: bool) -> CreateRepoOption {
|
||||
CreateRepoOption {
|
||||
auto_init: Some(false),
|
||||
default_branch: Some("main".to_owned()),
|
||||
description: None,
|
||||
gitignores: None,
|
||||
issue_labels: None,
|
||||
license: None,
|
||||
name: name.to_owned(),
|
||||
object_format_name: None,
|
||||
private: Some(private),
|
||||
readme: None,
|
||||
template: None,
|
||||
trust_model: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON body for a public, empty repo defaulting to `main`.
|
||||
fn repo_body_public(name: &str) -> String {
|
||||
format!(r#"{{"name":"{name}","auto_init":false,"private":false,"default_branch":"main"}}"#)
|
||||
/// `EditRepoOption` with every field unset — repo edits only ever
|
||||
/// change the one field the caller sets on top (Forgejo leaves `None`
|
||||
/// fields untouched).
|
||||
fn sparse_edit_repo_option() -> EditRepoOption {
|
||||
EditRepoOption {
|
||||
allow_fast_forward_only_merge: None,
|
||||
allow_manual_merge: None,
|
||||
allow_merge_commits: None,
|
||||
allow_rebase: None,
|
||||
allow_rebase_explicit: None,
|
||||
allow_rebase_update: None,
|
||||
allow_squash_merge: None,
|
||||
archived: None,
|
||||
autodetect_manual_merge: None,
|
||||
default_allow_maintainer_edit: None,
|
||||
default_branch: None,
|
||||
default_delete_branch_after_merge: None,
|
||||
default_merge_style: None,
|
||||
default_update_style: None,
|
||||
description: None,
|
||||
enable_prune: None,
|
||||
external_tracker: None,
|
||||
external_wiki: None,
|
||||
globally_editable_wiki: None,
|
||||
has_actions: None,
|
||||
has_issues: None,
|
||||
has_packages: None,
|
||||
has_projects: None,
|
||||
has_pull_requests: None,
|
||||
has_releases: None,
|
||||
has_wiki: None,
|
||||
ignore_whitespace_conflicts: None,
|
||||
internal_tracker: None,
|
||||
mirror_interval: None,
|
||||
name: None,
|
||||
private: None,
|
||||
template: None,
|
||||
website: None,
|
||||
wiki_branch: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a create-style call failed because the object already
|
||||
/// exists. Forgejo signals this as HTTP 409 (conflict) or 422
|
||||
/// (validation). The typed client surfaces those as
|
||||
/// `ApiErrorKind::Other(409)` / `ValidationFailed` when the endpoint
|
||||
/// spec lists the status, or as a bare `UnexpectedStatusCode`
|
||||
/// otherwise — match all shapes defensively.
|
||||
fn is_already_exists(e: &ForgejoError) -> bool {
|
||||
match e {
|
||||
ForgejoError::ApiError(api) => match api.error_kind() {
|
||||
ApiErrorKind::ValidationFailed => true,
|
||||
ApiErrorKind::Other(s) => *s == StatusCode::CONFLICT,
|
||||
_ => false,
|
||||
},
|
||||
ForgejoError::UnexpectedStatusCode(s) => {
|
||||
*s == StatusCode::CONFLICT || *s == StatusCode::UNPROCESSABLE_ENTITY
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an error is specifically an HTTP 409 conflict (and NOT a
|
||||
/// 422): the migrate endpoint's 422 is a validation error (bad
|
||||
/// `clone_addr` / service) and must surface, so it can't share
|
||||
/// [`is_already_exists`]'s 422 tolerance.
|
||||
fn is_conflict(e: &ForgejoError) -> bool {
|
||||
match e {
|
||||
ForgejoError::ApiError(api) => {
|
||||
matches!(api.error_kind(), ApiErrorKind::Other(s) if *s == StatusCode::CONFLICT)
|
||||
}
|
||||
ForgejoError::UnexpectedStatusCode(s) => *s == StatusCode::CONFLICT,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an error is Forgejo saying 404 — the resource is absent,
|
||||
/// as opposed to a transport / auth / server failure.
|
||||
fn is_not_found(e: &ForgejoError) -> bool {
|
||||
match e {
|
||||
ForgejoError::ApiError(api) => {
|
||||
matches!(api.error_kind(), ApiErrorKind::NotFound { .. })
|
||||
}
|
||||
ForgejoError::UnexpectedStatusCode(s) => *s == StatusCode::NOT_FOUND,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Fold a repo-creation result's "already exists" (409 / 422) into
|
||||
/// success. `label` is `<owner>/<name>` — purely for log + error
|
||||
/// context.
|
||||
fn created_or_exists(res: Result<Repository, ForgejoError>, label: &str) -> Result<()> {
|
||||
match res {
|
||||
Ok(_) => {
|
||||
tracing::info!(%label, "forge: created repo");
|
||||
Ok(())
|
||||
}
|
||||
Err(e) if is_already_exists(&e) => {
|
||||
tracing::debug!(%label, "forge: repo already exists");
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(e).with_context(|| format!("create repo {label}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set an existing repo to public visibility. No-op if the repo is
|
||||
/// already public. Used for `internal/knowledge` which may have been
|
||||
/// created as private on an older deployment.
|
||||
async fn set_repo_public(owner: &str, repo: &str, token: &str) -> Result<()> {
|
||||
let url = format!("{FORGE_HTTP}/api/v1/repos/{owner}/{repo}");
|
||||
let (status, _) =
|
||||
forge_http(reqwest::Method::PATCH, &url, token, r#"{"private":false}"#).await?;
|
||||
match status.as_u16() {
|
||||
200 => {
|
||||
tracing::debug!(%owner, %repo, "forge: repo set to public");
|
||||
Ok(())
|
||||
}
|
||||
other => anyhow::bail!("PATCH {owner}/{repo} (set public) returned HTTP {other}"),
|
||||
}
|
||||
let mut edit = sparse_edit_repo_option();
|
||||
edit.private = Some(false);
|
||||
api(token)?
|
||||
.repo_edit(owner, repo, edit)
|
||||
.await
|
||||
.with_context(|| format!("edit {owner}/{repo} (set public)"))?;
|
||||
tracing::debug!(%owner, %repo, "forge: repo set to public");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Create `name` inside org `org` as a public repo. Idempotent.
|
||||
async fn ensure_org_repo_public(org: &str, name: &str, token: &str) -> Result<()> {
|
||||
create_repo(
|
||||
&format!("{FORGE_HTTP}/api/v1/orgs/{org}/repos"),
|
||||
&repo_body_public(name),
|
||||
token,
|
||||
&format!("{org}/{name}"),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// POST a repo-creation request to `url` and fold "already exists"
|
||||
/// (HTTP 409 / 422) into success. `label` is `<owner>/<name>` — purely
|
||||
/// for log + error context.
|
||||
async fn create_repo(url: &str, body: &str, token: &str, label: &str) -> Result<()> {
|
||||
let (status, _) = forge_http(reqwest::Method::POST, url, token, body).await?;
|
||||
match status.as_u16() {
|
||||
201 => {
|
||||
tracing::info!(%label, "forge: created repo");
|
||||
Ok(())
|
||||
}
|
||||
409 | 422 => {
|
||||
tracing::debug!(%label, "forge: repo already exists");
|
||||
Ok(())
|
||||
}
|
||||
other => anyhow::bail!("POST {url} ({label}) returned HTTP {other}"),
|
||||
}
|
||||
let res = api(token)?
|
||||
.create_org_repo(org, repo_option(name, false))
|
||||
.await;
|
||||
created_or_exists(res, &format!("{org}/{name}"))
|
||||
}
|
||||
|
||||
/// Create a repo in the token-owner's own namespace. `token` belongs
|
||||
/// to the user we want the repo owned by (we use `core`'s token for
|
||||
/// `core/meta`). Idempotent.
|
||||
pub async fn ensure_repo(name: &str, token: &str) -> Result<()> {
|
||||
create_repo(
|
||||
&format!("{FORGE_HTTP}/api/v1/user/repos"),
|
||||
&repo_body(name),
|
||||
token,
|
||||
&format!("core/{name}"),
|
||||
)
|
||||
.await
|
||||
let res = api(token)?
|
||||
.create_current_user_repo(repo_option(name, true))
|
||||
.await;
|
||||
created_or_exists(res, &format!("core/{name}"))
|
||||
}
|
||||
|
||||
/// Create `name` inside org `org` (used for `agent-configs/<agent>`).
|
||||
/// Idempotent.
|
||||
async fn ensure_org_repo(org: &str, name: &str, token: &str) -> Result<()> {
|
||||
create_repo(
|
||||
&format!("{FORGE_HTTP}/api/v1/orgs/{org}/repos"),
|
||||
&repo_body(name),
|
||||
token,
|
||||
&format!("{org}/{name}"),
|
||||
)
|
||||
.await
|
||||
let res = api(token)?
|
||||
.create_org_repo(org, repo_option(name, true))
|
||||
.await;
|
||||
created_or_exists(res, &format!("{org}/{name}"))
|
||||
}
|
||||
|
||||
/// Push `dir` (the meta repo) to `core/meta` on the local forge.
|
||||
|
|
@ -141,7 +232,14 @@ pub async fn ensure_config_repo(name: &str) -> Result<()> {
|
|||
ensure_org_repo(CONFIG_ORG, name, &token).await?;
|
||||
// Agent = write collaborator: it can push config-PR branches + open PRs,
|
||||
// but the branch protection below keeps it off `main` directly.
|
||||
add_collaborator(CONFIG_ORG, name, name, "write", &token).await?;
|
||||
add_collaborator(
|
||||
CONFIG_ORG,
|
||||
name,
|
||||
name,
|
||||
AddCollaboratorOptionPermission::Write,
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
// Protect `main` core-only, fast-forward-only (no auto force-push).
|
||||
apply_config_repo_branch_protection(name, &token).await
|
||||
}
|
||||
|
|
@ -154,43 +252,20 @@ pub async fn ensure_shared_docs_repo(core_token: &str) -> Result<()> {
|
|||
}
|
||||
|
||||
/// Grant agent `name` read-only collaborator access to `internal/docs`.
|
||||
/// Idempotent: HTTP 204 (already a collaborator) is treated as success.
|
||||
/// Mirrors `meta_read_access` so agents can clone the shared docs repo
|
||||
/// without authentication hassle.
|
||||
/// Idempotent: re-adding an existing collaborator succeeds (Forgejo
|
||||
/// answers 204 either way). Mirrors `meta_read_access` so agents can
|
||||
/// clone the shared docs repo without authentication hassle.
|
||||
pub async fn shared_docs_access(name: &str, core_token: &str) -> Result<()> {
|
||||
let url =
|
||||
format!("{FORGE_HTTP}/api/v1/repos/{SHARED_ORG}/{SHARED_DOCS_REPO}/collaborators/{name}");
|
||||
let body = r#"{"permission":"read"}"#;
|
||||
let out = Command::new("curl")
|
||||
.args([
|
||||
"-sS",
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-w",
|
||||
"%{http_code}",
|
||||
"-X",
|
||||
"PUT",
|
||||
"-H",
|
||||
"Content-Type: application/json",
|
||||
"-H",
|
||||
&format!("Authorization: token {core_token}"),
|
||||
"-d",
|
||||
body,
|
||||
&url,
|
||||
])
|
||||
.output()
|
||||
.await
|
||||
.context("invoke curl PUT internal/docs/collaborators")?;
|
||||
let code = String::from_utf8_lossy(&out.stdout).trim().to_owned();
|
||||
match code.as_str() {
|
||||
"204" => {
|
||||
tracing::info!(%name, "forge: granted shared-docs read access");
|
||||
Ok(())
|
||||
}
|
||||
other => anyhow::bail!(
|
||||
"PUT {SHARED_ORG}/{SHARED_DOCS_REPO}/collaborators/{name} returned HTTP {other}"
|
||||
),
|
||||
}
|
||||
add_collaborator(
|
||||
SHARED_ORG,
|
||||
SHARED_DOCS_REPO,
|
||||
name,
|
||||
AddCollaboratorOptionPermission::Read,
|
||||
core_token,
|
||||
)
|
||||
.await?;
|
||||
tracing::info!(%name, "forge: granted shared-docs read access");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ensure the `internal/knowledge` repo exists and is public.
|
||||
|
|
@ -208,38 +283,19 @@ pub async fn ensure_knowledge_repo(core_token: &str) -> Result<()> {
|
|||
|
||||
/// Grant agent `name` read-only collaborator access to `core/meta` on
|
||||
/// the forge so the agent can clone/fetch the meta flake. Idempotent:
|
||||
/// HTTP 204 (already a collaborator) is treated as success.
|
||||
/// re-adding an existing collaborator succeeds (Forgejo answers 204
|
||||
/// either way).
|
||||
pub async fn meta_read_access(name: &str, core_token: &str) -> Result<()> {
|
||||
let url = format!("{FORGE_HTTP}/api/v1/repos/core/meta/collaborators/{name}");
|
||||
let body = r#"{"permission":"read"}"#;
|
||||
let out = Command::new("curl")
|
||||
.args([
|
||||
"-sS",
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-w",
|
||||
"%{http_code}",
|
||||
"-X",
|
||||
"PUT",
|
||||
"-H",
|
||||
"Content-Type: application/json",
|
||||
"-H",
|
||||
&format!("Authorization: token {core_token}"),
|
||||
"-d",
|
||||
body,
|
||||
&url,
|
||||
])
|
||||
.output()
|
||||
.await
|
||||
.context("invoke curl PUT core/meta/collaborators")?;
|
||||
let code = String::from_utf8_lossy(&out.stdout).trim().to_owned();
|
||||
match code.as_str() {
|
||||
"204" => {
|
||||
tracing::info!(%name, "forge: granted meta read access");
|
||||
Ok(())
|
||||
}
|
||||
other => anyhow::bail!("PUT core/meta/collaborators/{name} returned HTTP {other}"),
|
||||
}
|
||||
add_collaborator(
|
||||
"core",
|
||||
"meta",
|
||||
name,
|
||||
AddCollaboratorOptionPermission::Read,
|
||||
core_token,
|
||||
)
|
||||
.await?;
|
||||
tracing::info!(%name, "forge: granted meta read access");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add `http://localhost:3000/core/meta.git` as the `meta` remote in
|
||||
|
|
@ -339,22 +395,29 @@ pub async fn push_config(name: &str) -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// POST `/api/v1/orgs` to create an org named `name`. Idempotent:
|
||||
/// HTTP 422 ("user already exists") is treated as success.
|
||||
/// Create an org named `name` (`org_create`). Idempotent: HTTP 422
|
||||
/// ("user already exists") / 409 is treated as success.
|
||||
pub(super) async fn ensure_org(name: &str, admin_token: &str) -> Result<()> {
|
||||
let body = format!(r#"{{"username":"{name}"}}"#);
|
||||
let url = format!("{FORGE_HTTP}/api/v1/orgs");
|
||||
let (status, _) = forge_http(reqwest::Method::POST, &url, admin_token, &body).await?;
|
||||
match status.as_u16() {
|
||||
201 => {
|
||||
let org = CreateOrgOption {
|
||||
description: None,
|
||||
email: None,
|
||||
full_name: None,
|
||||
location: None,
|
||||
repo_admin_change_team_access: None,
|
||||
username: name.to_owned(),
|
||||
visibility: None,
|
||||
website: None,
|
||||
};
|
||||
match api(admin_token)?.org_create(org).await {
|
||||
Ok(_) => {
|
||||
tracing::info!(%name, "forge: created org");
|
||||
Ok(())
|
||||
}
|
||||
422 | 409 => {
|
||||
Err(e) if is_already_exists(&e) => {
|
||||
tracing::debug!(%name, "forge: org already exists");
|
||||
Ok(())
|
||||
}
|
||||
other => anyhow::bail!("POST /api/v1/orgs name={name} returned HTTP {other}"),
|
||||
Err(e) => Err(e).with_context(|| format!("create org {name}")),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -414,63 +477,82 @@ const MIRROR_INTERVAL: &str = "8h0m0s";
|
|||
/// Idempotent: if the repo already exists this function patches its
|
||||
/// `mirror_interval` to ensure it matches (covers mirrors that were
|
||||
/// created before the interval was introduced). A 409 on the migrate
|
||||
/// POST (a race between the GET check and the POST) is also success.
|
||||
/// call (a race between the existence check and the migrate) is also
|
||||
/// success.
|
||||
async fn ensure_mirror_repo(
|
||||
upstream: &str,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
admin_token: &str,
|
||||
) -> Result<()> {
|
||||
let repo_url = format!("{FORGE_HTTP}/api/v1/repos/{owner}/{repo}");
|
||||
let (status, _) = forge_http(reqwest::Method::GET, &repo_url, admin_token, "").await?;
|
||||
if status.is_success() {
|
||||
// Mirror already present. Patch interval so mirrors seeded before
|
||||
// this field was introduced (or with a different value) converge.
|
||||
let patch_body = serde_json::json!({ "mirror_interval": MIRROR_INTERVAL }).to_string();
|
||||
let (patch_status, patch_text) =
|
||||
forge_http(reqwest::Method::PATCH, &repo_url, admin_token, &patch_body).await?;
|
||||
if patch_status.is_success() {
|
||||
tracing::debug!(%owner, %repo, interval = MIRROR_INTERVAL, "forge: pull-mirror interval updated");
|
||||
} else {
|
||||
tracing::warn!(
|
||||
%owner, %repo, status = %patch_status, body = %patch_text,
|
||||
"forge: failed to set mirror_interval on existing pull-mirror"
|
||||
);
|
||||
let client = api(admin_token)?;
|
||||
match client.repo_get(owner, repo).await {
|
||||
Ok(_) => {
|
||||
// Mirror already present. Patch interval so mirrors seeded before
|
||||
// this field was introduced (or with a different value) converge.
|
||||
let mut edit = sparse_edit_repo_option();
|
||||
edit.mirror_interval = Some(MIRROR_INTERVAL.to_owned());
|
||||
match client.repo_edit(owner, repo, edit).await {
|
||||
Ok(_) => {
|
||||
tracing::debug!(%owner, %repo, interval = MIRROR_INTERVAL, "forge: pull-mirror interval updated");
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
%owner, %repo, error = %e,
|
||||
"forge: failed to set mirror_interval on existing pull-mirror"
|
||||
);
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
// Absent — fall through to migrate.
|
||||
Err(e) if is_not_found(&e) => {}
|
||||
// Anything else (transport, auth, 5xx) leaves the repo's existence
|
||||
// unknown: migrating anyway would fold a 409 into success and skip
|
||||
// the interval patch this pass. Surface it instead.
|
||||
Err(e) => {
|
||||
return Err(e).with_context(|| format!("get pull-mirror {owner}/{repo}"));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
// serde_json::json! → the upstream URL is escaped safely (no string
|
||||
// interpolation into the JSON body).
|
||||
let body = serde_json::json!({
|
||||
"clone_addr": upstream,
|
||||
"repo_owner": owner,
|
||||
"repo_name": repo,
|
||||
"mirror": true,
|
||||
let opts = MigrateRepoOptions {
|
||||
auth_password: None,
|
||||
auth_token: None,
|
||||
auth_username: None,
|
||||
clone_addr: upstream.to_owned(),
|
||||
description: None,
|
||||
issues: None,
|
||||
labels: None,
|
||||
lfs: None,
|
||||
lfs_endpoint: None,
|
||||
milestones: None,
|
||||
mirror: Some(true),
|
||||
// Periodic refresh instead of on-access sync — keeps CI isolated
|
||||
// from external DNS failures at clone time.
|
||||
"interval": MIRROR_INTERVAL,
|
||||
"service": "git",
|
||||
"private": false,
|
||||
})
|
||||
.to_string();
|
||||
let url = format!("{FORGE_HTTP}/api/v1/repos/migrate");
|
||||
let (status, text) = forge_http(reqwest::Method::POST, &url, admin_token, &body).await?;
|
||||
match status.as_u16() {
|
||||
201 => {
|
||||
mirror_interval: Some(MIRROR_INTERVAL.to_owned()),
|
||||
private: Some(false),
|
||||
pull_requests: None,
|
||||
releases: None,
|
||||
repo_name: repo.to_owned(),
|
||||
repo_owner: Some(owner.to_owned()),
|
||||
service: Some(MigrateRepoOptionsService::Git),
|
||||
uid: None,
|
||||
wiki: None,
|
||||
};
|
||||
match client.repo_migrate(opts).await {
|
||||
Ok(_) => {
|
||||
tracing::info!(%owner, %repo, %upstream, interval = MIRROR_INTERVAL, "forge: created pull-mirror");
|
||||
Ok(())
|
||||
}
|
||||
// 409 = a race created it between our GET check and here (the GET
|
||||
// is the real idempotency guard). NOT 422: for the migrate endpoint
|
||||
// 422 is a validation error (bad clone_addr / service), so it must
|
||||
// surface via the bail arm, not be swallowed as "already exists".
|
||||
409 => {
|
||||
// 409 = a race created it between our existence check and here (the
|
||||
// check is the real idempotency guard). NOT 422: for the migrate
|
||||
// endpoint 422 is a validation error (bad clone_addr / service), so
|
||||
// it must surface via the error arm, not be swallowed as "already
|
||||
// exists" — hence `is_conflict`, not `is_already_exists`.
|
||||
Err(e) if is_conflict(&e) => {
|
||||
tracing::debug!(%owner, %repo, "forge: pull-mirror already exists (race)");
|
||||
Ok(())
|
||||
}
|
||||
other => {
|
||||
anyhow::bail!("POST /api/v1/repos/migrate {owner}/{repo} returned HTTP {other}: {text}")
|
||||
}
|
||||
Err(e) => Err(e).with_context(|| format!("migrate pull-mirror {owner}/{repo}")),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -488,48 +570,101 @@ async fn ensure_mirror_repo(
|
|||
/// repos unprotected — operator-merged config PRs then bypassed the deploy
|
||||
/// pipeline and silently didn't apply.
|
||||
pub(super) async fn ensure_operators_team(org: &str, token: &str) -> Result<()> {
|
||||
let url = format!("{FORGE_HTTP}/api/v1/orgs/{org}/teams");
|
||||
let body = format!(
|
||||
r#"{{"name":"{OPERATORS_TEAM}","description":"hyperhive operators — merge gate for agent repos","permission":"write","includes_all_repositories":true,"can_create_org_repo":false}}"#
|
||||
);
|
||||
let (status, _) = forge_http(reqwest::Method::POST, &url, token, &body).await?;
|
||||
match status.as_u16() {
|
||||
201 => {
|
||||
let team = CreateTeamOption {
|
||||
can_create_org_repo: Some(false),
|
||||
description: Some("hyperhive operators — merge gate for agent repos".to_owned()),
|
||||
includes_all_repositories: Some(true),
|
||||
name: OPERATORS_TEAM.to_owned(),
|
||||
permission: Some(CreateTeamOptionPermission::Write),
|
||||
units: None,
|
||||
units_map: None,
|
||||
};
|
||||
match api(token)?.org_create_team(org, team).await {
|
||||
Ok(_) => {
|
||||
tracing::info!(%org, "forge: created {OPERATORS_TEAM} team");
|
||||
Ok(())
|
||||
}
|
||||
409 | 422 => {
|
||||
Err(e) if is_already_exists(&e) => {
|
||||
tracing::debug!(%org, "forge: {OPERATORS_TEAM} team already exists");
|
||||
Ok(())
|
||||
}
|
||||
other => {
|
||||
anyhow::bail!("POST /orgs/{org}/teams ({OPERATORS_TEAM}) returned HTTP {other}")
|
||||
}
|
||||
Err(e) => Err(e).with_context(|| format!("create team {org}/{OPERATORS_TEAM}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Add `user` as a collaborator on `owner/repo` at `permission`
|
||||
/// (`read` / `write` / `admin`). Idempotent: 201 (added) and 204 (already a
|
||||
/// collaborator / permission updated) both count as success.
|
||||
/// Add `user` as a collaborator on `owner/repo` at `permission`.
|
||||
/// Idempotent: adding an existing collaborator just updates its
|
||||
/// permission (Forgejo answers 204 either way; a 201 from older
|
||||
/// versions is tolerated defensively).
|
||||
async fn add_collaborator(
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
user: &str,
|
||||
permission: &str,
|
||||
permission: AddCollaboratorOptionPermission,
|
||||
token: &str,
|
||||
) -> Result<()> {
|
||||
let url = format!("{FORGE_HTTP}/api/v1/repos/{owner}/{repo}/collaborators/{user}");
|
||||
let body = format!(r#"{{"permission":"{permission}"}}"#);
|
||||
let (status, _) = forge_http(reqwest::Method::PUT, &url, token, &body).await?;
|
||||
match status.as_u16() {
|
||||
201 | 204 => {
|
||||
tracing::debug!(%owner, %repo, %user, %permission, "forge: collaborator set");
|
||||
Ok(())
|
||||
}
|
||||
other => {
|
||||
anyhow::bail!("PUT {owner}/{repo}/collaborators/{user} returned HTTP {other}")
|
||||
let res = api(token)?
|
||||
.repo_add_collaborator(
|
||||
owner,
|
||||
repo,
|
||||
user,
|
||||
AddCollaboratorOption {
|
||||
permission: Some(permission),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
match res {
|
||||
Ok(()) => {}
|
||||
Err(ForgejoError::UnexpectedStatusCode(s)) if s == StatusCode::CREATED => {}
|
||||
Err(e) => {
|
||||
return Err(e).with_context(|| format!("add collaborator {user} to {owner}/{repo}"));
|
||||
}
|
||||
}
|
||||
tracing::debug!(%owner, %repo, %user, ?permission, "forge: collaborator set");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `CreateBranchProtectionOption` protecting `main` with every other
|
||||
/// field unset — Forgejo treats `None` fields as their defaults, same
|
||||
/// as the sparse JSON bodies the raw-HTTP predecessor sent. Callers
|
||||
/// set the whitelist/approval fields they need on top.
|
||||
fn main_branch_protection_option() -> CreateBranchProtectionOption {
|
||||
CreateBranchProtectionOption {
|
||||
apply_to_admins: None,
|
||||
approvals_whitelist_teams: None,
|
||||
approvals_whitelist_username: None,
|
||||
block_on_official_review_requests: None,
|
||||
block_on_outdated_branch: None,
|
||||
block_on_rejected_reviews: None,
|
||||
branch_name: Some("main".to_owned()),
|
||||
dismiss_stale_approvals: None,
|
||||
enable_approvals_whitelist: None,
|
||||
enable_merge_whitelist: None,
|
||||
enable_push: None,
|
||||
enable_push_whitelist: None,
|
||||
enable_status_check: None,
|
||||
ignore_stale_approvals: None,
|
||||
merge_whitelist_teams: None,
|
||||
merge_whitelist_usernames: None,
|
||||
protected_file_patterns: None,
|
||||
push_whitelist_deploy_keys: None,
|
||||
push_whitelist_teams: None,
|
||||
push_whitelist_usernames: None,
|
||||
require_signed_commits: None,
|
||||
required_approvals: None,
|
||||
rule_name: None,
|
||||
status_check_contexts: None,
|
||||
unprotected_file_patterns: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a branch-protection create failed because a rule for the
|
||||
/// branch already exists: 409/422 ([`is_already_exists`]) or the 200
|
||||
/// Forgejo answers instead of 201 for a duplicate rule (unlisted in
|
||||
/// the endpoint spec, so it surfaces as `UnexpectedStatusCode(200)`).
|
||||
fn is_protection_already_present(e: &ForgejoError) -> bool {
|
||||
is_already_exists(e)
|
||||
|| matches!(e, ForgejoError::UnexpectedStatusCode(s) if *s == StatusCode::OK)
|
||||
}
|
||||
|
||||
/// Apply the operator merge-gate branch protection to `repo`'s default
|
||||
|
|
@ -538,21 +673,26 @@ async fn add_collaborator(
|
|||
/// agent, not in the team) cannot merge its own PR. Idempotent: an existing
|
||||
/// rule for the branch (200/409/422) is treated as success.
|
||||
async fn apply_operator_branch_protection(repo: &str, token: &str) -> Result<()> {
|
||||
let url = format!("{FORGE_HTTP}/api/v1/repos/{AGENTS_ORG}/{repo}/branch_protections");
|
||||
let body = format!(
|
||||
r#"{{"branch_name":"main","enable_merge_whitelist":true,"merge_whitelist_teams":["{OPERATORS_TEAM}"],"enable_approvals_whitelist":true,"approvals_whitelist_teams":["{OPERATORS_TEAM}"],"required_approvals":1,"block_on_official_review_requests":true}}"#
|
||||
);
|
||||
let (status, _) = forge_http(reqwest::Method::POST, &url, token, &body).await?;
|
||||
match status.as_u16() {
|
||||
201 => {
|
||||
let mut rule = main_branch_protection_option();
|
||||
rule.enable_merge_whitelist = Some(true);
|
||||
rule.merge_whitelist_teams = Some(vec![OPERATORS_TEAM.to_owned()]);
|
||||
rule.enable_approvals_whitelist = Some(true);
|
||||
rule.approvals_whitelist_teams = Some(vec![OPERATORS_TEAM.to_owned()]);
|
||||
rule.required_approvals = Some(1);
|
||||
rule.block_on_official_review_requests = Some(true);
|
||||
match api(token)?
|
||||
.repo_create_branch_protection(AGENTS_ORG, repo, rule)
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
tracing::info!(%repo, "forge: applied operator branch protection");
|
||||
Ok(())
|
||||
}
|
||||
200 | 409 | 422 => {
|
||||
Err(e) if is_protection_already_present(&e) => {
|
||||
tracing::debug!(%repo, "forge: branch protection already present");
|
||||
Ok(())
|
||||
}
|
||||
other => anyhow::bail!("POST {AGENTS_ORG}/{repo}/branch_protections returned HTTP {other}"),
|
||||
Err(e) => Err(e).with_context(|| format!("create branch protection {AGENTS_ORG}/{repo}")),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -564,45 +704,63 @@ async fn apply_operator_branch_protection(repo: &str, token: &str) -> Result<()>
|
|||
/// (`run_merge_config_pr`). The agent can never push `main` directly.
|
||||
/// - **operator-team approval is required** to merge, and the author (not in
|
||||
/// the team) cannot self-approve.
|
||||
/// - **`enable_force_push` is `false`** — `main` only ever advances by
|
||||
/// - **force-pushing `main` stays impossible** — `main` only ever advances by
|
||||
/// fast-forward. The merge handler's `ff_push_to_main` is already a
|
||||
/// non-force push, so it lands fine. The legacy `push_config` mirror DOES
|
||||
/// force-push (it re-points status tags and rewinds `main` on a failed-build
|
||||
/// rollback), so the protection now rejects those non-ff updates — that
|
||||
/// rollback), so the protection rejects those non-ff updates — that
|
||||
/// mirror runs best-effort until the agent-opened PR-merge flow retires it.
|
||||
/// (Auto force-push is intentionally not allowed: per operator directive a
|
||||
/// silent force-push is a bug, not a feature.)
|
||||
/// silent force-push is a bug, not a feature. The raw-HTTP predecessor
|
||||
/// sent `"enable_force_push":false` + `"allow_manual_merge":true` in this
|
||||
/// body; neither is a `CreateBranchProtectionOption` field, so Forgejo
|
||||
/// ignored both keys — dropping them changes nothing: force-push
|
||||
/// protection defaults to off, and `allow_manual_merge` is a *repo*
|
||||
/// setting, not a branch-protection one.)
|
||||
///
|
||||
/// Idempotent: an existing rule for the branch (200/409/422) is success.
|
||||
async fn apply_config_repo_branch_protection(repo: &str, token: &str) -> Result<()> {
|
||||
let url = format!("{FORGE_HTTP}/api/v1/repos/{CONFIG_ORG}/{repo}/branch_protections");
|
||||
let body = format!(
|
||||
r#"{{"branch_name":"main","enable_push_whitelist":true,"push_whitelist_usernames":["core"],"enable_merge_whitelist":true,"merge_whitelist_usernames":["core"],"enable_approvals_whitelist":true,"approvals_whitelist_teams":["{OPERATORS_TEAM}"],"required_approvals":1,"block_on_official_review_requests":true,"allow_manual_merge":true,"enable_force_push":false}}"#
|
||||
);
|
||||
let (status, resp_body) = forge_http(reqwest::Method::POST, &url, token, &body).await?;
|
||||
if status.as_u16() == 201 {
|
||||
let client = api(token)?;
|
||||
let mut rule = main_branch_protection_option();
|
||||
rule.enable_push_whitelist = Some(true);
|
||||
rule.push_whitelist_usernames = Some(vec!["core".to_owned()]);
|
||||
rule.enable_merge_whitelist = Some(true);
|
||||
rule.merge_whitelist_usernames = Some(vec!["core".to_owned()]);
|
||||
rule.enable_approvals_whitelist = Some(true);
|
||||
rule.approvals_whitelist_teams = Some(vec![OPERATORS_TEAM.to_owned()]);
|
||||
rule.required_approvals = Some(1);
|
||||
rule.block_on_official_review_requests = Some(true);
|
||||
let Err(create_err) = client
|
||||
.repo_create_branch_protection(CONFIG_ORG, repo, rule)
|
||||
.await
|
||||
else {
|
||||
tracing::info!(%repo, "forge: applied config-repo branch protection");
|
||||
return Ok(());
|
||||
}
|
||||
// Non-201 is ambiguous: it can mean "rule already exists" (idempotent
|
||||
// success) OR a silent rejection — e.g. a 422 where Forgejo refused
|
||||
// the request and created NO rule. The old code treated 200/409/422
|
||||
// all as success, so a rejected POST left the repo unprotected with
|
||||
// no error (the reported case: a new agent's config repo had no
|
||||
// `main` rule and nothing was logged). Don't trust the status code:
|
||||
// verify the `main` rule actually exists, and on failure surface the
|
||||
// POST's response body so the real reason is in the journal.
|
||||
let main_url = format!("{url}/main");
|
||||
let (check, _) = forge_http(reqwest::Method::GET, &main_url, token, "").await?;
|
||||
if check.as_u16() == 200 {
|
||||
tracing::debug!(%repo, %status, "forge: config-repo branch protection already present");
|
||||
Ok(())
|
||||
} else {
|
||||
anyhow::bail!(
|
||||
"branch protection for {CONFIG_ORG}/{repo} not applied: POST -> HTTP {status} \
|
||||
(body: {body}); GET main -> HTTP {check}, no `main` rule present",
|
||||
body = resp_body.trim(),
|
||||
)
|
||||
};
|
||||
// A create failure is ambiguous: it can mean "rule already exists"
|
||||
// (idempotent success) OR a silent rejection — e.g. a 422 where Forgejo
|
||||
// refused the request and created NO rule. The old code treated
|
||||
// 200/409/422 all as success, so a rejected POST left the repo
|
||||
// unprotected with no error (the reported case: a new agent's config
|
||||
// repo had no `main` rule and nothing was logged). Don't trust the
|
||||
// status: verify the `main` rule actually exists, and on failure
|
||||
// surface the create error (its Display carries Forgejo's validation
|
||||
// message) so the real reason is in the journal.
|
||||
match client
|
||||
.repo_get_branch_protection(CONFIG_ORG, repo, "main")
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
tracing::debug!(
|
||||
%repo, create_error = %create_err,
|
||||
"forge: config-repo branch protection already present"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
Err(check_err) => anyhow::bail!(
|
||||
"branch protection for {CONFIG_ORG}/{repo} not applied: create failed \
|
||||
({create_err}); GET main rule failed ({check_err}), no `main` rule present"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -614,7 +772,14 @@ async fn apply_config_repo_branch_protection(repo: &str, token: &str) -> Result<
|
|||
/// create repos directly (`max_repo_creation = 0`). Idempotent.
|
||||
pub async fn create_agent_repo(agent: &str, repo: &str, core_token: &str) -> Result<String> {
|
||||
ensure_org_repo(AGENTS_ORG, repo, core_token).await?;
|
||||
add_collaborator(AGENTS_ORG, repo, agent, "write", core_token).await?;
|
||||
add_collaborator(
|
||||
AGENTS_ORG,
|
||||
repo,
|
||||
agent,
|
||||
AddCollaboratorOptionPermission::Write,
|
||||
core_token,
|
||||
)
|
||||
.await?;
|
||||
apply_operator_branch_protection(repo, core_token).await?;
|
||||
tracing::info!(%agent, %repo, "forge: created agent repo in {AGENTS_ORG} with operator merge gate");
|
||||
Ok(format!("{AGENTS_ORG}/{repo}"))
|
||||
|
|
|
|||
|
|
@ -1,15 +1,18 @@
|
|||
//! Per-agent Forgejo user + access-token provisioning, account
|
||||
//! policy (email alignment, repo-creation lockdown), avatar uploads,
|
||||
//! and the bootstrap `core` admin user + token lifecycle. Shared
|
||||
//! HTTP / `forgejo admin` helpers live in the module root (`super`).
|
||||
//! and the bootstrap `core` admin user + token lifecycle. The typed
|
||||
//! API-client constructor + `forgejo admin` helpers live in the
|
||||
//! module root (`super`).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use base64::Engine;
|
||||
use forgejo_api::structs::{EditUserOption, UpdateUserAvatarOption};
|
||||
use forgejo_api::{ApiErrorKind, ForgejoError};
|
||||
use reqwest::StatusCode;
|
||||
|
||||
use super::{CONFIG_ORG, FORGE_HTTP, forge_admin, forge_http, is_present};
|
||||
use super::{CONFIG_ORG, api, forge_admin, is_present};
|
||||
|
||||
const TOKEN_NAME_PREFIX: &str = "hyperhive";
|
||||
/// Where the host-side `core` admin token lives. Used by hive-c0re
|
||||
|
|
@ -55,6 +58,49 @@ fn agent_email(name: &str) -> String {
|
|||
format!("{name}@hyperhive.local")
|
||||
}
|
||||
|
||||
/// `EditUserOption` with every field unset except the ones Forgejo's
|
||||
/// validator effectively requires: `login_name` and `source_id = 0`
|
||||
/// (local auth, the default for users hive-c0re creates). Omitting
|
||||
/// `login_name` made Forgejo reset `use_custom_avatar` on every admin
|
||||
/// edit — the same reason the old raw JSON bodies always carried both
|
||||
/// fields. Callers set only the field(s) they mean to change on top.
|
||||
fn sparse_edit_user_option(name: &str) -> EditUserOption {
|
||||
EditUserOption {
|
||||
active: None,
|
||||
admin: None,
|
||||
allow_create_organization: None,
|
||||
allow_git_hook: None,
|
||||
allow_import_local: None,
|
||||
description: None,
|
||||
email: None,
|
||||
full_name: None,
|
||||
hide_email: None,
|
||||
location: None,
|
||||
login_name: Some(name.to_owned()),
|
||||
max_repo_creation: None,
|
||||
must_change_password: None,
|
||||
password: None,
|
||||
prohibit_login: None,
|
||||
pronouns: None,
|
||||
restricted: None,
|
||||
source_id: Some(0),
|
||||
visibility: None,
|
||||
website: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a Forgejo API error is a definitive 403. The typed client
|
||||
/// maps a 403 response to `ApiErrorKind::Forbidden` when the endpoint
|
||||
/// spec lists it, or to `UnexpectedStatusCode(403)` otherwise — check
|
||||
/// both defensively.
|
||||
fn is_forbidden(e: &ForgejoError) -> bool {
|
||||
match e {
|
||||
ForgejoError::ApiError(api) => matches!(api.error_kind(), ApiErrorKind::Forbidden),
|
||||
ForgejoError::UnexpectedStatusCode(s) => *s == StatusCode::FORBIDDEN,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Ensure a forgejo user named `name` exists. Idempotent: forgejo
|
||||
/// returns a "user already exists" error which we treat as success.
|
||||
/// `admin` adds `--admin` (site admin) — used for the bootstrap
|
||||
|
|
@ -129,11 +175,11 @@ async fn change_user_password(name: &str, password: &str) -> Result<()> {
|
|||
/// Forgejo's admin-user-edit endpoint from resetting `use_custom_avatar`
|
||||
/// on every `sync_agent` tick. Delete the marker to force re-alignment.
|
||||
///
|
||||
/// Uses the admin REST API (`PATCH /api/v1/admin/users/{name}`) rather
|
||||
/// than `forgejo admin user edit` because the CLI dropped the `edit`
|
||||
/// subcommand somewhere between forgejo 8 and current. Body includes
|
||||
/// `login_name` (required by Forgejo's `EditUserOption` validator) and
|
||||
/// `source_id = 0` (local auth, the default for users hive-c0re creates).
|
||||
/// Uses the admin REST API (`admin_edit_user`, i.e. `PATCH
|
||||
/// /api/v1/admin/users/{name}`) rather than `forgejo admin user edit`
|
||||
/// because the CLI dropped the `edit` subcommand somewhere between
|
||||
/// forgejo 8 and current. The edit body carries `login_name` +
|
||||
/// `source_id = 0` via [`sparse_edit_user_option`].
|
||||
pub(super) async fn ensure_user_email(name: &str) {
|
||||
let marker = crate::paths::forge_email_aligned_marker(name);
|
||||
if marker.exists() {
|
||||
|
|
@ -144,31 +190,33 @@ pub(super) async fn ensure_user_email(name: &str) {
|
|||
return;
|
||||
};
|
||||
let email = agent_email(name);
|
||||
// `login_name` is required by Forgejo's EditUserOption validator.
|
||||
// Omitting it caused Forgejo to reset use_custom_avatar on each call.
|
||||
let body = format!(r#"{{"email":"{email}","login_name":"{name}","source_id":0}}"#);
|
||||
let url = format!("{FORGE_HTTP}/api/v1/admin/users/{name}");
|
||||
match forge_http(reqwest::Method::PATCH, &url, &token, &body).await {
|
||||
Ok((status, _)) if status.is_success() => {
|
||||
let mut edit = sparse_edit_user_option(name);
|
||||
edit.email = Some(email.clone());
|
||||
let client = match api(&token) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
tracing::warn!(%name, error = %e, "forge: PATCH user email: client build failed");
|
||||
return;
|
||||
}
|
||||
};
|
||||
match client.admin_edit_user(name, edit).await {
|
||||
Ok(_) => {
|
||||
if let Some(parent) = marker.parent() {
|
||||
std::fs::create_dir_all(parent).ok();
|
||||
}
|
||||
std::fs::write(&marker, "").ok();
|
||||
tracing::info!(%name, %email, "forge: user email aligned");
|
||||
}
|
||||
Ok((status, _)) if status == reqwest::StatusCode::FORBIDDEN => {
|
||||
Err(e) if is_forbidden(&e) => {
|
||||
// Core token missing admin scope — see
|
||||
// `docs/forge.md::Token scopes` migration note.
|
||||
tracing::warn!(
|
||||
%name, %email, %status,
|
||||
%name, %email, error = %e,
|
||||
"forge: PATCH user email forbidden — core token likely missing admin scope. \
|
||||
Delete {CORE_TOKEN_PATH} and restart hive-c0re to re-mint with the new scopes."
|
||||
);
|
||||
}
|
||||
Ok((status, _)) => {
|
||||
tracing::warn!(%name, %email, %status, "forge: PATCH user email returned non-success");
|
||||
}
|
||||
Err(e) => tracing::warn!(%name, error = %e, "forge: PATCH user email transport error"),
|
||||
Err(e) => tracing::warn!(%name, %email, error = %e, "forge: PATCH user email failed"),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -183,11 +231,12 @@ pub(super) async fn ensure_user_email(name: &str) {
|
|||
/// so creation is refused while push / PR / clone stay intact. **Existing
|
||||
/// repos are untouched** — this only blocks *new* direct creation.
|
||||
///
|
||||
/// Marker-guarded like [`ensure_user_email`]: the PATCH runs once per
|
||||
/// agent (delete the marker to re-apply). Body carries `login_name` +
|
||||
/// `source_id` for the same reason `ensure_user_email` does — omitting
|
||||
/// `login_name` makes Forgejo's `EditUserOption` validator reset
|
||||
/// `use_custom_avatar`. Best-effort: failures warn, don't propagate.
|
||||
/// Marker-guarded like [`ensure_user_email`]: the edit runs once per
|
||||
/// agent (delete the marker to re-apply). The edit body carries
|
||||
/// `login_name` + `source_id` for the same reason `ensure_user_email`
|
||||
/// does — omitting `login_name` makes Forgejo's `EditUserOption`
|
||||
/// validator reset `use_custom_avatar`. Best-effort: failures warn,
|
||||
/// don't propagate.
|
||||
pub(super) async fn ensure_repo_creation_disabled(name: &str) {
|
||||
let marker = crate::paths::forge_repo_creation_disabled_marker(name);
|
||||
if marker.exists() {
|
||||
|
|
@ -197,28 +246,32 @@ pub(super) async fn ensure_repo_creation_disabled(name: &str) {
|
|||
tracing::debug!(%name, "forge: skipping ensure_repo_creation_disabled — no core token yet");
|
||||
return;
|
||||
};
|
||||
let body = format!(r#"{{"login_name":"{name}","source_id":0,"max_repo_creation":0}}"#);
|
||||
let url = format!("{FORGE_HTTP}/api/v1/admin/users/{name}");
|
||||
match forge_http(reqwest::Method::PATCH, &url, &token, &body).await {
|
||||
Ok((status, _)) if status.is_success() => {
|
||||
let mut edit = sparse_edit_user_option(name);
|
||||
edit.max_repo_creation = Some(0);
|
||||
let client = match api(&token) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
tracing::warn!(%name, error = %e, "forge: PATCH max_repo_creation: client build failed");
|
||||
return;
|
||||
}
|
||||
};
|
||||
match client.admin_edit_user(name, edit).await {
|
||||
Ok(_) => {
|
||||
if let Some(parent) = marker.parent() {
|
||||
std::fs::create_dir_all(parent).ok();
|
||||
}
|
||||
std::fs::write(&marker, "").ok();
|
||||
tracing::info!(%name, "forge: disabled direct repo creation (max_repo_creation=0)");
|
||||
}
|
||||
Ok((status, _)) if status == reqwest::StatusCode::FORBIDDEN => {
|
||||
Err(e) if is_forbidden(&e) => {
|
||||
tracing::warn!(
|
||||
%name, %status,
|
||||
%name, error = %e,
|
||||
"forge: PATCH max_repo_creation forbidden — core token likely missing admin scope. \
|
||||
Delete {CORE_TOKEN_PATH} and restart hive-c0re to re-mint with the new scopes."
|
||||
);
|
||||
}
|
||||
Ok((status, _)) => {
|
||||
tracing::warn!(%name, %status, "forge: PATCH max_repo_creation returned non-success");
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(%name, error = %e, "forge: PATCH max_repo_creation transport error");
|
||||
tracing::warn!(%name, error = %e, "forge: PATCH max_repo_creation failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -337,15 +390,17 @@ pub(super) async fn ensure_core_avatar(token: &str) -> Result<()> {
|
|||
let png_bytes = tokio::fs::read(&png_path)
|
||||
.await
|
||||
.with_context(|| format!("read core avatar PNG from {}", png_path.display()))?;
|
||||
let body = format!(
|
||||
r#"{{"image":"{}"}}"#,
|
||||
base64::engine::general_purpose::STANDARD.encode(&png_bytes),
|
||||
);
|
||||
let url = format!("{FORGE_HTTP}/api/v1/admin/users/core/avatar");
|
||||
let (status, _) = forge_http(reqwest::Method::POST, &url, token, &body).await?;
|
||||
if !status.is_success() {
|
||||
anyhow::bail!("set core avatar: HTTP {status}");
|
||||
}
|
||||
// The raw-HTTP predecessor POSTed the admin endpoint
|
||||
// `/admin/users/core/avatar`, which forgejo-api has no method for.
|
||||
// `token` IS the core user's own token though, so updating "the
|
||||
// current user's avatar" (`POST /user/avatar`) is behaviorally
|
||||
// identical.
|
||||
api(token)?
|
||||
.user_update_avatar(UpdateUserAvatarOption {
|
||||
image: Some(base64::engine::general_purpose::STANDARD.encode(&png_bytes)),
|
||||
})
|
||||
.await
|
||||
.context("set core avatar")?;
|
||||
if let Some(parent) = marker.parent() {
|
||||
std::fs::create_dir_all(parent).ok();
|
||||
}
|
||||
|
|
@ -356,9 +411,8 @@ pub(super) async fn ensure_core_avatar(token: &str) -> Result<()> {
|
|||
|
||||
/// Set the `agent-configs` org's Forgejo avatar to the
|
||||
/// configs-stack glyph once. Sibling to `ensure_core_avatar`:
|
||||
/// one-shot, marker-guarded, best-effort. Forgejo's per-org avatar
|
||||
/// endpoint is `POST /api/v1/orgs/{org}/avatar` with a base64-PNG
|
||||
/// JSON body — same shape as the admin user endpoint above.
|
||||
/// one-shot, marker-guarded, best-effort. Uses `org_update_avatar`
|
||||
/// (`POST /api/v1/orgs/{org}/avatar`, base64-PNG payload).
|
||||
pub(super) async fn ensure_config_org_avatar(token: &str) -> Result<()> {
|
||||
let marker = crate::paths::forge_config_org_avatar_marker();
|
||||
if marker.exists() {
|
||||
|
|
@ -368,15 +422,15 @@ pub(super) async fn ensure_config_org_avatar(token: &str) -> Result<()> {
|
|||
let png_bytes = tokio::fs::read(&png_path)
|
||||
.await
|
||||
.with_context(|| format!("read {CONFIG_ORG} avatar PNG from {}", png_path.display()))?;
|
||||
let body = format!(
|
||||
r#"{{"image":"{}"}}"#,
|
||||
base64::engine::general_purpose::STANDARD.encode(&png_bytes),
|
||||
);
|
||||
let url = format!("{FORGE_HTTP}/api/v1/orgs/{CONFIG_ORG}/avatar");
|
||||
let (status, _) = forge_http(reqwest::Method::POST, &url, token, &body).await?;
|
||||
if !status.is_success() {
|
||||
anyhow::bail!("set {CONFIG_ORG} avatar: HTTP {status}");
|
||||
}
|
||||
api(token)?
|
||||
.org_update_avatar(
|
||||
CONFIG_ORG,
|
||||
UpdateUserAvatarOption {
|
||||
image: Some(base64::engine::general_purpose::STANDARD.encode(&png_bytes)),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.with_context(|| format!("set {CONFIG_ORG} avatar"))?;
|
||||
if let Some(parent) = marker.parent() {
|
||||
std::fs::create_dir_all(parent).ok();
|
||||
}
|
||||
|
|
@ -407,32 +461,47 @@ enum CoreTokenCheck {
|
|||
Indeterminate,
|
||||
}
|
||||
|
||||
/// Map the HTTP status of the token-probe call to a [`CoreTokenCheck`].
|
||||
/// Pure so the decision logic is unit-testable without a live forge.
|
||||
fn classify_core_token_status(status: StatusCode) -> CoreTokenCheck {
|
||||
if status.is_success() {
|
||||
CoreTokenCheck::Valid
|
||||
} else if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {
|
||||
CoreTokenCheck::Invalid
|
||||
} else {
|
||||
CoreTokenCheck::Indeterminate
|
||||
/// Map a failed token-probe call to a [`CoreTokenCheck`]. Only a
|
||||
/// definitive auth rejection (401/403 — surfaced by the typed client
|
||||
/// as `Unauthorized`/`Forbidden` API errors, or defensively as bare
|
||||
/// `UnexpectedStatusCode`s) is `Invalid`; anything else (transport,
|
||||
/// 5xx, unexpected shapes) is `Indeterminate`. Pure so the decision
|
||||
/// logic is unit-testable without a live forge.
|
||||
fn classify_core_token_error(e: &ForgejoError) -> CoreTokenCheck {
|
||||
match e {
|
||||
ForgejoError::ApiError(api) => match api.error_kind() {
|
||||
ApiErrorKind::Unauthorized | ApiErrorKind::Forbidden => CoreTokenCheck::Invalid,
|
||||
_ => CoreTokenCheck::Indeterminate,
|
||||
},
|
||||
ForgejoError::UnexpectedStatusCode(s)
|
||||
if *s == StatusCode::UNAUTHORIZED || *s == StatusCode::FORBIDDEN =>
|
||||
{
|
||||
CoreTokenCheck::Invalid
|
||||
}
|
||||
_ => CoreTokenCheck::Indeterminate,
|
||||
}
|
||||
}
|
||||
|
||||
/// Probe whether `token` is still accepted by the current forge with a
|
||||
/// cheap authenticated `GET /api/v1/user` (covered by the core token's
|
||||
/// `read:user` scope). See [`CoreTokenCheck`] for how the outcome is
|
||||
/// interpreted.
|
||||
/// cheap authenticated `user_get_current` (`GET /api/v1/user`, covered
|
||||
/// by the core token's `read:user` scope). See [`CoreTokenCheck`] for
|
||||
/// how the outcome is interpreted.
|
||||
async fn check_core_token(token: &str) -> CoreTokenCheck {
|
||||
let url = format!("{FORGE_HTTP}/api/v1/user");
|
||||
match forge_http(reqwest::Method::GET, &url, token, "").await {
|
||||
Ok((status, _)) => classify_core_token_status(status),
|
||||
let Ok(client) = api(token) else {
|
||||
return CoreTokenCheck::Indeterminate;
|
||||
};
|
||||
match client.user_get_current().await {
|
||||
Ok(_) => CoreTokenCheck::Valid,
|
||||
Err(e) => {
|
||||
tracing::debug!(
|
||||
error = %e,
|
||||
"forge: core-token probe could not reach forge; treating as indeterminate"
|
||||
);
|
||||
CoreTokenCheck::Indeterminate
|
||||
let outcome = classify_core_token_error(&e);
|
||||
if outcome == CoreTokenCheck::Indeterminate {
|
||||
tracing::debug!(
|
||||
error = %e,
|
||||
"forge: core-token probe inconclusive (unreachable / unexpected response); \
|
||||
treating as indeterminate"
|
||||
);
|
||||
}
|
||||
outcome
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -484,37 +553,42 @@ pub fn core_token() -> Option<String> {
|
|||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{CoreTokenCheck, classify_core_token_status};
|
||||
use super::{CoreTokenCheck, classify_core_token_error};
|
||||
use forgejo_api::{ApiError, ApiErrorKind, ForgejoError};
|
||||
use reqwest::StatusCode;
|
||||
|
||||
#[test]
|
||||
fn success_statuses_are_valid() {
|
||||
assert_eq!(
|
||||
classify_core_token_status(StatusCode::OK),
|
||||
CoreTokenCheck::Valid
|
||||
);
|
||||
assert_eq!(
|
||||
classify_core_token_status(StatusCode::NO_CONTENT),
|
||||
CoreTokenCheck::Valid
|
||||
);
|
||||
fn api_err(kind: ApiErrorKind) -> ForgejoError {
|
||||
ForgejoError::ApiError(ApiError {
|
||||
message: None,
|
||||
kind,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auth_rejection_statuses_are_invalid() {
|
||||
fn auth_rejection_errors_are_invalid() {
|
||||
// The whole point: a stale token (forge rebuilt out from under it)
|
||||
// 401s, and 401/403 are the only outcomes that trigger a re-mint.
|
||||
assert_eq!(
|
||||
classify_core_token_status(StatusCode::UNAUTHORIZED),
|
||||
classify_core_token_error(&api_err(ApiErrorKind::Unauthorized)),
|
||||
CoreTokenCheck::Invalid
|
||||
);
|
||||
assert_eq!(
|
||||
classify_core_token_status(StatusCode::FORBIDDEN),
|
||||
classify_core_token_error(&api_err(ApiErrorKind::Forbidden)),
|
||||
CoreTokenCheck::Invalid
|
||||
);
|
||||
// Defensive: the same statuses arriving as bare status codes
|
||||
// (endpoint spec didn't list them) must classify identically.
|
||||
for s in [StatusCode::UNAUTHORIZED, StatusCode::FORBIDDEN] {
|
||||
assert_eq!(
|
||||
classify_core_token_error(&ForgejoError::UnexpectedStatusCode(s)),
|
||||
CoreTokenCheck::Invalid,
|
||||
"status {s} should be invalid"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transient_and_unexpected_statuses_are_indeterminate() {
|
||||
fn transient_and_unexpected_errors_are_indeterminate() {
|
||||
// Never re-mint on a transient — minting needs the forge too, and
|
||||
// churning tokens on a blip is worse than keeping the existing one.
|
||||
for s in [
|
||||
|
|
@ -525,10 +599,18 @@ mod tests {
|
|||
StatusCode::NOT_FOUND,
|
||||
] {
|
||||
assert_eq!(
|
||||
classify_core_token_status(s),
|
||||
classify_core_token_error(&ForgejoError::UnexpectedStatusCode(s)),
|
||||
CoreTokenCheck::Indeterminate,
|
||||
"status {s} should be indeterminate"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
classify_core_token_error(&api_err(ApiErrorKind::NotFound { errors: None })),
|
||||
CoreTokenCheck::Indeterminate
|
||||
);
|
||||
assert_eq!(
|
||||
classify_core_token_error(&api_err(ApiErrorKind::Generic)),
|
||||
CoreTokenCheck::Indeterminate
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,10 @@
|
|||
//! webhook is auto-created by [`ensure_webhook`] at startup. A
|
||||
//! periodic pull in `main.rs` provides a fallback cadence.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use forgejo_api::structs::{CreateHookOption, CreateHookOptionConfig, CreateHookOptionType};
|
||||
|
||||
pub const ORG: &str = "internal";
|
||||
pub const REPO: &str = "knowledge";
|
||||
|
|
@ -145,66 +148,61 @@ async fn seed_readme(core_token: &str) -> Result<()> {
|
|||
/// Called at startup alongside [`ensure_local_clone`]. No-op when the
|
||||
/// core token is absent (forge not yet provisioned).
|
||||
pub async fn ensure_webhook(core_token: &str, dashboard_port: u16) -> Result<()> {
|
||||
// The typed client carries no per-request timeout, so each call is
|
||||
// wrapped in one: this runs as a detached startup task, and a forge
|
||||
// that accepts connections but never answers would otherwise hang
|
||||
// it forever (and the hourly pull fallback masks the missing hook).
|
||||
const HTTP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
|
||||
let target_url = format!("http://127.0.0.1:{dashboard_port}/webhook/knowledge");
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(10))
|
||||
.build()
|
||||
.context("build reqwest client for webhook setup")?;
|
||||
let client = crate::forge::api(core_token)?;
|
||||
|
||||
// List existing hooks — skip creation if ours is already there.
|
||||
let list_url = format!(
|
||||
"{}/api/v1/repos/{ORG}/{REPO}/hooks",
|
||||
crate::forge::FORGE_HTTP
|
||||
);
|
||||
let resp = client
|
||||
.get(&list_url)
|
||||
.header("Authorization", format!("token {core_token}"))
|
||||
.send()
|
||||
// Best-effort like the raw-HTTP predecessor: a listing failure
|
||||
// falls through to the create attempt.
|
||||
let listed = tokio::time::timeout(HTTP_TIMEOUT, client.repo_list_hooks(ORG, REPO).all())
|
||||
.await
|
||||
.with_context(|| format!("GET {list_url}"))?;
|
||||
if resp.status().is_success() {
|
||||
let hooks: Vec<serde_json::Value> = resp.json().await.unwrap_or_default();
|
||||
let already_exists = hooks.iter().any(|h| {
|
||||
h.get("config")
|
||||
.and_then(|c| c.get("url"))
|
||||
.and_then(|u| u.as_str())
|
||||
== Some(&target_url)
|
||||
});
|
||||
if already_exists {
|
||||
tracing::debug!(%target_url, "knowledge: push webhook already configured");
|
||||
return Ok(());
|
||||
.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, "knowledge: push webhook already configured");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::debug!(error = %e, "knowledge: listing hooks failed; attempting create");
|
||||
}
|
||||
}
|
||||
|
||||
// Create the webhook.
|
||||
let create_url = format!(
|
||||
"{}/api/v1/repos/{ORG}/{REPO}/hooks",
|
||||
crate::forge::FORGE_HTTP
|
||||
);
|
||||
let body = serde_json::json!({
|
||||
"type": "forgejo",
|
||||
"config": {
|
||||
"url": target_url,
|
||||
"content_type": "json"
|
||||
let hook = CreateHookOption {
|
||||
active: Some(true),
|
||||
authorization_header: None,
|
||||
branch_filter: None,
|
||||
config: CreateHookOptionConfig {
|
||||
content_type: "json".to_owned(),
|
||||
url: url::Url::parse(&target_url).context("parse webhook target url")?,
|
||||
additional: BTreeMap::new(),
|
||||
},
|
||||
"events": ["push"],
|
||||
"active": true
|
||||
});
|
||||
let resp = client
|
||||
.post(&create_url)
|
||||
.header("Authorization", format!("token {core_token}"))
|
||||
.json(&body)
|
||||
.send()
|
||||
events: Some(vec!["push".to_owned()]),
|
||||
r#type: CreateHookOptionType::Forgejo,
|
||||
};
|
||||
tokio::time::timeout(HTTP_TIMEOUT, client.repo_create_hook(ORG, REPO, hook))
|
||||
.await
|
||||
.with_context(|| format!("POST {create_url}"))?;
|
||||
let status = resp.status();
|
||||
if status.is_success() {
|
||||
tracing::info!(%target_url, "knowledge: push webhook created");
|
||||
Ok(())
|
||||
} else {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
anyhow::bail!("create webhook for {ORG}/{REPO} failed ({status}): {body}")
|
||||
}
|
||||
.map_err(anyhow::Error::from)
|
||||
.and_then(|r| r.map_err(anyhow::Error::from))
|
||||
.with_context(|| format!("create webhook for {ORG}/{REPO}"))?;
|
||||
tracing::info!(%target_url, "knowledge: push webhook created");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pull the latest changes in the local clone. Called from the webhook
|
||||
|
|
|
|||
|
|
@ -10,6 +10,14 @@ path = "src/main.rs"
|
|||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
clap = { workspace = true }
|
||||
# `sync` = blocking client (hive-forge is a blocking CLI). TLS backend
|
||||
# comes from workspace feature unification on reqwest: the
|
||||
# `rustls-tls-native-roots` feature below applies to forgejo-api's
|
||||
# internal client too (same compiled reqwest), so the hive-CA trust
|
||||
# note keeps holding.
|
||||
forgejo-api = { workspace = true, features = ["sync"] }
|
||||
url.workspace = true
|
||||
time.workspace = true
|
||||
reqwest = { workspace = true, features = [
|
||||
"json",
|
||||
# Trust the OS/system CA store (rustls-native-certs), not only the
|
||||
|
|
|
|||
|
|
@ -1,11 +1,14 @@
|
|||
//! Blocking HTTP client for the Forgejo REST API. Identity is the
|
||||
//! per-agent token under `${HYPERHIVE_STATE_DIR}/forge-token`. All
|
||||
//! verbs go through this client so error surfaces, header set, and
|
||||
//! 4xx/5xx body unwrapping stay consistent.
|
||||
//! App-level Forgejo client wrapper. Identity is the per-agent token
|
||||
//! under `${HYPERHIVE_STATE_DIR}/forge-token`. REST calls go through
|
||||
//! the typed [`forgejo_api::sync::Forgejo`] client (exposed via
|
||||
//! [`Client::api`]); a minimal raw `reqwest` client remains for the
|
||||
//! few *web-router* routes Forgejo does not serve under `/api/v1/`
|
||||
//! (attachment downloads, Actions artifact/log routes).
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use forgejo_api::{Auth, ForgejoError};
|
||||
use reqwest::blocking::{Client as HttpClient, Response};
|
||||
use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE, HeaderMap, HeaderValue};
|
||||
use serde::Serialize;
|
||||
|
|
@ -18,14 +21,23 @@ const DEFAULT_URL: &str = "http://localhost:3000";
|
|||
/// take a repo override.
|
||||
const DEFAULT_REPO: &str = "hyperhive/hyperhive";
|
||||
|
||||
/// Blocking Forgejo API client. Cheap to clone (wraps an
|
||||
/// `Arc<reqwest::Client>` internally).
|
||||
/// Forgejo client pair: the typed `/api/v1` client plus a raw
|
||||
/// `reqwest` client for web-router-only routes.
|
||||
pub struct Client {
|
||||
http: HttpClient,
|
||||
/// Typed Forgejo REST client — every `/api/v1` call goes through
|
||||
/// this (see [`Client::api`]).
|
||||
api: forgejo_api::sync::Forgejo,
|
||||
/// Raw HTTP client for the routes Forgejo serves only through its
|
||||
/// web router, NOT under `/api/v1/` (so `forgejo-api` has no
|
||||
/// method for them): attachment downloads at `/attachments/<uuid>`,
|
||||
/// Actions artifact zips, the run-view log streamer, and the
|
||||
/// persisted-log download. Carries the same `Authorization: token`
|
||||
/// header the typed client sends.
|
||||
web: HttpClient,
|
||||
base: String,
|
||||
/// Per-agent forge token. Kept alongside the pre-built auth header
|
||||
/// so verbs that shell out to `git` (e.g. `clone`) can assemble
|
||||
/// an authenticated push URL without re-reading the token file.
|
||||
/// Per-agent forge token. Kept so verbs that shell out to `git`
|
||||
/// (e.g. `clone`) can assemble an authenticated push URL without
|
||||
/// re-reading the token file.
|
||||
token: String,
|
||||
/// Default repo used when a verb doesn't carry an explicit
|
||||
/// `[repo]` override.
|
||||
|
|
@ -49,19 +61,24 @@ impl Client {
|
|||
.unwrap_or_else(|| DEFAULT_REPO.to_owned());
|
||||
let token = read_token().context("read forge-token")?;
|
||||
|
||||
let url = url::Url::parse(&base).with_context(|| format!("parse HIVE_FORGE_URL {base}"))?;
|
||||
let api = forgejo_api::sync::Forgejo::new(Auth::Token(&token), url)
|
||||
.context("build forgejo client")?;
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
let auth = format!("token {token}");
|
||||
let mut auth_val = HeaderValue::from_str(&auth).context("auth header")?;
|
||||
auth_val.set_sensitive(true);
|
||||
headers.insert(AUTHORIZATION, auth_val);
|
||||
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
|
||||
|
||||
let http = HttpClient::builder()
|
||||
let web = HttpClient::builder()
|
||||
.default_headers(headers)
|
||||
.build()
|
||||
.context("build reqwest client")?;
|
||||
|
||||
Ok(Self {
|
||||
http,
|
||||
api,
|
||||
web,
|
||||
base,
|
||||
token,
|
||||
default_repo,
|
||||
|
|
@ -69,6 +86,13 @@ impl Client {
|
|||
})
|
||||
}
|
||||
|
||||
/// The typed Forgejo REST client. All `/api/v1` traffic goes
|
||||
/// through this.
|
||||
#[must_use]
|
||||
pub fn api(&self) -> &forgejo_api::sync::Forgejo {
|
||||
&self.api
|
||||
}
|
||||
|
||||
/// Assemble an authenticated git URL for `repo` (e.g.
|
||||
/// `internal/knowledge`) by injecting the agent's forge user +
|
||||
/// token into the base URL's authority: `http://<user>:<token>@host/<repo>.git`.
|
||||
|
|
@ -95,11 +119,6 @@ impl Client {
|
|||
self.json_mode
|
||||
}
|
||||
|
||||
/// Resolve the API base path (`<base>/api/v1`).
|
||||
fn api(&self) -> String {
|
||||
format!("{}/api/v1", self.base)
|
||||
}
|
||||
|
||||
/// Return the active repo. `from_env` already folded the
|
||||
/// `-r/--repo` override into `default_repo`, so verbs just read
|
||||
/// it as-is — no per-verb override plumbing.
|
||||
|
|
@ -108,177 +127,10 @@ impl Client {
|
|||
&self.default_repo
|
||||
}
|
||||
|
||||
/// GET `<api>/<path>` and decode JSON.
|
||||
pub fn get_json(&self, path: &str) -> Result<Value> {
|
||||
let url = format!("{}{}", self.api(), path);
|
||||
let resp = self.http.get(&url).send().context("GET")?;
|
||||
decode_json(resp, &format!("GET {url}"))
|
||||
}
|
||||
|
||||
/// GET `<api>/<path>` and decode JSON. Returns `None` if the
|
||||
/// server responds with 404 (resource absent rather than an error).
|
||||
pub fn get_json_optional(&self, path: &str) -> Result<Option<Value>> {
|
||||
let url = format!("{}{}", self.api(), path);
|
||||
let resp = self.http.get(&url).send().context("GET")?;
|
||||
if resp.status() == reqwest::StatusCode::NOT_FOUND {
|
||||
return Ok(None);
|
||||
}
|
||||
decode_json(resp, &format!("GET {url}")).map(Some)
|
||||
}
|
||||
|
||||
/// GET a paginated list endpoint and concatenate all pages.
|
||||
/// `path` should NOT include `page=` (we own it); other query
|
||||
/// params (`?limit=N&state=open&...`) are preserved. Pages drain
|
||||
/// while the response carries a `Link: rel="next"` header, up to
|
||||
/// `max_pages` (the runaway-loop safety cap). Returns the merged
|
||||
/// array. Used by `lint` for repo-wide queries.
|
||||
pub fn get_json_all(&self, path: &str, max_pages: u32) -> Result<Vec<Value>> {
|
||||
let sep = if path.contains('?') { '&' } else { '?' };
|
||||
let mut merged = Vec::new();
|
||||
for page in 1..=max_pages {
|
||||
let url = format!("{}{}{sep}page={page}", self.api(), path);
|
||||
let resp = self.http.get(&url).send().context("GET")?;
|
||||
let has_next = resp
|
||||
.headers()
|
||||
.get(reqwest::header::LINK)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.is_some_and(|s| s.contains("rel=\"next\""));
|
||||
let v = decode_json(resp, &format!("GET {url}"))?;
|
||||
let arr = v.as_array().cloned().unwrap_or_default();
|
||||
let empty = arr.is_empty();
|
||||
merged.extend(arr);
|
||||
if empty || !has_next {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(merged)
|
||||
}
|
||||
|
||||
/// GET `<api>/<path>` and return the raw response body as text
|
||||
/// (used by `diff` which fetches a `text/plain` blob).
|
||||
pub fn get_text(&self, path: &str, accept: &str) -> Result<String> {
|
||||
let url = format!("{}{}", self.api(), path);
|
||||
let resp = self
|
||||
.http
|
||||
.get(&url)
|
||||
.header(ACCEPT, accept)
|
||||
.send()
|
||||
.context("GET")?;
|
||||
decode_text(resp, &format!("GET {url}"))
|
||||
}
|
||||
|
||||
/// POST a JSON body to `<api>/<path>` and decode the response.
|
||||
pub fn post_json<B: Serialize>(&self, path: &str, body: &B) -> Result<Value> {
|
||||
let url = format!("{}{}", self.api(), path);
|
||||
let resp = self
|
||||
.http
|
||||
.post(&url)
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.json(body)
|
||||
.send()
|
||||
.context("POST")?;
|
||||
decode_json(resp, &format!("POST {url}"))
|
||||
}
|
||||
|
||||
/// PATCH a JSON body to `<api>/<path>` and decode the response.
|
||||
pub fn patch_json<B: Serialize>(&self, path: &str, body: &B) -> Result<Value> {
|
||||
let url = format!("{}{}", self.api(), path);
|
||||
let resp = self
|
||||
.http
|
||||
.patch(&url)
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.json(body)
|
||||
.send()
|
||||
.context("PATCH")?;
|
||||
decode_json(resp, &format!("PATCH {url}"))
|
||||
}
|
||||
|
||||
/// PUT a JSON body to `<api>/<path>` and decode the response.
|
||||
pub fn put_json<B: Serialize>(&self, path: &str, body: &B) -> Result<Value> {
|
||||
let url = format!("{}{}", self.api(), path);
|
||||
let resp = self
|
||||
.http
|
||||
.put(&url)
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.json(body)
|
||||
.send()
|
||||
.context("PUT")?;
|
||||
decode_json(resp, &format!("PUT {url}"))
|
||||
}
|
||||
|
||||
/// PUT a JSON body to `<api>/<path>` for an endpoint that returns
|
||||
/// `204 No Content` (empty body), so there is nothing to decode.
|
||||
/// Used by `repo-add-collaborator` (Forgejo's add-collaborator PUT
|
||||
/// answers 204 on success).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the request fails to send (transport/network
|
||||
/// error) or the server responds with a non-2xx status (the response
|
||||
/// body is included in the error).
|
||||
pub fn put_no_content<B: Serialize>(&self, path: &str, body: &B) -> Result<()> {
|
||||
let url = format!("{}{}", self.api(), path);
|
||||
let resp = self
|
||||
.http
|
||||
.put(&url)
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.json(body)
|
||||
.send()
|
||||
.context("PUT")?;
|
||||
check_status(resp, &format!("PUT {url}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// PATCH `<api>/<path>` for an endpoint that returns a 2xx with an
|
||||
/// empty body (nothing to decode). Used to mark a notification thread
|
||||
/// read (`/notifications/threads/{id}` answers `205 Reset Content`).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the request fails to send (transport/network
|
||||
/// error) or the server responds with a non-2xx status (the response
|
||||
/// body is included in the error).
|
||||
pub fn patch_no_content(&self, path: &str) -> Result<()> {
|
||||
let url = format!("{}{}", self.api(), path);
|
||||
let resp = self.http.patch(&url).send().context("PATCH")?;
|
||||
check_status(resp, &format!("PATCH {url}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// POST a JSON body to `<api>/<path>` for an endpoint that returns a
|
||||
/// 2xx with an empty body (so there is nothing to decode). Used by
|
||||
/// `pr-merge` — Forgejo's merge endpoint answers `200 OK` with no body
|
||||
/// on success and a non-2xx (e.g. `405`) when the PR is not mergeable.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the request fails to send (transport/network
|
||||
/// error) or the server responds with a non-2xx status (the response
|
||||
/// body is included in the error).
|
||||
pub fn post_no_content<B: Serialize>(&self, path: &str, body: &B) -> Result<()> {
|
||||
let url = format!("{}{}", self.api(), path);
|
||||
let resp = self
|
||||
.http
|
||||
.post(&url)
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.json(body)
|
||||
.send()
|
||||
.context("POST")?;
|
||||
check_status(resp, &format!("POST {url}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// DELETE `<api>/<path>`. Optional JSON body for endpoints that
|
||||
/// need it (Forgejo's subscription unwatch uses bodyless DELETE).
|
||||
pub fn delete(&self, path: &str, body: Option<&Value>) -> Result<()> {
|
||||
let url = format!("{}{}", self.api(), path);
|
||||
let mut req = self.http.delete(&url);
|
||||
if let Some(b) = body {
|
||||
req = req.header(CONTENT_TYPE, "application/json").json(b);
|
||||
}
|
||||
let resp = req.send().context("DELETE")?;
|
||||
check_status(resp, &format!("DELETE {url}"))?;
|
||||
Ok(())
|
||||
/// The active repo split into `(owner, name)` for the typed
|
||||
/// client's per-segment path arguments.
|
||||
pub fn owner_repo(&self) -> Result<(&str, &str)> {
|
||||
split_repo(self.repo())
|
||||
}
|
||||
|
||||
/// Build the full URL for a Forgejo attachment by UUID.
|
||||
|
|
@ -300,9 +152,9 @@ impl Client {
|
|||
}
|
||||
|
||||
/// POST a JSON body to a base-relative *web* path (NOT under
|
||||
/// `/api/v1/`) and decode the JSON response. Used for endpoints
|
||||
/// Forgejo only serves through its web router — e.g. the Actions
|
||||
/// run-view log streamer at
|
||||
/// `/api/v1/`, so no `forgejo-api` method exists) and decode the
|
||||
/// JSON response. Used for endpoints Forgejo only serves through
|
||||
/// its web router — e.g. the Actions run-view log streamer at
|
||||
/// `<base>/<owner>/<repo>/actions/runs/<run>/jobs/<job>`. The
|
||||
/// agent's `Authorization: token` header is sent as usual; the
|
||||
/// web router accepts a token-authed doer and, because the handler
|
||||
|
|
@ -312,44 +164,67 @@ impl Client {
|
|||
pub fn post_json_web<B: Serialize>(&self, path: &str, body: &B) -> Result<Value> {
|
||||
let url = self.web_url(path);
|
||||
let resp = self
|
||||
.http
|
||||
.web
|
||||
.post(&url)
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.json(body)
|
||||
.send()
|
||||
.context("POST")?;
|
||||
decode_json(resp, &format!("POST {url}"))
|
||||
let resp = check_status(resp, &format!("POST {url}"))?;
|
||||
resp.json::<Value>()
|
||||
.with_context(|| format!("decode JSON for POST {url}"))
|
||||
}
|
||||
|
||||
/// GET a raw (non-API) URL and return the response body as bytes.
|
||||
/// The client's auth headers are still sent — Forgejo requires them
|
||||
/// for private attachment downloads. Uses the full URL as-is; the
|
||||
/// caller is responsible for constructing it (see `attachment_url`).
|
||||
/// Stays on the raw `reqwest` client because these are *web-router*
|
||||
/// routes (`/attachments/<uuid>`, Actions artifact / persisted-log
|
||||
/// downloads) with no `/api/v1` equivalent. The client's auth
|
||||
/// headers are still sent — Forgejo requires them for private
|
||||
/// attachment downloads. Uses the full URL as-is; the caller is
|
||||
/// responsible for constructing it (see `attachment_url`).
|
||||
pub fn get_bytes_raw(&self, url: &str) -> Result<Vec<u8>> {
|
||||
let resp = self.http.get(url).send().context("GET")?;
|
||||
let resp = self.web.get(url).send().context("GET")?;
|
||||
let resp = check_status(resp, &format!("GET {url}"))?;
|
||||
resp.bytes()
|
||||
.map(|b| b.to_vec())
|
||||
.with_context(|| format!("read bytes for GET {url}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// POST a multipart file upload, returning the parsed response.
|
||||
/// Used by `attach-issue` / `attach-comment`.
|
||||
pub fn post_multipart_file(&self, path: &str, file: &std::path::Path) -> Result<Value> {
|
||||
let url = format!("{}{}", self.api(), path);
|
||||
let form = reqwest::blocking::multipart::Form::new()
|
||||
.file("attachment", file)
|
||||
.with_context(|| format!("read {}", file.display()))?;
|
||||
let resp = self
|
||||
.http
|
||||
.post(&url)
|
||||
.multipart(form)
|
||||
.send()
|
||||
.context("POST")?;
|
||||
decode_json(resp, &format!("POST {url}"))
|
||||
/// Split an `owner/name` repo string into its two path segments for
|
||||
/// the typed client. Errors on anything that isn't exactly
|
||||
/// `owner/name` with both halves non-empty.
|
||||
pub fn split_repo(repo: &str) -> Result<(&str, &str)> {
|
||||
match repo.split_once('/') {
|
||||
Some((owner, name)) if !owner.is_empty() && !name.is_empty() && !name.contains('/') => {
|
||||
Ok((owner, name))
|
||||
}
|
||||
_ => bail!("hive-forge: repo must be of the form owner/name, got {repo:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// True when a typed-client error is Forgejo saying 404 (resource
|
||||
/// absent rather than a transport / auth / server failure). Used by
|
||||
/// verbs that treat "not there" as a normal state (e.g.
|
||||
/// `subscription` reads a 404 as "not watching").
|
||||
#[must_use]
|
||||
pub fn is_not_found(err: &ForgejoError) -> bool {
|
||||
match err {
|
||||
ForgejoError::ApiError(e) => {
|
||||
matches!(e.error_kind(), forgejo_api::ApiErrorKind::NotFound { .. })
|
||||
}
|
||||
ForgejoError::UnexpectedStatusCode(code) => *code == reqwest::StatusCode::NOT_FOUND,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert a CLI-side `u64` issue/PR/comment number to the `i64` the
|
||||
/// typed client's path arguments use. Numbers past `i64::MAX` don't
|
||||
/// exist on any forge; error instead of wrapping.
|
||||
pub fn index(n: u64) -> Result<i64> {
|
||||
i64::try_from(n).with_context(|| format!("number {n} out of range"))
|
||||
}
|
||||
|
||||
/// Locate and read the forge token. Falls back to `$PWD/forge-token`
|
||||
/// when `HYPERHIVE_STATE_DIR` isn't set, matching the bash helper.
|
||||
fn read_token() -> Result<String> {
|
||||
|
|
@ -364,9 +239,10 @@ fn read_token() -> Result<String> {
|
|||
Ok(raw.trim().to_owned())
|
||||
}
|
||||
|
||||
/// Surface non-2xx HTTP responses as anyhow errors with the response
|
||||
/// body included (matches `curl --fail-with-body`) — turns
|
||||
/// silent failures into errors with a clear message.
|
||||
/// Surface non-2xx HTTP responses on the raw web routes as anyhow
|
||||
/// errors with the response body included (matches `curl
|
||||
/// --fail-with-body`) — turns silent failures into errors with a
|
||||
/// clear message.
|
||||
fn check_status(resp: Response, op: &str) -> Result<Response> {
|
||||
let status = resp.status();
|
||||
if status.is_success() {
|
||||
|
|
@ -376,13 +252,28 @@ fn check_status(resp: Response, op: &str) -> Result<Response> {
|
|||
bail!("hive-forge: {op} failed ({status}): {body}");
|
||||
}
|
||||
|
||||
fn decode_json(resp: Response, op: &str) -> Result<Value> {
|
||||
let resp = check_status(resp, op)?;
|
||||
resp.json::<Value>()
|
||||
.with_context(|| format!("decode JSON for {op}"))
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::split_repo;
|
||||
|
||||
fn decode_text(resp: Response, op: &str) -> Result<String> {
|
||||
let resp = check_status(resp, op)?;
|
||||
resp.text().with_context(|| format!("decode text for {op}"))
|
||||
#[test]
|
||||
fn split_repo_accepts_owner_name() {
|
||||
assert_eq!(
|
||||
split_repo("hyperhive/hyperhive").unwrap(),
|
||||
("hyperhive", "hyperhive")
|
||||
);
|
||||
assert_eq!(
|
||||
split_repo("internal/knowledge").unwrap(),
|
||||
("internal", "knowledge")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_repo_rejects_malformed() {
|
||||
assert!(split_repo("no-slash").is_err());
|
||||
assert!(split_repo("/name").is_err());
|
||||
assert!(split_repo("owner/").is_err());
|
||||
assert!(split_repo("a/b/c").is_err());
|
||||
assert!(split_repo("").is_err());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,12 +13,12 @@
|
|||
//! `forge cli: agents keep commenting without reading prev comments`.)
|
||||
|
||||
use anyhow::Result;
|
||||
use serde_json::Value;
|
||||
use forgejo_api::structs::{NotifyGetRepoListQuery, NotifyReadThreadQuery};
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index, split_repo};
|
||||
|
||||
/// Forgejo's per-page notification cap.
|
||||
const PAGE_SIZE: u64 = 50;
|
||||
const PAGE_SIZE: u32 = 50;
|
||||
/// How many pages of unread notifications to scan for the thread.
|
||||
/// Notifications come newest-first and a thread the caller is about to
|
||||
/// comment on was just active, so it sits near the top; this cap keeps
|
||||
|
|
@ -26,7 +26,7 @@ const PAGE_SIZE: u64 = 50;
|
|||
/// firehose), at the cost of not detecting a match buried past
|
||||
/// `MAX_PAGES * PAGE_SIZE` unread items (degrade-open — acceptable for
|
||||
/// a courtesy guard).
|
||||
const MAX_PAGES: u64 = 5;
|
||||
const MAX_PAGES: u32 = 5;
|
||||
|
||||
/// The notification thread id of an UNREAD notification on
|
||||
/// `<repo>#<number>`, or `None` when the thread has no unread
|
||||
|
|
@ -34,24 +34,30 @@ const MAX_PAGES: u64 = 5;
|
|||
/// number can't false-match another repo. Errors only on transport /
|
||||
/// non-2xx — callers degrade open on `Err`.
|
||||
pub fn unread_thread_id(client: &Client, repo: &str, number: u64) -> Result<Option<u64>> {
|
||||
let (owner, name) = split_repo(repo)?;
|
||||
for page in 1..=MAX_PAGES {
|
||||
let v = client.get_json(&format!(
|
||||
"/repos/{repo}/notifications?all=false&page={page}&limit={PAGE_SIZE}"
|
||||
))?;
|
||||
let arr = v.as_array().cloned().unwrap_or_default();
|
||||
let len = arr.len() as u64;
|
||||
for n in &arr {
|
||||
let query = NotifyGetRepoListQuery {
|
||||
all: Some(false),
|
||||
..Default::default()
|
||||
};
|
||||
let (_, threads) = client
|
||||
.api()
|
||||
.notify_get_repo_list(owner, name, query)
|
||||
.page(page)
|
||||
.page_size(PAGE_SIZE)
|
||||
.send()?;
|
||||
for n in &threads {
|
||||
let subject_url = n
|
||||
.get("subject")
|
||||
.and_then(|s| s.get("url"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("");
|
||||
.subject
|
||||
.as_ref()
|
||||
.and_then(|s| s.url.as_ref())
|
||||
.map_or("", url::Url::as_str);
|
||||
if subject_matches(subject_url, number) {
|
||||
return Ok(n.get("id").and_then(Value::as_u64));
|
||||
return Ok(n.id.and_then(|id| u64::try_from(id).ok()));
|
||||
}
|
||||
}
|
||||
// Last (short) page reached — stop.
|
||||
if len < PAGE_SIZE {
|
||||
if threads.len() < PAGE_SIZE as usize {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
|
@ -62,7 +68,11 @@ pub fn unread_thread_id(client: &Client, repo: &str, number: u64) -> Result<Opti
|
|||
/// result). Clears the unread signal so a subsequent comment isn't
|
||||
/// blocked after the agent has read the thread.
|
||||
pub fn mark_thread_read(client: &Client, thread_id: u64) -> Result<()> {
|
||||
client.patch_no_content(&format!("/notifications/threads/{thread_id}"))
|
||||
client
|
||||
.api()
|
||||
.notify_read_thread(index(thread_id)?, NotifyReadThreadQuery::default())
|
||||
.send()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reading a thread (`comments` / `view`) is the "I've seen it" signal:
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ use std::path::PathBuf;
|
|||
|
||||
use anyhow::{Result, bail};
|
||||
use clap::Args as ClapArgs;
|
||||
use serde_json::Value;
|
||||
use forgejo_api::structs::ListActionRunsQuery;
|
||||
|
||||
use crate::client::Client;
|
||||
|
||||
|
|
@ -45,28 +45,29 @@ pub struct Args {
|
|||
/// Pages over the REST runs list (newest-first) to find the run whose
|
||||
/// run-page `html_url` ends in `/runs/<run-number>`, returning its global
|
||||
/// run id — the identifier the web artifact-download route requires.
|
||||
fn resolve_run_id(client: &Client, repo: &str, run_number: u64) -> Result<u64> {
|
||||
fn resolve_run_id(client: &Client, repo: &str, run_number: u64) -> Result<i64> {
|
||||
const PER_PAGE: u32 = 50;
|
||||
const MAX_PAGES: u32 = 40;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
for page in 1..=MAX_PAGES {
|
||||
let path = format!("/repos/{repo}/actions/runs?limit={PER_PAGE}&page={page}");
|
||||
let body = client.get_json(&path)?;
|
||||
let runs = body
|
||||
.get("workflow_runs")
|
||||
.and_then(Value::as_array)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let body = client
|
||||
.api()
|
||||
.list_action_runs(owner, name, ListActionRunsQuery::default())
|
||||
.page(page)
|
||||
.page_size(PER_PAGE)
|
||||
.send()?;
|
||||
let runs = body.workflow_runs.unwrap_or_default();
|
||||
if runs.is_empty() {
|
||||
break;
|
||||
}
|
||||
for run in &runs {
|
||||
let tail = run
|
||||
.get("html_url")
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|u| u.rsplit('/').next())
|
||||
.html_url
|
||||
.as_ref()
|
||||
.and_then(|u| u.as_str().rsplit('/').next())
|
||||
.and_then(|s| s.parse::<u64>().ok());
|
||||
if tail == Some(run_number)
|
||||
&& let Some(id) = run.get("id").and_then(Value::as_u64)
|
||||
&& let Some(id) = run.id
|
||||
{
|
||||
return Ok(id);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,9 +5,10 @@
|
|||
|
||||
use anyhow::Result;
|
||||
use clap::Args as ClapArgs;
|
||||
use serde_json::{Value, json};
|
||||
use forgejo_api::structs::EditIssueOption;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
use crate::verbs::print_json;
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
|
|
@ -22,37 +23,45 @@ pub struct Args {
|
|||
}
|
||||
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let current = client.get_json(&format!("/repos/{repo}/issues/{}", args.number))?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let idx = index(args.number)?;
|
||||
let current = client.api().issue_get_issue(owner, name, idx).send()?;
|
||||
let mut assignees: Vec<String> = current
|
||||
.get("assignees")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|u| u.get("login").and_then(Value::as_str).map(str::to_owned))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
.assignees
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(|u| u.login)
|
||||
.collect();
|
||||
if args.remove {
|
||||
assignees.retain(|u| u != &args.user);
|
||||
} else if !assignees.contains(&args.user) {
|
||||
assignees.push(args.user.clone());
|
||||
}
|
||||
let resp = client.patch_json(
|
||||
&format!("/repos/{repo}/issues/{}", args.number),
|
||||
&json!({ "assignees": assignees }),
|
||||
)?;
|
||||
let payload = EditIssueOption {
|
||||
assignee: None,
|
||||
assignees: Some(assignees),
|
||||
body: None,
|
||||
due_date: None,
|
||||
milestone: None,
|
||||
r#ref: None,
|
||||
state: None,
|
||||
title: None,
|
||||
unset_due_date: None,
|
||||
updated_at: None,
|
||||
};
|
||||
let resp = client
|
||||
.api()
|
||||
.issue_edit_issue(owner, name, idx, payload)
|
||||
.send()?;
|
||||
let logins: Vec<&str> = resp
|
||||
.get("assignees")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|u| u.get("login").and_then(Value::as_str))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
.assignees
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(|u| u.login.as_deref())
|
||||
.collect();
|
||||
print_json(&json!({
|
||||
"number": resp.get("number"),
|
||||
"number": resp.number,
|
||||
"assignees": logins,
|
||||
}))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,13 +2,15 @@
|
|||
//! <file>` — upload a file as an attachment. Prints the browser
|
||||
//! download URL.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::Args as ClapArgs;
|
||||
use serde_json::Value;
|
||||
use forgejo_api::structs::{
|
||||
Attachment, IssueCreateIssueAttachmentQuery, IssueCreateIssueCommentAttachmentQuery,
|
||||
};
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
pub struct IssueArgs {
|
||||
|
|
@ -39,11 +41,16 @@ pub fn run_issue(client: &Client, args: IssueArgs) -> Result<()> {
|
|||
args.file.display()
|
||||
);
|
||||
}
|
||||
let repo = client.repo();
|
||||
let resp = client.post_multipart_file(
|
||||
&format!("/repos/{repo}/issues/{}/assets", args.number),
|
||||
&args.file,
|
||||
)?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let bytes = read_file(&args.file)?;
|
||||
let query = IssueCreateIssueAttachmentQuery {
|
||||
name: file_name(&args.file),
|
||||
updated_at: None,
|
||||
};
|
||||
let resp = client
|
||||
.api()
|
||||
.issue_create_issue_attachment(owner, name, index(args.number)?, &bytes, query)
|
||||
.send()?;
|
||||
print_url(&resp);
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -61,17 +68,33 @@ pub fn run_comment(client: &Client, args: CommentArgs) -> Result<()> {
|
|||
args.file.display()
|
||||
);
|
||||
}
|
||||
let repo = client.repo();
|
||||
let resp = client.post_multipart_file(
|
||||
&format!("/repos/{repo}/issues/comments/{}/assets", args.id),
|
||||
&args.file,
|
||||
)?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let bytes = read_file(&args.file)?;
|
||||
let query = IssueCreateIssueCommentAttachmentQuery {
|
||||
name: file_name(&args.file),
|
||||
updated_at: None,
|
||||
};
|
||||
let resp = client
|
||||
.api()
|
||||
.issue_create_issue_comment_attachment(owner, name, index(args.id)?, &bytes, query)
|
||||
.send()?;
|
||||
print_url(&resp);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_url(v: &Value) {
|
||||
if let Some(url) = v.get("browser_download_url").and_then(Value::as_str) {
|
||||
fn read_file(path: &Path) -> Result<Vec<u8>> {
|
||||
std::fs::read(path).with_context(|| format!("read {}", path.display()))
|
||||
}
|
||||
|
||||
/// The upload's attachment name — the file's basename, matching what
|
||||
/// the old multipart form (which sent the file with its real name)
|
||||
/// made the server record.
|
||||
fn file_name(path: &Path) -> Option<String> {
|
||||
path.file_name().map(|n| n.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
fn print_url(v: &Attachment) {
|
||||
if let Some(url) = &v.browser_download_url {
|
||||
println!("{url}");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@
|
|||
|
||||
use anyhow::Result;
|
||||
use clap::Args as ClapArgs;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::client::Client;
|
||||
|
||||
|
|
@ -13,17 +12,16 @@ pub struct Args {
|
|||
}
|
||||
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let v = client.get_json(&format!("/repos/{repo}/branches?limit=100"))?;
|
||||
let names: Vec<&str> = v
|
||||
.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|b| b.get("name").and_then(Value::as_str))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
for n in names {
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let (_, branches) = client
|
||||
.api()
|
||||
.repo_list_branches(owner, name)
|
||||
.page_size(100)
|
||||
.send()?;
|
||||
for branch in &branches {
|
||||
let Some(n) = branch.name.as_deref() else {
|
||||
continue;
|
||||
};
|
||||
if args.pattern.as_deref().is_none_or(|p| n.contains(p)) {
|
||||
println!("{n}");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,16 +22,16 @@
|
|||
//! - `--branch <name>` → dispatches `--workflow` on that branch directly.
|
||||
//! - `--run <n>` → looks the run up in the Actions runs list (by the
|
||||
//! `runs/<n>` tail of its `html_url`, same convention as `ci-log` /
|
||||
//! `artifact-get`) and dispatches the SAME workflow on the SAME branch the
|
||||
//! run used.
|
||||
//! `artifact-get`) and dispatches the SAME workflow on the SAME ref the
|
||||
//! run used (the run record's `prettyref` + `workflow_id`).
|
||||
//!
|
||||
//! Dispatch re-runs the whole workflow, so there is no single-job variant.
|
||||
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
use clap::Args as ClapArgs;
|
||||
use serde_json::{Value, json};
|
||||
use forgejo_api::structs::{ActionRun, DispatchWorkflowOption, ListActionRunsQuery};
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
pub struct Args {
|
||||
|
|
@ -60,12 +60,12 @@ pub struct Args {
|
|||
///
|
||||
/// Returns an error if none of `--pr` / `--run` / `--branch` is given, if a
|
||||
/// `--pr` / `--run` handle can't be resolved (unknown PR/run, or a run
|
||||
/// missing its branch), or if the dispatch POST fails (network, or a non-2xx
|
||||
/// missing its ref), or if the dispatch POST fails (network, or a non-2xx
|
||||
/// such as `404` for an unknown workflow file or branch).
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let (workflow, branch) = match (args.pr, args.run, args.branch.as_deref()) {
|
||||
(Some(pr), _, _) => (args.workflow.clone(), branch_for_pr(client, repo, pr)?),
|
||||
(Some(pr), _, _) => (args.workflow.clone(), branch_for_pr(client, pr)?),
|
||||
(_, Some(run), _) => resolve_run(client, repo, run, &args.workflow)?,
|
||||
(_, _, Some(branch)) => (args.workflow.clone(), branch.to_string()),
|
||||
(None, None, None) => {
|
||||
|
|
@ -73,9 +73,16 @@ pub fn run(client: &Client, args: Args) -> Result<()> {
|
|||
}
|
||||
};
|
||||
|
||||
let path = format!("/repos/{repo}/actions/workflows/{workflow}/dispatches");
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let body = DispatchWorkflowOption {
|
||||
inputs: None,
|
||||
r#ref: branch.clone(),
|
||||
return_run_info: None,
|
||||
};
|
||||
client
|
||||
.post_no_content(&path, &json!({ "ref": branch }))
|
||||
.api()
|
||||
.dispatch_workflow(owner, name, &workflow, body)
|
||||
.send()
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"dispatch workflow {workflow} on {branch} ({repo}) — the workflow \
|
||||
|
|
@ -89,19 +96,21 @@ pub fn run(client: &Client, args: Args) -> Result<()> {
|
|||
|
||||
/// Resolve a PR's head branch name (`head.ref`) — the branch a same-repo PR
|
||||
/// pushes to, which is the ref we dispatch the workflow on.
|
||||
fn branch_for_pr(client: &Client, repo: &str, pr: u64) -> Result<String> {
|
||||
let pull = client.get_json(&format!("/repos/{repo}/pulls/{pr}"))?;
|
||||
pull.get("head")
|
||||
.and_then(|h| h.get("ref"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
fn branch_for_pr(client: &Client, pr: u64) -> Result<String> {
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let pull = client
|
||||
.api()
|
||||
.repo_get_pull_request(owner, name, index(pr)?)
|
||||
.send()?;
|
||||
pull.head
|
||||
.and_then(|h| h.r#ref)
|
||||
.with_context(|| format!("ci-rerun: PR #{pr} has no head.ref"))
|
||||
}
|
||||
|
||||
/// Page the Actions runs list (newest-first) to find the run whose run-page
|
||||
/// `html_url` ends in `/runs/<run-number>`, returning the `(workflow, branch)`
|
||||
/// to dispatch a fresh run of it. `fallback_workflow` is used when the run
|
||||
/// carries no workflow `path`.
|
||||
/// carries no workflow file name.
|
||||
fn resolve_run(
|
||||
client: &Client,
|
||||
repo: &str,
|
||||
|
|
@ -110,21 +119,22 @@ fn resolve_run(
|
|||
) -> Result<(String, String)> {
|
||||
const PER_PAGE: u32 = 50;
|
||||
const MAX_PAGES: u32 = 40;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
for page in 1..=MAX_PAGES {
|
||||
let path = format!("/repos/{repo}/actions/runs?limit={PER_PAGE}&page={page}");
|
||||
let body = client.get_json(&path)?;
|
||||
let runs = body
|
||||
.get("workflow_runs")
|
||||
.and_then(Value::as_array)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let body = client
|
||||
.api()
|
||||
.list_action_runs(owner, name, ListActionRunsQuery::default())
|
||||
.page(page)
|
||||
.page_size(PER_PAGE)
|
||||
.send()?;
|
||||
let runs = body.workflow_runs.unwrap_or_default();
|
||||
if runs.is_empty() {
|
||||
break;
|
||||
}
|
||||
for run in &runs {
|
||||
if run_number_of(run) == Some(run_number) {
|
||||
return run_dispatch_target(run, fallback_workflow)
|
||||
.with_context(|| format!("ci-rerun: run #{run_number} has no head_branch"));
|
||||
.with_context(|| format!("ci-rerun: run #{run_number} has no ref"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -133,24 +143,24 @@ fn resolve_run(
|
|||
|
||||
/// The per-repo run NUMBER from a run object's `html_url` (`…/runs/<n>` tail),
|
||||
/// matching the `runs/<n>` the UI shows and `pr-status` surfaces.
|
||||
fn run_number_of(run: &Value) -> Option<u64> {
|
||||
run.get("html_url")
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|u| u.rsplit('/').next())
|
||||
fn run_number_of(run: &ActionRun) -> Option<u64> {
|
||||
run.html_url
|
||||
.as_ref()
|
||||
.and_then(|u| u.as_str().rsplit('/').next())
|
||||
.and_then(|s| s.parse::<u64>().ok())
|
||||
}
|
||||
|
||||
/// Pull the `(workflow-file, branch)` dispatch target out of a run object:
|
||||
/// `head_branch` is the branch, and the workflow file is the basename of the
|
||||
/// run's `path` (e.g. `.forgejo/workflows/ci.yml` → `ci.yml`), falling back to
|
||||
/// `fallback_workflow` when the run carries no usable `path`. `None` only when
|
||||
/// the run has no `head_branch`.
|
||||
fn run_dispatch_target(run: &Value, fallback_workflow: &str) -> Option<(String, String)> {
|
||||
let branch = run.get("head_branch").and_then(Value::as_str)?;
|
||||
/// Pull the `(workflow-file, ref)` dispatch target out of a run record:
|
||||
/// `prettyref` is the ref the run ran on (the branch name for push /
|
||||
/// dispatch runs — PR-event runs carry a `#<n>` pseudo-ref the dispatch
|
||||
/// endpoint will reject with a clear 404), and `workflow_id` is the
|
||||
/// workflow file name (e.g. `ci.yml`), falling back to
|
||||
/// `fallback_workflow` when absent. `None` only when the run has no ref.
|
||||
fn run_dispatch_target(run: &ActionRun, fallback_workflow: &str) -> Option<(String, String)> {
|
||||
let branch = run.prettyref.as_deref().filter(|s| !s.is_empty())?;
|
||||
let workflow = run
|
||||
.get("path")
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|p| p.rsplit('/').next())
|
||||
.workflow_id
|
||||
.as_deref()
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or(fallback_workflow);
|
||||
Some((workflow.to_string(), branch.to_string()))
|
||||
|
|
@ -158,28 +168,41 @@ fn run_dispatch_target(run: &Value, fallback_workflow: &str) -> Option<(String,
|
|||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{run_dispatch_target, run_number_of};
|
||||
use super::{ActionRun, run_dispatch_target, run_number_of};
|
||||
use serde_json::json;
|
||||
|
||||
/// Build a typed run record from an API-shaped JSON fixture. The
|
||||
/// struct's fields are all optional, but the timestamp / URL
|
||||
/// fields deserialize through `with`-modules that require the
|
||||
/// keys to be *present* (as `null`) — fill those in so partial
|
||||
/// fixtures stay terse.
|
||||
fn run_from(mut v: serde_json::Value) -> ActionRun {
|
||||
let obj = v.as_object_mut().unwrap();
|
||||
for key in ["created", "started", "stopped", "updated", "html_url"] {
|
||||
obj.entry(key).or_insert(serde_json::Value::Null);
|
||||
}
|
||||
serde_json::from_value(v).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_run_number_from_html_url() {
|
||||
let run = json!({ "html_url": "http://forge/h/h/actions/runs/750" });
|
||||
let run = run_from(json!({ "html_url": "http://forge/h/h/actions/runs/750" }));
|
||||
assert_eq!(run_number_of(&run), Some(750));
|
||||
let run = json!({ "html_url": "https://forge/o/r/actions/runs/42" });
|
||||
let run = run_from(json!({ "html_url": "https://forge/o/r/actions/runs/42" }));
|
||||
assert_eq!(run_number_of(&run), Some(42));
|
||||
assert_eq!(
|
||||
run_number_of(&json!({ "html_url": "http://forge/o/r/x" })),
|
||||
run_number_of(&run_from(json!({ "html_url": "http://forge/o/r/x" }))),
|
||||
None
|
||||
);
|
||||
assert_eq!(run_number_of(&json!({})), None);
|
||||
assert_eq!(run_number_of(&run_from(json!({}))), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_workflow_and_branch() {
|
||||
let run = json!({
|
||||
"head_branch": "atlas/foo",
|
||||
"path": ".forgejo/workflows/ci.yml",
|
||||
});
|
||||
let run = run_from(json!({
|
||||
"prettyref": "atlas/foo",
|
||||
"workflow_id": "ci.yml",
|
||||
}));
|
||||
assert_eq!(
|
||||
run_dispatch_target(&run, "fallback.yml"),
|
||||
Some(("ci.yml".to_string(), "atlas/foo".to_string()))
|
||||
|
|
@ -187,8 +210,8 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn falls_back_to_default_workflow_without_path() {
|
||||
let run = json!({ "head_branch": "b" });
|
||||
fn falls_back_to_default_workflow_without_file() {
|
||||
let run = run_from(json!({ "prettyref": "b" }));
|
||||
assert_eq!(
|
||||
run_dispatch_target(&run, "fallback.yml"),
|
||||
Some(("fallback.yml".to_string(), "b".to_string()))
|
||||
|
|
@ -196,7 +219,7 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn no_branch_means_no_target() {
|
||||
assert_eq!(run_dispatch_target(&json!({}), "ci.yml"), None);
|
||||
fn no_ref_means_no_target() {
|
||||
assert_eq!(run_dispatch_target(&run_from(json!({})), "ci.yml"), None);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ use anyhow::Result;
|
|||
use clap::Args as ClapArgs;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
use crate::verbs::print_json;
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
|
|
@ -14,13 +14,31 @@ pub struct Args {
|
|||
}
|
||||
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let resp = client.patch_json(
|
||||
&format!("/repos/{repo}/issues/{}", args.number),
|
||||
&json!({ "state": "closed" }),
|
||||
)?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let resp = client
|
||||
.api()
|
||||
.issue_edit_issue(owner, name, index(args.number)?, state_edit("closed"))
|
||||
.send()?;
|
||||
print_json(&json!({
|
||||
"number": resp.get("number"),
|
||||
"state": resp.get("state"),
|
||||
"number": resp.number,
|
||||
"state": resp.state,
|
||||
}))
|
||||
}
|
||||
|
||||
/// An `EditIssueOption` that only sets `state` — shared by `close` /
|
||||
/// `reopen` (the null fields ride along and Forgejo treats them as
|
||||
/// "leave unchanged").
|
||||
pub(crate) fn state_edit(state: &str) -> forgejo_api::structs::EditIssueOption {
|
||||
forgejo_api::structs::EditIssueOption {
|
||||
assignee: None,
|
||||
assignees: None,
|
||||
body: None,
|
||||
due_date: None,
|
||||
milestone: None,
|
||||
r#ref: None,
|
||||
state: Some(state.to_owned()),
|
||||
title: None,
|
||||
unset_due_date: None,
|
||||
updated_at: None,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,10 +11,11 @@
|
|||
|
||||
use anyhow::{Result, bail};
|
||||
use clap::Args as ClapArgs;
|
||||
use forgejo_api::structs::CreateIssueCommentOption;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::body;
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
use crate::notify;
|
||||
use crate::verbs::print_json;
|
||||
|
||||
|
|
@ -63,12 +64,21 @@ pub fn run(client: &Client, args: Args) -> Result<()> {
|
|||
}
|
||||
}
|
||||
|
||||
let resp = client.post_json(
|
||||
&format!("/repos/{repo}/issues/{}/comments", args.number),
|
||||
&json!({ "body": body }),
|
||||
)?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let resp = client
|
||||
.api()
|
||||
.issue_create_comment(
|
||||
owner,
|
||||
name,
|
||||
index(args.number)?,
|
||||
CreateIssueCommentOption {
|
||||
body,
|
||||
updated_at: None,
|
||||
},
|
||||
)
|
||||
.send()?;
|
||||
print_json(&json!({
|
||||
"id": resp.get("id"),
|
||||
"url": resp.get("html_url"),
|
||||
"id": resp.id,
|
||||
"url": resp.html_url,
|
||||
}))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,12 +1,13 @@
|
|||
//! `comment-edit <id> [body sources] [repo]` — edit an existing
|
||||
//! comment by id.
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::{Result, bail};
|
||||
use clap::Args as ClapArgs;
|
||||
use forgejo_api::structs::EditIssueCommentOption;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::body;
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
use crate::verbs::print_json;
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
|
|
@ -33,14 +34,26 @@ pub fn run(client: &Client, args: Args) -> Result<()> {
|
|||
args.body_file.as_deref(),
|
||||
"comment-edit",
|
||||
)?;
|
||||
let repo = client.repo();
|
||||
let resp = client.patch_json(
|
||||
&format!("/repos/{repo}/issues/comments/{}", args.id),
|
||||
&json!({ "body": body }),
|
||||
)?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let Some(resp) = client
|
||||
.api()
|
||||
.issue_edit_comment(
|
||||
owner,
|
||||
name,
|
||||
index(args.id)?,
|
||||
EditIssueCommentOption {
|
||||
body,
|
||||
updated_at: None,
|
||||
},
|
||||
)
|
||||
.send()?
|
||||
else {
|
||||
// Forgejo answers 204 (no content) when the edit was a no-op.
|
||||
bail!("hive-forge comment-edit: comment {} not updated", args.id);
|
||||
};
|
||||
print_json(&json!({
|
||||
"id": resp.get("id"),
|
||||
"user": resp.get("user").and_then(|u| u.get("login")),
|
||||
"url": resp.get("html_url"),
|
||||
"id": resp.id,
|
||||
"user": resp.user.as_ref().and_then(|u| u.login.as_deref()),
|
||||
"url": resp.html_url,
|
||||
}))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
//! `comment-show <id>` — print the body (or full JSON envelope
|
||||
//! when `--json` is set globally) of a single comment by id.
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::{Result, bail};
|
||||
use clap::Args as ClapArgs;
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::verbs::print_json;
|
||||
use crate::client::{Client, index};
|
||||
use crate::verbs::{print_json, rfc3339};
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
pub struct Args {
|
||||
|
|
@ -15,20 +15,26 @@ pub struct Args {
|
|||
}
|
||||
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let v = client.get_json(&format!("/repos/{repo}/issues/comments/{}", args.id))?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let Some(c) = client
|
||||
.api()
|
||||
.issue_get_comment(owner, name, index(args.id)?)
|
||||
.send()?
|
||||
else {
|
||||
bail!("hive-forge comment-show: comment {} not found", args.id);
|
||||
};
|
||||
if client.json_mode() {
|
||||
let trimmed = json!({
|
||||
"id": v.get("id"),
|
||||
"user": v.get("user").and_then(|u| u.get("login")),
|
||||
"created_at": v.get("created_at"),
|
||||
"updated_at": v.get("updated_at"),
|
||||
"body": v.get("body"),
|
||||
"url": v.get("html_url"),
|
||||
"id": c.id,
|
||||
"user": c.user.as_ref().and_then(|u| u.login.as_deref()),
|
||||
"created_at": rfc3339(c.created_at),
|
||||
"updated_at": rfc3339(c.updated_at),
|
||||
"body": c.body,
|
||||
"url": c.html_url,
|
||||
});
|
||||
print_json(&trimmed)
|
||||
} else {
|
||||
let body = v.get("body").and_then(Value::as_str).unwrap_or("");
|
||||
let body = c.body.as_deref().unwrap_or("");
|
||||
println!("{body}");
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,11 +28,12 @@
|
|||
|
||||
use anyhow::Result;
|
||||
use clap::Args as ClapArgs;
|
||||
use forgejo_api::structs::IssueGetCommentsQuery;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
use crate::notify;
|
||||
use crate::verbs::print_json;
|
||||
use crate::verbs::{print_json, rfc3339};
|
||||
|
||||
/// Forgejo's per-page comment cap. The API caps `limit` at 50 even
|
||||
/// if a higher value is requested; pin it explicitly so the math
|
||||
|
|
@ -59,12 +60,12 @@ pub struct Args {
|
|||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let thread = match args.tail {
|
||||
Some(n) => fetch_tail(client, repo, args.number, n)?,
|
||||
None => fetch_head(client, repo, args.number, args.limit)?,
|
||||
Some(n) => fetch_tail(client, args.number, n)?,
|
||||
None => fetch_head(client, args.number, args.limit)?,
|
||||
};
|
||||
// Merge in PR review bodies (empty for issues — degrades to a
|
||||
// no-op) so review feedback isn't silently dropped.
|
||||
let comments = merge_chronological(thread, fetch_review_bodies(client, repo, args.number));
|
||||
let comments = merge_chronological(thread, fetch_review_bodies(client, args.number));
|
||||
// Reading the thread clears its unread notification so the
|
||||
// read-before-comment guard (in `comment`) lets a reply through.
|
||||
notify::mark_read_best_effort(client, repo, args.number);
|
||||
|
|
@ -106,6 +107,16 @@ pub fn run(client: &Client, args: Args) -> Result<()> {
|
|||
}
|
||||
}
|
||||
|
||||
/// Serialize a typed comment page back to the JSON `Value` shape the
|
||||
/// merge + render pipeline works on (the structs serialize to the API
|
||||
/// wire shape, so downstream field access is unchanged).
|
||||
fn to_values<T: serde::Serialize>(items: Vec<T>) -> Result<Vec<Value>> {
|
||||
items
|
||||
.into_iter()
|
||||
.map(|c| serde_json::to_value(&c).map_err(Into::into))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Fetch a PR's review *bodies* and normalise them to the comment
|
||||
/// shape so they merge alongside issue-thread comments.
|
||||
///
|
||||
|
|
@ -119,34 +130,37 @@ pub fn run(client: &Client, args: Args) -> Result<()> {
|
|||
/// `created_at` is synthesised from the review's `submitted_at` so
|
||||
/// the chronological merge sorts uniformly; `kind:"review"` + the
|
||||
/// review `state` tag the entry for display.
|
||||
fn fetch_review_bodies(client: &Client, repo: &str, number: u64) -> Vec<Value> {
|
||||
fn fetch_review_bodies(client: &Client, number: u64) -> Vec<Value> {
|
||||
let Ok((owner, name)) = client.owner_repo() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Ok(idx) = index(number) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let reviews = client
|
||||
.get_json(&format!("/repos/{repo}/pulls/{number}/reviews"))
|
||||
.ok()
|
||||
.and_then(|v| v.as_array().cloned())
|
||||
.api()
|
||||
.repo_list_pull_reviews(owner, name, idx)
|
||||
.send()
|
||||
.map(|(_, reviews)| reviews)
|
||||
.unwrap_or_default();
|
||||
reviews
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let state = r.get("state").and_then(Value::as_str).unwrap_or("");
|
||||
let state = r.state.as_deref().unwrap_or("").to_owned();
|
||||
if state == "PENDING" {
|
||||
return None;
|
||||
}
|
||||
if r.get("body")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.is_empty()
|
||||
{
|
||||
if r.body.as_deref().unwrap_or("").trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let submitted = rfc3339(r.submitted_at);
|
||||
Some(json!({
|
||||
"id": r.get("id"),
|
||||
"user": r.get("user"),
|
||||
"created_at": r.get("submitted_at"),
|
||||
"updated_at": r.get("submitted_at"),
|
||||
"body": r.get("body"),
|
||||
"html_url": r.get("html_url"),
|
||||
"id": r.id,
|
||||
"user": r.user,
|
||||
"created_at": submitted,
|
||||
"updated_at": submitted,
|
||||
"body": r.body,
|
||||
"html_url": r.html_url,
|
||||
"kind": "review",
|
||||
"state": state,
|
||||
}))
|
||||
|
|
@ -170,11 +184,19 @@ fn merge_chronological(mut items: Vec<Value>, reviews: Vec<Value>) -> Vec<Value>
|
|||
}
|
||||
|
||||
/// Fetch the first page's worth of comments (existing behaviour).
|
||||
fn fetch_head(client: &Client, repo: &str, number: u64, limit: u64) -> Result<Vec<Value>> {
|
||||
let v = client.get_json(&format!(
|
||||
"/repos/{repo}/issues/{number}/comments?limit={limit}"
|
||||
))?;
|
||||
Ok(v.as_array().cloned().unwrap_or_default())
|
||||
fn fetch_head(client: &Client, number: u64, limit: u64) -> Result<Vec<Value>> {
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let (_, comments) = client
|
||||
.api()
|
||||
.issue_get_comments(
|
||||
owner,
|
||||
name,
|
||||
index(number)?,
|
||||
IssueGetCommentsQuery::default(),
|
||||
)
|
||||
.page_size(u32::try_from(limit).unwrap_or(u32::MAX))
|
||||
.send()?;
|
||||
to_values(comments)
|
||||
}
|
||||
|
||||
/// Fetch the last `n` comments on an issue/PR in chronological order.
|
||||
|
|
@ -186,16 +208,17 @@ fn fetch_head(client: &Client, repo: &str, number: u64, limit: u64) -> Result<Ve
|
|||
/// first to know how many exist, then start paginating from the
|
||||
/// page that contains item `total - n`. Work is bounded by
|
||||
/// `ceil(n/50) + 1` page fetches, regardless of thread length.
|
||||
#[allow(
|
||||
clippy::cast_possible_truncation,
|
||||
reason = "the forge `comments` count cast to usize is a small issue-thread length, never anywhere near usize::MAX even on a 32-bit target, so it cannot truncate in practice"
|
||||
)]
|
||||
fn fetch_tail(client: &Client, repo: &str, number: u64, n: usize) -> Result<Vec<Value>> {
|
||||
fn fetch_tail(client: &Client, number: u64, n: usize) -> Result<Vec<Value>> {
|
||||
if n == 0 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let issue = client.get_json(&format!("/repos/{repo}/issues/{number}"))?;
|
||||
let total = issue.get("comments").and_then(Value::as_u64).unwrap_or(0) as usize;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let idx = index(number)?;
|
||||
let issue = client.api().issue_get_issue(owner, name, idx).send()?;
|
||||
let total = issue
|
||||
.comments
|
||||
.and_then(|c| usize::try_from(c).ok())
|
||||
.unwrap_or(0);
|
||||
if total == 0 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
|
@ -210,17 +233,19 @@ fn fetch_tail(client: &Client, repo: &str, number: u64, n: usize) -> Result<Vec<
|
|||
let last_page = (total - 1) / page_size + 1;
|
||||
let mut merged: Vec<Value> = Vec::with_capacity(n + page_size);
|
||||
for page in start_page..=last_page {
|
||||
let v = client.get_json(&format!(
|
||||
"/repos/{repo}/issues/{number}/comments?limit={PAGE_SIZE}&page={page}"
|
||||
))?;
|
||||
let arr = v.as_array().cloned().unwrap_or_default();
|
||||
let (_, arr) = client
|
||||
.api()
|
||||
.issue_get_comments(owner, name, idx, IssueGetCommentsQuery::default())
|
||||
.page(u32::try_from(page).unwrap_or(u32::MAX))
|
||||
.page_size(u32::try_from(PAGE_SIZE).unwrap_or(u32::MAX))
|
||||
.send()?;
|
||||
if arr.is_empty() {
|
||||
// Page came back empty — either we miscounted (comments
|
||||
// deleted between the issue GET and now) or upstream's
|
||||
// playing tricks. Stop rather than spin.
|
||||
break;
|
||||
}
|
||||
merged.extend(arr);
|
||||
merged.extend(to_values(arr)?);
|
||||
}
|
||||
// The first fetched page contains items from `start_page` × 50
|
||||
// back; we overshoot by `start_idx % 50` items. Slice the tail
|
||||
|
|
|
|||
|
|
@ -15,8 +15,9 @@
|
|||
|
||||
use anyhow::Result;
|
||||
use clap::Args as ClapArgs;
|
||||
use forgejo_api::structs::RepoDownloadPullDiffOrPatchQuery;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
pub struct Args {
|
||||
|
|
@ -31,11 +32,17 @@ pub struct Args {
|
|||
}
|
||||
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let diff = client.get_text(
|
||||
&format!("/repos/{repo}/pulls/{}.diff", args.number),
|
||||
"text/plain",
|
||||
)?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let diff = client
|
||||
.api()
|
||||
.repo_download_pull_diff_or_patch(
|
||||
owner,
|
||||
name,
|
||||
index(args.number)?,
|
||||
"diff",
|
||||
RepoDownloadPullDiffOrPatchQuery::default(),
|
||||
)
|
||||
.send()?;
|
||||
let out = if args.full {
|
||||
diff
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -2,9 +2,9 @@
|
|||
|
||||
use anyhow::Result;
|
||||
use clap::Args as ClapArgs;
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
use crate::verbs::print_json;
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
|
|
@ -14,22 +14,33 @@ pub struct Args {
|
|||
}
|
||||
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let v = client.get_json(&format!("/repos/{repo}/issues/{}", args.number))?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let issue = client
|
||||
.api()
|
||||
.issue_get_issue(owner, name, index(args.number)?)
|
||||
.send()?;
|
||||
let assignees: Vec<&str> = issue
|
||||
.assignees
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(|u| u.login.as_deref())
|
||||
.collect();
|
||||
let labels: Vec<&str> = issue
|
||||
.labels
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(|l| l.name.as_deref())
|
||||
.collect();
|
||||
let trimmed = json!({
|
||||
"number": v.get("number"),
|
||||
"title": v.get("title"),
|
||||
"state": v.get("state"),
|
||||
"user": v.get("user").and_then(|u| u.get("login")),
|
||||
"assignees": v.get("assignees")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(|x| x.get("login")).cloned().collect::<Vec<_>>())
|
||||
.unwrap_or_default(),
|
||||
"labels": v.get("labels")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(|x| x.get("name")).cloned().collect::<Vec<_>>())
|
||||
.unwrap_or_default(),
|
||||
"body": v.get("body"),
|
||||
"number": issue.number,
|
||||
"title": issue.title,
|
||||
"state": issue.state,
|
||||
"user": issue.user.as_ref().and_then(|u| u.login.as_deref()),
|
||||
"assignees": assignees,
|
||||
"labels": labels,
|
||||
"body": issue.body,
|
||||
});
|
||||
print_json(&trimmed)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
|
||||
use anyhow::Result;
|
||||
use clap::Args as ClapArgs;
|
||||
use serde_json::{Value, json};
|
||||
use forgejo_api::structs::CreateIssueOption;
|
||||
|
||||
use crate::body;
|
||||
use crate::client::Client;
|
||||
|
|
@ -32,13 +32,23 @@ pub struct Args {
|
|||
/// I/O error from writing the issue URL to stdout.
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let body = body::resolve(args.body.as_deref(), args.body_file.as_deref())?.unwrap_or_default();
|
||||
let repo = client.repo();
|
||||
let mut payload = json!({ "title": args.title, "body": body });
|
||||
if let Some(a) = args.assignee {
|
||||
payload["assignees"] = json!([a]);
|
||||
}
|
||||
let resp = client.post_json(&format!("/repos/{repo}/issues"), &payload)?;
|
||||
if let Some(url) = resp.get("html_url").and_then(Value::as_str) {
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let payload = CreateIssueOption {
|
||||
assignee: None,
|
||||
assignees: args.assignee.map(|a| vec![a]),
|
||||
body: Some(body),
|
||||
closed: None,
|
||||
due_date: None,
|
||||
labels: None,
|
||||
milestone: None,
|
||||
r#ref: None,
|
||||
title: args.title,
|
||||
};
|
||||
let issue = client
|
||||
.api()
|
||||
.issue_create_issue(owner, name, payload)
|
||||
.send()?;
|
||||
if let Some(url) = issue.html_url {
|
||||
println!("{url}");
|
||||
}
|
||||
Ok(())
|
||||
|
|
|
|||
|
|
@ -4,10 +4,11 @@
|
|||
|
||||
use anyhow::Result;
|
||||
use clap::{Args as ClapArgs, ValueEnum};
|
||||
use serde_json::{Map, Value, json};
|
||||
use forgejo_api::structs::EditIssueOption;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::body;
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
use crate::verbs::print_json;
|
||||
|
||||
#[derive(Copy, Clone, ValueEnum)]
|
||||
|
|
@ -55,7 +56,9 @@ pub struct Args {
|
|||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
// Body is partial: only update the body field if a source was
|
||||
// actually given. Piped stdin without --body/--body-file leaves
|
||||
// body alone (the partial-update contract).
|
||||
// body alone (the partial-update contract). Absent fields ride as
|
||||
// JSON `null`, which Forgejo's partial-update binding treats as
|
||||
// "leave unchanged".
|
||||
let body_explicit = args.body.is_some() || args.body_file.is_some();
|
||||
let body = if body_explicit {
|
||||
body::resolve(args.body.as_deref(), args.body_file.as_deref())?
|
||||
|
|
@ -63,29 +66,28 @@ pub fn run(client: &Client, args: Args) -> Result<()> {
|
|||
None
|
||||
};
|
||||
|
||||
let mut payload = Map::new();
|
||||
if let Some(t) = args.title {
|
||||
payload.insert("title".into(), Value::String(t));
|
||||
}
|
||||
if let Some(b) = body {
|
||||
payload.insert("body".into(), Value::String(b));
|
||||
}
|
||||
if let Some(s) = args.state {
|
||||
payload.insert("state".into(), Value::String(s.as_str().to_owned()));
|
||||
}
|
||||
if let Some(m) = args.milestone {
|
||||
payload.insert("milestone".into(), Value::Number(m.into()));
|
||||
}
|
||||
let payload = EditIssueOption {
|
||||
assignee: None,
|
||||
assignees: None,
|
||||
body,
|
||||
due_date: None,
|
||||
milestone: args.milestone.map(index).transpose()?,
|
||||
r#ref: None,
|
||||
state: args.state.map(|s| s.as_str().to_owned()),
|
||||
title: args.title,
|
||||
unset_due_date: None,
|
||||
updated_at: None,
|
||||
};
|
||||
|
||||
let repo = client.repo();
|
||||
let resp = client.patch_json(
|
||||
&format!("/repos/{repo}/issues/{}", args.number),
|
||||
&Value::Object(payload),
|
||||
)?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let resp = client
|
||||
.api()
|
||||
.issue_edit_issue(owner, name, index(args.number)?, payload)
|
||||
.send()?;
|
||||
print_json(&json!({
|
||||
"number": resp.get("number"),
|
||||
"title": resp.get("title"),
|
||||
"state": resp.get("state"),
|
||||
"milestone": resp.get("milestone").and_then(|m| m.get("title")),
|
||||
"number": resp.number,
|
||||
"title": resp.title,
|
||||
"state": resp.state,
|
||||
"milestone": resp.milestone.as_ref().and_then(|m| m.title.as_deref()),
|
||||
}))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,9 +3,10 @@
|
|||
|
||||
use anyhow::{Result, bail};
|
||||
use clap::{Args as ClapArgs, Subcommand};
|
||||
use serde_json::{Value, json};
|
||||
use forgejo_api::structs::{DeleteLabelsOption, IssueLabelsOption, IssueListLabelsQuery, Label};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
use crate::verbs::print_json;
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
|
|
@ -33,85 +34,84 @@ enum Action {
|
|||
}
|
||||
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let idx = index(args.number)?;
|
||||
match args.action.unwrap_or(Action::List) {
|
||||
Action::List => {
|
||||
let labels =
|
||||
client.get_json(&format!("/repos/{repo}/issues/{}/labels", args.number))?;
|
||||
let labels = client.api().issue_get_labels(owner, name, idx).send()?;
|
||||
print_label_names(&labels);
|
||||
}
|
||||
Action::Add { labels } => {
|
||||
if labels.is_empty() {
|
||||
bail!("hive-forge labels add: pass at least one label name");
|
||||
}
|
||||
let all = client.get_json(&format!("/repos/{repo}/labels?limit=100"))?;
|
||||
let ids = resolve_ids(&all, &labels);
|
||||
let resp = client.post_json(
|
||||
&format!("/repos/{repo}/issues/{}/labels", args.number),
|
||||
&json!({ "labels": ids }),
|
||||
)?;
|
||||
let all = repo_labels(client)?;
|
||||
let ids: Vec<serde_json::Value> = resolve_ids(&all, &labels)
|
||||
.into_iter()
|
||||
.map(|id| json!(id))
|
||||
.collect();
|
||||
let resp = client
|
||||
.api()
|
||||
.issue_add_label(
|
||||
owner,
|
||||
name,
|
||||
idx,
|
||||
IssueLabelsOption {
|
||||
labels: Some(ids),
|
||||
updated_at: None,
|
||||
},
|
||||
)
|
||||
.send()?;
|
||||
print_label_names(&resp);
|
||||
}
|
||||
Action::Remove { labels } => {
|
||||
if labels.is_empty() {
|
||||
bail!("hive-forge labels remove: pass at least one label name");
|
||||
}
|
||||
let all = client.get_json(&format!("/repos/{repo}/labels?limit=100"))?;
|
||||
for name in &labels {
|
||||
if let Some(id) = lookup_id(&all, name) {
|
||||
let _ = client.delete(
|
||||
&format!("/repos/{repo}/issues/{}/labels/{id}", args.number),
|
||||
None,
|
||||
);
|
||||
let all = repo_labels(client)?;
|
||||
for label in &labels {
|
||||
if let Some(id) = lookup_id(&all, label) {
|
||||
let _ = client
|
||||
.api()
|
||||
.issue_remove_label(
|
||||
owner,
|
||||
name,
|
||||
idx,
|
||||
&id.to_string(),
|
||||
DeleteLabelsOption { updated_at: None },
|
||||
)
|
||||
.send();
|
||||
}
|
||||
}
|
||||
let labels =
|
||||
client.get_json(&format!("/repos/{repo}/issues/{}/labels", args.number))?;
|
||||
let labels = client.api().issue_get_labels(owner, name, idx).send()?;
|
||||
print_label_names(&labels);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn resolve_ids(all: &Value, names: &[String]) -> Vec<u64> {
|
||||
let Some(arr) = all.as_array() else {
|
||||
return Vec::new();
|
||||
};
|
||||
names
|
||||
.iter()
|
||||
.filter_map(|n| {
|
||||
arr.iter().find_map(|l| {
|
||||
let lname = l.get("name").and_then(Value::as_str)?;
|
||||
if lname == n {
|
||||
l.get("id").and_then(Value::as_u64)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
/// First page (100) of the repo's label set, for name → id resolution.
|
||||
fn repo_labels(client: &Client) -> Result<Vec<Label>> {
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let (_, labels) = client
|
||||
.api()
|
||||
.issue_list_labels(owner, name, IssueListLabelsQuery::default())
|
||||
.page_size(100)
|
||||
.send()?;
|
||||
Ok(labels)
|
||||
}
|
||||
|
||||
fn lookup_id(all: &Value, name: &str) -> Option<u64> {
|
||||
let arr = all.as_array()?;
|
||||
arr.iter().find_map(|l| {
|
||||
let lname = l.get("name").and_then(Value::as_str)?;
|
||||
if lname == name {
|
||||
l.get("id").and_then(Value::as_u64)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
fn resolve_ids(all: &[Label], names: &[String]) -> Vec<i64> {
|
||||
names.iter().filter_map(|n| lookup_id(all, n)).collect()
|
||||
}
|
||||
|
||||
fn print_label_names(v: &Value) {
|
||||
let names: Vec<&str> = v
|
||||
.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|l| l.get("name").and_then(Value::as_str))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
fn lookup_id(all: &[Label], name: &str) -> Option<i64> {
|
||||
all.iter()
|
||||
.find(|l| l.name.as_deref() == Some(name))
|
||||
.and_then(|l| l.id)
|
||||
}
|
||||
|
||||
fn print_label_names(labels: &[Label]) {
|
||||
let names: Vec<&str> = labels.iter().filter_map(|l| l.name.as_deref()).collect();
|
||||
let _ = print_json(&json!(names));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,14 +10,18 @@
|
|||
//! - `assignments [--user NAME]`
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use anyhow::{Result, bail};
|
||||
use clap::{Args as ClapArgs, Subcommand, ValueEnum};
|
||||
use forgejo_api::structs::{
|
||||
Issue, IssueGetCommentsQuery, IssueListIssuesQuery, IssueListIssuesQueryState,
|
||||
IssueListIssuesQueryType, RepoListPullRequestsQuery, RepoListPullRequestsQueryState,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::verbs::print_json;
|
||||
use crate::verbs::{print_json, rfc3339};
|
||||
|
||||
/// Safety cap on paginated walks: 20 pages × 50 items = 1000.
|
||||
/// Plenty for the hyperhive repo today; bump if a future repo trips it.
|
||||
|
|
@ -53,11 +57,14 @@ enum Kind {
|
|||
}
|
||||
|
||||
impl Kind {
|
||||
fn forgejo_type(self) -> &'static str {
|
||||
/// Forgejo's `type` filter: `issues` / `pulls`, or absent for the
|
||||
/// both-kinds slice (the forge returns everything when `type` is
|
||||
/// omitted).
|
||||
fn query_type(self) -> Option<IssueListIssuesQueryType> {
|
||||
match self {
|
||||
Kind::Issues => "issues",
|
||||
Kind::Pulls => "pulls",
|
||||
Kind::All => "all",
|
||||
Kind::Issues => Some(IssueListIssuesQueryType::Issues),
|
||||
Kind::Pulls => Some(IssueListIssuesQueryType::Pulls),
|
||||
Kind::All => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -70,11 +77,19 @@ enum State {
|
|||
}
|
||||
|
||||
impl State {
|
||||
fn as_str(self) -> &'static str {
|
||||
fn issue_state(self) -> IssueListIssuesQueryState {
|
||||
match self {
|
||||
State::Open => "open",
|
||||
State::Closed => "closed",
|
||||
State::All => "all",
|
||||
State::Open => IssueListIssuesQueryState::Open,
|
||||
State::Closed => IssueListIssuesQueryState::Closed,
|
||||
State::All => IssueListIssuesQueryState::All,
|
||||
}
|
||||
}
|
||||
|
||||
fn pull_state(self) -> RepoListPullRequestsQueryState {
|
||||
match self {
|
||||
State::Open => RepoListPullRequestsQueryState::Open,
|
||||
State::Closed => RepoListPullRequestsQueryState::Closed,
|
||||
State::All => RepoListPullRequestsQueryState::All,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -125,26 +140,44 @@ pub fn run(client: &Client, args: Args) -> Result<()> {
|
|||
}
|
||||
}
|
||||
|
||||
/// Drain the repo's issue list (both kinds unless filtered) across
|
||||
/// pages, up to the runaway cap.
|
||||
fn fetch_issues(
|
||||
client: &Client,
|
||||
r#type: Option<IssueListIssuesQueryType>,
|
||||
state: IssueListIssuesQueryState,
|
||||
) -> Result<Vec<Issue>> {
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let mut items = Vec::new();
|
||||
for page in 1..=MAX_PAGES {
|
||||
let query = IssueListIssuesQuery {
|
||||
state: Some(state),
|
||||
r#type,
|
||||
..Default::default()
|
||||
};
|
||||
let (_, batch) = client
|
||||
.api()
|
||||
.issue_list_issues(owner, name, query)
|
||||
.page(page)
|
||||
.page_size(PAGE_LIMIT)
|
||||
.send()?;
|
||||
let short = batch.len() < PAGE_LIMIT as usize;
|
||||
items.extend(batch);
|
||||
if short {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
// ───────────────────────── unassigned ─────────────────────────
|
||||
|
||||
fn run_unassigned(client: &Client, args: UnassignedArgs) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let items = client.get_json_all(
|
||||
&format!(
|
||||
"/repos/{repo}/issues?type={}&state={}&limit={PAGE_LIMIT}",
|
||||
args.r#type.forgejo_type(),
|
||||
args.state.as_str()
|
||||
),
|
||||
MAX_PAGES,
|
||||
)?;
|
||||
let items = fetch_issues(client, args.r#type.query_type(), args.state.issue_state())?;
|
||||
let filtered: Vec<Value> = items
|
||||
.into_iter()
|
||||
.filter(|it| {
|
||||
it.get("assignees")
|
||||
.and_then(Value::as_array)
|
||||
.is_none_or(Vec::is_empty)
|
||||
})
|
||||
.map(trim_item)
|
||||
.iter()
|
||||
.filter(|it| it.assignees.as_ref().is_none_or(Vec::is_empty))
|
||||
.map(trim_issue)
|
||||
.collect();
|
||||
emit(client, &filtered, |it| {
|
||||
format!("#{} [{}] {}", num(it), kind_label(it), title(it))
|
||||
|
|
@ -154,41 +187,64 @@ fn run_unassigned(client: &Client, args: UnassignedArgs) -> Result<()> {
|
|||
// ───────────────────────── no-reviewer ────────────────────────
|
||||
|
||||
fn run_no_reviewer(client: &Client, args: NoReviewerArgs) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
// PR-only: `/repos/{repo}/pulls` doesn't return issues.
|
||||
let pulls = client.get_json_all(
|
||||
&format!(
|
||||
"/repos/{repo}/pulls?state={}&limit={PAGE_LIMIT}",
|
||||
args.state.as_str()
|
||||
),
|
||||
MAX_PAGES,
|
||||
)?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
// PR-only: the pulls endpoint doesn't return issues.
|
||||
let mut pulls = Vec::new();
|
||||
for page in 1..=MAX_PAGES {
|
||||
let query = RepoListPullRequestsQuery {
|
||||
state: Some(args.state.pull_state()),
|
||||
..Default::default()
|
||||
};
|
||||
let (_, batch) = client
|
||||
.api()
|
||||
.repo_list_pull_requests(owner, name, query)
|
||||
.page(page)
|
||||
.page_size(PAGE_LIMIT)
|
||||
.send()?;
|
||||
let short = batch.len() < PAGE_LIMIT as usize;
|
||||
pulls.extend(batch);
|
||||
if short {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let needle = format!("@{}", args.reviewer);
|
||||
let mut missing: Vec<Value> = Vec::new();
|
||||
for pr in pulls {
|
||||
let number = pr.get("number").and_then(Value::as_u64).unwrap_or(0);
|
||||
if number == 0 {
|
||||
for pr in &pulls {
|
||||
let Some(number) = pr.number.filter(|n| *n > 0) else {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// Check PR body itself first — saves a comment-fetch on freshly-opened PRs
|
||||
// that already @reviewer in the description.
|
||||
let body = pr.get("body").and_then(Value::as_str).unwrap_or("");
|
||||
if body.contains(&needle) {
|
||||
if pr.body.as_deref().unwrap_or("").contains(&needle) {
|
||||
continue;
|
||||
}
|
||||
// Paginate so PRs with >50 comments don't yield false positives
|
||||
// (flagged in review). Same 1000-comment ceiling as elsewhere.
|
||||
let comments = client.get_json_all(
|
||||
&format!("/repos/{repo}/issues/{number}/comments?limit={PAGE_LIMIT}"),
|
||||
MAX_PAGES,
|
||||
)?;
|
||||
let mentioned = comments.iter().any(|c| {
|
||||
c.get("body")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|body| body.contains(&needle))
|
||||
});
|
||||
let mut mentioned = false;
|
||||
for page in 1..=MAX_PAGES {
|
||||
let (_, comments) = client
|
||||
.api()
|
||||
.issue_get_comments(owner, name, number, IssueGetCommentsQuery::default())
|
||||
.page(page)
|
||||
.page_size(PAGE_LIMIT)
|
||||
.send()?;
|
||||
let short = comments.len() < PAGE_LIMIT as usize;
|
||||
mentioned = comments
|
||||
.iter()
|
||||
.any(|c| c.body.as_deref().is_some_and(|body| body.contains(&needle)));
|
||||
if mentioned || short {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !mentioned {
|
||||
missing.push(trim_item(pr));
|
||||
missing.push(json!({
|
||||
"number": pr.number,
|
||||
"title": pr.title,
|
||||
"state": pr.state,
|
||||
"url": pr.html_url,
|
||||
"is_pr": true,
|
||||
"assignees": logins(pr.assignees.as_deref()),
|
||||
}));
|
||||
}
|
||||
}
|
||||
emit(client, &missing, |it| format!("#{} {}", num(it), title(it)))
|
||||
|
|
@ -200,50 +256,64 @@ fn run_stale_branches(client: &Client, args: StaleBranchesArgs) -> Result<()> {
|
|||
if args.days < 0 {
|
||||
bail!("--days must be non-negative");
|
||||
}
|
||||
let repo = client.repo();
|
||||
let branches = client.get_json_all(
|
||||
&format!("/repos/{repo}/branches?limit={PAGE_LIMIT}"),
|
||||
MAX_PAGES,
|
||||
)?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let mut branches = Vec::new();
|
||||
for page in 1..=MAX_PAGES {
|
||||
let (_, batch) = client
|
||||
.api()
|
||||
.repo_list_branches(owner, name)
|
||||
.page(page)
|
||||
.page_size(PAGE_LIMIT)
|
||||
.send()?;
|
||||
let short = batch.len() < PAGE_LIMIT as usize;
|
||||
branches.extend(batch);
|
||||
if short {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Collect active PR head refs to skip — a branch with an open PR
|
||||
// isn't "stale", it's "in review".
|
||||
let open_pulls = client.get_json_all(
|
||||
&format!("/repos/{repo}/pulls?state=open&limit={PAGE_LIMIT}"),
|
||||
MAX_PAGES,
|
||||
)?;
|
||||
let active_heads: std::collections::HashSet<String> = open_pulls
|
||||
.iter()
|
||||
.filter_map(|p| {
|
||||
p.get("head")
|
||||
.and_then(|h| h.get("ref"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
})
|
||||
.collect();
|
||||
let mut active_heads: std::collections::HashSet<String> = std::collections::HashSet::new();
|
||||
for page in 1..=MAX_PAGES {
|
||||
let query = RepoListPullRequestsQuery {
|
||||
state: Some(RepoListPullRequestsQueryState::Open),
|
||||
..Default::default()
|
||||
};
|
||||
let (_, batch) = client
|
||||
.api()
|
||||
.repo_list_pull_requests(owner, name, query)
|
||||
.page(page)
|
||||
.page_size(PAGE_LIMIT)
|
||||
.send()?;
|
||||
let short = batch.len() < PAGE_LIMIT as usize;
|
||||
active_heads.extend(
|
||||
batch
|
||||
.iter()
|
||||
.filter_map(|p| p.head.as_ref().and_then(|h| h.r#ref.clone())),
|
||||
);
|
||||
if short {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let cutoff_days = today_days_utc().context("compute today")? - args.days;
|
||||
let today = OffsetDateTime::now_utc().date();
|
||||
let mut stale: Vec<Value> = Vec::new();
|
||||
for br in branches {
|
||||
let name = br.get("name").and_then(Value::as_str).unwrap_or("");
|
||||
if name.is_empty() || active_heads.contains(name) {
|
||||
for br in &branches {
|
||||
let branch_name = br.name.as_deref().unwrap_or("");
|
||||
if branch_name.is_empty() || active_heads.contains(branch_name) {
|
||||
continue;
|
||||
}
|
||||
let ts = br
|
||||
.get("commit")
|
||||
.and_then(|c| c.get("timestamp"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("");
|
||||
let Some(date_str) = ts.get(..10) else {
|
||||
let Some(ts) = br.commit.as_ref().and_then(|c| c.timestamp) else {
|
||||
continue;
|
||||
};
|
||||
let Some(days) = parse_yyyy_mm_dd_days(date_str) else {
|
||||
continue;
|
||||
};
|
||||
if days <= cutoff_days {
|
||||
// Whole days between the commit's calendar date and today —
|
||||
// date-granular, matching the old YYYY-MM-DD prefix math.
|
||||
let age_days = (today - ts.date()).whole_days();
|
||||
if age_days >= args.days {
|
||||
stale.push(json!({
|
||||
"name": name,
|
||||
"last_commit": ts,
|
||||
"age_days": (today_days_utc().unwrap_or(days) - days),
|
||||
"name": branch_name,
|
||||
"last_commit": rfc3339(Some(ts)),
|
||||
"age_days": age_days,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
|
@ -257,27 +327,14 @@ fn run_stale_branches(client: &Client, args: StaleBranchesArgs) -> Result<()> {
|
|||
// ───────────────────────── assignments ────────────────────────
|
||||
|
||||
fn run_assignments(client: &Client, args: AssignmentsArgs) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let items = client.get_json_all(
|
||||
&format!("/repos/{repo}/issues?type=all&state=open&limit={PAGE_LIMIT}"),
|
||||
MAX_PAGES,
|
||||
)?;
|
||||
let items = fetch_issues(client, None, IssueListIssuesQueryState::Open)?;
|
||||
let mut by_user: BTreeMap<String, Vec<Value>> = BTreeMap::new();
|
||||
for it in items {
|
||||
let assignees: Vec<String> = it
|
||||
.get("assignees")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|x| x.get("login").and_then(Value::as_str))
|
||||
.map(str::to_owned)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
for it in &items {
|
||||
let assignees = logins(it.assignees.as_deref());
|
||||
if assignees.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let slim = trim_item(it);
|
||||
let slim = trim_issue(it);
|
||||
for u in assignees {
|
||||
if args.user.as_deref().is_some_and(|w| w != u) {
|
||||
continue;
|
||||
|
|
@ -317,27 +374,27 @@ fn run_assignments(client: &Client, args: AssignmentsArgs) -> Result<()> {
|
|||
|
||||
// ───────────────────────── shared helpers ─────────────────────
|
||||
|
||||
/// Strip a Forgejo issue/PR JSON down to the fields lint output cares
|
||||
/// Assignee logins from a typed user list (missing logins dropped).
|
||||
fn logins(users: Option<&[forgejo_api::structs::User]>) -> Vec<String> {
|
||||
users
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(|u| u.login.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Strip a Forgejo issue/PR down to the fields lint output cares
|
||||
/// about. Mirrors the trim pattern in `verbs/issue.rs`.
|
||||
fn trim_item(it: Value) -> Value {
|
||||
fn trim_issue(it: &Issue) -> Value {
|
||||
json!({
|
||||
"number": it.get("number"),
|
||||
"title": it.get("title"),
|
||||
"state": it.get("state"),
|
||||
"url": it.get("html_url"),
|
||||
// Forgejo's unified /issues endpoint always emits a
|
||||
// `pull_request` key — `null` for plain issues, an object
|
||||
// (with merged/url/etc.) for PRs. Treat any non-null as a PR.
|
||||
"is_pr": it.get("pull_request").is_some_and(|v| !v.is_null()),
|
||||
"assignees": it
|
||||
.get("assignees")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|x| x.get("login").cloned())
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
"number": it.number,
|
||||
"title": it.title,
|
||||
"state": it.state,
|
||||
"url": it.html_url,
|
||||
// The unified issues endpoint marks PRs with a `pull_request`
|
||||
// object (absent/null for plain issues).
|
||||
"is_pr": it.pull_request.is_some(),
|
||||
"assignees": logins(it.assignees.as_deref()),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -375,77 +432,3 @@ where
|
|||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// ─── tiny date helpers (avoid pulling in chrono/time for one verb) ───
|
||||
|
||||
/// Days since 1970-01-01 in UTC for "today" (best-effort from system clock).
|
||||
fn today_days_utc() -> Result<i64> {
|
||||
let secs = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.context("system clock before epoch")?
|
||||
.as_secs();
|
||||
// `as_secs()` returns u64; clamp into i64 (won't overflow until y2554).
|
||||
Ok(i64::try_from(secs / 86_400).unwrap_or(i64::MAX))
|
||||
}
|
||||
|
||||
/// Parse a `YYYY-MM-DD` (e.g. the first 10 chars of an RFC3339 stamp)
|
||||
/// into days-since-1970-01-01 (UTC midnight). Returns `None` on parse
|
||||
/// failure rather than panicking — lint output stays best-effort.
|
||||
fn parse_yyyy_mm_dd_days(stamp: &str) -> Option<i64> {
|
||||
let bytes = stamp.as_bytes();
|
||||
if bytes.len() < 10 || bytes[4] != b'-' || bytes[7] != b'-' {
|
||||
return None;
|
||||
}
|
||||
let year: i32 = std::str::from_utf8(&bytes[0..4]).ok()?.parse().ok()?;
|
||||
let month: u32 = std::str::from_utf8(&bytes[5..7]).ok()?.parse().ok()?;
|
||||
let day: u32 = std::str::from_utf8(&bytes[8..10]).ok()?.parse().ok()?;
|
||||
if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
|
||||
return None;
|
||||
}
|
||||
Some(days_from_civil(year, month, day))
|
||||
}
|
||||
|
||||
/// Howard Hinnant's `days_from_civil`: proleptic Gregorian → days since
|
||||
/// 1970-01-01. Public-domain reference algorithm. Handles negative years.
|
||||
fn days_from_civil(year: i32, month: u32, day: u32) -> i64 {
|
||||
let y = if month <= 2 { year - 1 } else { year };
|
||||
let era = if y >= 0 { y } else { y - 399 } / 400;
|
||||
let yoe = i64::from(y - era * 400); // [0, 399]
|
||||
let m = i64::from(month);
|
||||
let d = i64::from(day);
|
||||
let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
|
||||
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
|
||||
i64::from(era) * 146_097 + doe - 719_468
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn epoch_is_day_zero() {
|
||||
assert_eq!(days_from_civil(1970, 1, 1), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_dates() {
|
||||
// Hinnant reference values
|
||||
assert_eq!(days_from_civil(2000, 1, 1), 10_957);
|
||||
assert_eq!(days_from_civil(2020, 2, 29), 18_321);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_iso_prefix() {
|
||||
assert_eq!(
|
||||
parse_yyyy_mm_dd_days("2020-02-29T12:00:00+02:00"),
|
||||
Some(18_321)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_input() {
|
||||
assert_eq!(parse_yyyy_mm_dd_days("not-a-date"), None);
|
||||
assert_eq!(parse_yyyy_mm_dd_days("2020/02/29"), None);
|
||||
assert_eq!(parse_yyyy_mm_dd_days("2020-13-01"), None);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,19 +10,20 @@
|
|||
//! read-side curl-fallback gap (no boundary concerns —
|
||||
//! every agent + the operator queries the issue tracker constantly).
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::{Args as ClapArgs, ValueEnum};
|
||||
use forgejo_api::structs::{
|
||||
IssueListIssuesQuery, IssueListIssuesQueryState, IssueListIssuesQueryType,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::verbs::print_json;
|
||||
|
||||
/// What kind of items to return. Matches Forgejo's `type` query
|
||||
/// parameter values verbatim (`issues` / `pulls` / `all`) so the
|
||||
/// mapping is one-for-one and a future enum addition upstream
|
||||
/// stays trivially supportable.
|
||||
/// What kind of items to return. Maps onto Forgejo's `type` query
|
||||
/// parameter: `issues` / `pulls`, or no filter at all for `both`
|
||||
/// (Forgejo returns issues + PRs when `type` is absent — same slice
|
||||
/// the forge UI's "Issues" tab shows without a type filter).
|
||||
#[derive(Copy, Clone, Debug, ValueEnum)]
|
||||
#[clap(rename_all = "kebab-case")]
|
||||
pub enum Kind {
|
||||
|
|
@ -30,17 +31,16 @@ pub enum Kind {
|
|||
Issue,
|
||||
/// Pull requests only.
|
||||
Pr,
|
||||
/// Issues + pull requests (default; matches the forge UI's
|
||||
/// "Issues" tab when no type filter is applied).
|
||||
/// Issues + pull requests (default).
|
||||
Both,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
fn api_value(self) -> &'static str {
|
||||
fn query_type(self) -> Option<IssueListIssuesQueryType> {
|
||||
match self {
|
||||
Self::Issue => "issues",
|
||||
Self::Pr => "pulls",
|
||||
Self::Both => "all",
|
||||
Self::Issue => Some(IssueListIssuesQueryType::Issues),
|
||||
Self::Pr => Some(IssueListIssuesQueryType::Pulls),
|
||||
Self::Both => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -56,11 +56,11 @@ pub enum State {
|
|||
}
|
||||
|
||||
impl State {
|
||||
fn api_value(self) -> &'static str {
|
||||
fn query_state(self) -> IssueListIssuesQueryState {
|
||||
match self {
|
||||
Self::Open => "open",
|
||||
Self::Closed => "closed",
|
||||
Self::All => "all",
|
||||
Self::Open => IssueListIssuesQueryState::Open,
|
||||
Self::Closed => IssueListIssuesQueryState::Closed,
|
||||
Self::All => IssueListIssuesQueryState::All,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -100,54 +100,40 @@ pub struct Args {
|
|||
}
|
||||
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let mut path = format!(
|
||||
"/repos/{repo}/issues?type={}&state={}&limit={}&page={}",
|
||||
args.kind.api_value(),
|
||||
args.state.api_value(),
|
||||
args.limit,
|
||||
args.page
|
||||
);
|
||||
if let Some(u) = args.assignee.as_deref()
|
||||
&& !u.is_empty()
|
||||
{
|
||||
write!(path, "&assigned_by={}", super::pct_encode(u)).unwrap();
|
||||
}
|
||||
if let Some(u) = args.author.as_deref()
|
||||
&& !u.is_empty()
|
||||
{
|
||||
write!(path, "&created_by={}", super::pct_encode(u)).unwrap();
|
||||
}
|
||||
if let Some(u) = args.mention.as_deref()
|
||||
&& !u.is_empty()
|
||||
{
|
||||
write!(path, "&mentioned_by={}", super::pct_encode(u)).unwrap();
|
||||
}
|
||||
if !args.labels.is_empty() {
|
||||
// Encode each label individually so a comma INSIDE a label
|
||||
// (rare but legal) gets escaped while the field separator
|
||||
// stays a literal comma the forge will parse as N labels.
|
||||
let encoded: Vec<String> = args.labels.iter().map(|l| super::pct_encode(l)).collect();
|
||||
write!(path, "&labels={}", encoded.join(",")).unwrap();
|
||||
}
|
||||
let resp = client.get_json(&path)?;
|
||||
if client.json_mode() {
|
||||
return print_json(&resp);
|
||||
}
|
||||
let Some(items) = resp.as_array() else {
|
||||
// Forge returned something other than an array — most likely
|
||||
// an error envelope; fall back to JSON-dumping so the user
|
||||
// can see what came back.
|
||||
return print_json(&resp);
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let query = IssueListIssuesQuery {
|
||||
state: Some(args.state.query_state()),
|
||||
// The forge parses `labels` as a comma-separated list of names.
|
||||
labels: (!args.labels.is_empty()).then(|| args.labels.join(",")),
|
||||
q: None,
|
||||
r#type: args.kind.query_type(),
|
||||
milestones: None,
|
||||
since: None,
|
||||
before: None,
|
||||
created_by: args.author.clone().filter(|s| !s.is_empty()),
|
||||
assigned_by: args.assignee.clone().filter(|s| !s.is_empty()),
|
||||
mentioned_by: args.mention.clone().filter(|s| !s.is_empty()),
|
||||
sort: None,
|
||||
};
|
||||
for item in items {
|
||||
let (_, issues) = client
|
||||
.api()
|
||||
.issue_list_issues(owner, name, query)
|
||||
.page(u32::try_from(args.page).unwrap_or(u32::MAX))
|
||||
.page_size(u32::try_from(args.limit).unwrap_or(u32::MAX))
|
||||
.send()?;
|
||||
let count = issues.len() as u64;
|
||||
let items = serde_json::to_value(issues)?;
|
||||
if client.json_mode() {
|
||||
return print_json(&items);
|
||||
}
|
||||
for item in items.as_array().into_iter().flatten() {
|
||||
print_row(item);
|
||||
}
|
||||
// When the returned page is exactly `--limit` items, more pages
|
||||
// may exist. Print a hint to stderr so the caller knows to fetch
|
||||
// the next page rather than assuming the result is complete. Only
|
||||
// fires on a full page — a short or empty page signals the end.
|
||||
if items.len() as u64 == args.limit {
|
||||
if count == args.limit {
|
||||
eprintln!(
|
||||
"… {} shown (page {}); more results may exist — re-run with --page {} (or raise --limit).",
|
||||
args.limit,
|
||||
|
|
@ -184,19 +170,25 @@ mod tests {
|
|||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn kind_api_values_match_forgejo_enum() {
|
||||
// The forge accepts only `issues` / `pulls` / `all` for the
|
||||
// `type` parameter — pin the wire mapping so a clap rename
|
||||
fn kind_query_types_match_forgejo_enum() {
|
||||
// The forge accepts only `issues` / `pulls` for the `type`
|
||||
// parameter (absent = both) — pin the mapping so a clap rename
|
||||
// doesn't silently start returning the wrong slice.
|
||||
assert_eq!(Kind::Issue.api_value(), "issues");
|
||||
assert_eq!(Kind::Pr.api_value(), "pulls");
|
||||
assert_eq!(Kind::Both.api_value(), "all");
|
||||
assert_eq!(
|
||||
Kind::Issue.query_type(),
|
||||
Some(IssueListIssuesQueryType::Issues)
|
||||
);
|
||||
assert_eq!(Kind::Pr.query_type(), Some(IssueListIssuesQueryType::Pulls));
|
||||
assert_eq!(Kind::Both.query_type(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_api_values_match_forgejo_enum() {
|
||||
assert_eq!(State::Open.api_value(), "open");
|
||||
assert_eq!(State::Closed.api_value(), "closed");
|
||||
assert_eq!(State::All.api_value(), "all");
|
||||
fn state_query_states_match_forgejo_enum() {
|
||||
assert_eq!(State::Open.query_state(), IssueListIssuesQueryState::Open);
|
||||
assert_eq!(
|
||||
State::Closed.query_state(),
|
||||
IssueListIssuesQueryState::Closed
|
||||
);
|
||||
assert_eq!(State::All.query_state(), IssueListIssuesQueryState::All);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,12 +1,17 @@
|
|||
//! `milestone list|create|close` — manage milestones. Default action:
|
||||
//! list.
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::{Context, Result};
|
||||
use clap::{Args as ClapArgs, Subcommand};
|
||||
use forgejo_api::structs::{
|
||||
CreateMilestoneOption, EditMilestoneOption, IssueGetMilestonesListQuery,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
use time::format_description::well_known::Rfc3339;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::verbs::print_json;
|
||||
use crate::client::{Client, index};
|
||||
use crate::verbs::{print_json, rfc3339};
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
pub struct Args {
|
||||
|
|
@ -38,52 +43,71 @@ enum Action {
|
|||
}
|
||||
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
match args.action.unwrap_or(Action::List) {
|
||||
Action::List => {
|
||||
let v = client.get_json(&format!("/repos/{repo}/milestones?state=open&limit=50"))?;
|
||||
let trimmed: Vec<Value> = v
|
||||
.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.map(|m| {
|
||||
json!({
|
||||
"id": m.get("id"),
|
||||
"title": m.get("title"),
|
||||
"open_issues": m.get("open_issues"),
|
||||
"closed_issues": m.get("closed_issues"),
|
||||
"due_on": m.get("due_on"),
|
||||
"description": m.get("description"),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
let query = IssueGetMilestonesListQuery {
|
||||
state: Some("open".to_owned()),
|
||||
name: None,
|
||||
};
|
||||
let (_, milestones) = client
|
||||
.api()
|
||||
.issue_get_milestones_list(owner, name, query)
|
||||
.page_size(50)
|
||||
.send()?;
|
||||
let trimmed: Vec<Value> = milestones
|
||||
.iter()
|
||||
.map(|m| {
|
||||
json!({
|
||||
"id": m.id,
|
||||
"title": m.title,
|
||||
"open_issues": m.open_issues,
|
||||
"closed_issues": m.closed_issues,
|
||||
"due_on": rfc3339(m.due_on),
|
||||
"description": m.description,
|
||||
})
|
||||
})
|
||||
.unwrap_or_default();
|
||||
.collect();
|
||||
print_json(&Value::Array(trimmed))
|
||||
}
|
||||
Action::Create { title, desc, due } => {
|
||||
let mut payload = json!({ "title": title });
|
||||
if let Some(d) = desc.filter(|s| !s.is_empty()) {
|
||||
payload["description"] = Value::String(d);
|
||||
}
|
||||
if let Some(d) = due.filter(|s| !s.is_empty()) {
|
||||
payload["due_on"] = Value::String(format!("{d}T00:00:00Z"));
|
||||
}
|
||||
let resp = client.post_json(&format!("/repos/{repo}/milestones"), &payload)?;
|
||||
let due_on = due
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|d| {
|
||||
OffsetDateTime::parse(&format!("{d}T00:00:00Z"), &Rfc3339)
|
||||
.with_context(|| format!("milestone create: bad --due date {d:?}"))
|
||||
})
|
||||
.transpose()?;
|
||||
let payload = CreateMilestoneOption {
|
||||
description: desc.filter(|s| !s.is_empty()),
|
||||
due_on,
|
||||
state: None,
|
||||
title: Some(title),
|
||||
};
|
||||
let resp = client
|
||||
.api()
|
||||
.issue_create_milestone(owner, name, payload)
|
||||
.send()?;
|
||||
print_json(&json!({
|
||||
"id": resp.get("id"),
|
||||
"title": resp.get("title"),
|
||||
"id": resp.id,
|
||||
"title": resp.title,
|
||||
}))
|
||||
}
|
||||
Action::Close { id } => {
|
||||
let resp = client.patch_json(
|
||||
&format!("/repos/{repo}/milestones/{id}"),
|
||||
&json!({ "state": "closed" }),
|
||||
)?;
|
||||
let payload = EditMilestoneOption {
|
||||
description: None,
|
||||
due_on: None,
|
||||
state: Some("closed".to_owned()),
|
||||
title: None,
|
||||
};
|
||||
let resp = client
|
||||
.api()
|
||||
.issue_edit_milestone(owner, name, index(id)?, payload)
|
||||
.send()?;
|
||||
print_json(&json!({
|
||||
"id": resp.get("id"),
|
||||
"title": resp.get("title"),
|
||||
"state": resp.get("state"),
|
||||
"id": resp.id,
|
||||
"title": resp.title,
|
||||
"state": resp.state,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,8 +46,10 @@ use std::fmt::Write as _;
|
|||
|
||||
use anyhow::Result;
|
||||
use serde_json::Value;
|
||||
use time::OffsetDateTime;
|
||||
use time::format_description::well_known::Rfc3339;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
|
||||
/// Pretty-print a `serde_json` value to stdout with a trailing newline,
|
||||
/// matching the bash script's `| jq` output shape.
|
||||
|
|
@ -57,6 +59,15 @@ pub(crate) fn print_json(v: &Value) -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Format an optional timestamp as its RFC 3339 string — the shape the
|
||||
/// raw API emitted, so output stays stable across the typed-client
|
||||
/// port. `None` (and the never-in-practice unformattable timestamp)
|
||||
/// map to `None` so callers keep their existing null/placeholder
|
||||
/// handling.
|
||||
pub(crate) fn rfc3339(ts: Option<OffsetDateTime>) -> Option<String> {
|
||||
ts.and_then(|t| t.format(&Rfc3339).ok())
|
||||
}
|
||||
|
||||
/// Issue-vs-PR kind, for the `pr <verb>` / `issue <verb>` sub-command
|
||||
/// validation.
|
||||
#[derive(Clone, Copy)]
|
||||
|
|
@ -72,9 +83,12 @@ pub(crate) enum Kind {
|
|||
/// PRs and marks PRs with a non-null `pull_request` field, so one GET
|
||||
/// classifies it. Errors with a "use the other command" message on mismatch.
|
||||
pub(crate) fn assert_kind(client: &Client, number: u64, expected: Kind) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let v = client.get_json(&format!("/repos/{repo}/issues/{number}"))?;
|
||||
let is_pr = v.get("pull_request").is_some_and(|p| !p.is_null());
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let issue = client
|
||||
.api()
|
||||
.issue_get_issue(owner, name, index(number)?)
|
||||
.send()?;
|
||||
let is_pr = issue.pull_request.is_some();
|
||||
match (expected, is_pr) {
|
||||
(Kind::Pr, false) => {
|
||||
anyhow::bail!(
|
||||
|
|
@ -89,12 +103,12 @@ pub(crate) fn assert_kind(client: &Client, number: u64, expected: Kind) -> Resul
|
|||
}
|
||||
|
||||
/// Minimal RFC 3986 unreserved-set percent encoder. Covers the subset of
|
||||
/// characters that show up in the values we splice into request paths —
|
||||
/// usernames, label names, artifact names — without pulling in a fresh
|
||||
/// workspace dep. Unreserved bytes (`[A-Za-z0-9-._~]`) pass through, so
|
||||
/// the common identifier case is a no-op; everything else is `%XX`-escaped.
|
||||
/// Shared by `list` (query-string filters) and `artifact-get` (the
|
||||
/// artifact-name path segment).
|
||||
/// characters that show up in the values we splice into *web-route* paths
|
||||
/// (the typed client encodes its own path segments) — artifact names —
|
||||
/// without pulling in a fresh workspace dep. Unreserved bytes
|
||||
/// (`[A-Za-z0-9-._~]`) pass through, so the common identifier case is a
|
||||
/// no-op; everything else is `%XX`-escaped. Used by `artifact-get` (the
|
||||
/// artifact-name path segment on the web download route).
|
||||
pub(crate) fn pct_encode(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for b in s.bytes() {
|
||||
|
|
@ -119,17 +133,30 @@ pub(crate) fn latest_reviews(
|
|||
repo: &str,
|
||||
pr: u64,
|
||||
) -> Result<Vec<(String, String)>> {
|
||||
let reviews = client.get_json_all(&format!("/repos/{repo}/pulls/{pr}/reviews"), 10)?;
|
||||
let (owner, name) = crate::client::split_repo(repo)?;
|
||||
let pr = index(pr)?;
|
||||
// Paginate (50/page, 10-page runaway cap — same ceiling the raw
|
||||
// client used) so a heavily re-reviewed PR doesn't truncate.
|
||||
let mut reviews = Vec::new();
|
||||
for page in 1..=10u32 {
|
||||
let (_, batch) = client
|
||||
.api()
|
||||
.repo_list_pull_reviews(owner, name, pr)
|
||||
.page(page)
|
||||
.page_size(50)
|
||||
.send()?;
|
||||
let short = batch.len() < 50;
|
||||
reviews.extend(batch);
|
||||
if short {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let mut latest: Vec<(String, String)> = Vec::new();
|
||||
for r in &reviews {
|
||||
let Some(login) = r
|
||||
.get("user")
|
||||
.and_then(|u| u.get("login"))
|
||||
.and_then(Value::as_str)
|
||||
else {
|
||||
let Some(login) = r.user.as_ref().and_then(|u| u.login.as_deref()) else {
|
||||
continue;
|
||||
};
|
||||
let st = r.get("state").and_then(Value::as_str).unwrap_or("");
|
||||
let st = r.state.as_deref().unwrap_or("");
|
||||
if st == "COMMENT" || st == "PENDING" || st.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
|
@ -148,8 +175,8 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn pct_encode_passes_unreserved_through() {
|
||||
// Usernames + plain label/artifact names round-trip verbatim —
|
||||
// no performance regression on the common case.
|
||||
// Plain artifact names round-trip verbatim — no performance
|
||||
// regression on the common case.
|
||||
assert_eq!(pct_encode("damocles"), "damocles");
|
||||
assert_eq!(pct_encode("area-ops"), "area-ops");
|
||||
assert_eq!(pct_encode("area_ops"), "area_ops");
|
||||
|
|
@ -158,9 +185,8 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn pct_encode_escapes_reserved() {
|
||||
// Forgejo labels can contain spaces ("good first issue" is the
|
||||
// canonical example); `&` / `/` in any spliced value must escape
|
||||
// so they can't break out of the path/query segment.
|
||||
// `&` / `/` / spaces in any spliced value must escape so they
|
||||
// can't break out of the path/query segment.
|
||||
assert_eq!(pct_encode("good first issue"), "good%20first%20issue");
|
||||
assert_eq!(pct_encode("x&y"), "x%26y");
|
||||
assert_eq!(pct_encode("a/b"), "a%2Fb");
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ use anyhow::Result;
|
|||
use clap::Args as ClapArgs;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
use crate::verbs::print_json;
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
|
|
@ -14,17 +14,20 @@ pub struct Args {
|
|||
}
|
||||
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let v = client.get_json(&format!("/repos/{repo}/pulls/{}", args.number))?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let pull = client
|
||||
.api()
|
||||
.repo_get_pull_request(owner, name, index(args.number)?)
|
||||
.send()?;
|
||||
let trimmed = json!({
|
||||
"number": v.get("number"),
|
||||
"title": v.get("title"),
|
||||
"state": v.get("state"),
|
||||
"merged": v.get("merged"),
|
||||
"user": v.get("user").and_then(|u| u.get("login")),
|
||||
"head_sha": v.get("head").and_then(|h| h.get("sha")),
|
||||
"head_branch": v.get("head").and_then(|h| h.get("label")),
|
||||
"base_branch": v.get("base").and_then(|b| b.get("label")),
|
||||
"number": pull.number,
|
||||
"title": pull.title,
|
||||
"state": pull.state,
|
||||
"merged": pull.merged,
|
||||
"user": pull.user.as_ref().and_then(|u| u.login.as_deref()),
|
||||
"head_sha": pull.head.as_ref().and_then(|h| h.sha.as_deref()),
|
||||
"head_branch": pull.head.as_ref().and_then(|h| h.label.as_deref()),
|
||||
"base_branch": pull.base.as_ref().and_then(|b| b.label.as_deref()),
|
||||
});
|
||||
print_json(&trimmed)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,9 +8,9 @@
|
|||
|
||||
use anyhow::Result;
|
||||
use clap::Args as ClapArgs;
|
||||
use serde_json::json;
|
||||
use forgejo_api::structs::PullReviewRequestOptions;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
pub struct Args {
|
||||
|
|
@ -24,17 +24,26 @@ pub struct Args {
|
|||
}
|
||||
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let path = format!("/repos/{repo}/pulls/{}/requested_reviewers", args.number);
|
||||
let body = json!({ "reviewers": [args.user] });
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let idx = index(args.number)?;
|
||||
let body = PullReviewRequestOptions {
|
||||
reviewers: Some(vec![args.user.clone()]),
|
||||
team_reviewers: None,
|
||||
};
|
||||
if args.remove {
|
||||
client.delete(&path, Some(&body))?;
|
||||
client
|
||||
.api()
|
||||
.repo_delete_pull_review_requests(owner, name, idx, body)
|
||||
.send()?;
|
||||
println!(
|
||||
"review request withdrawn: {} on #{}",
|
||||
args.user, args.number
|
||||
);
|
||||
} else {
|
||||
client.post_json(&path, &body)?;
|
||||
client
|
||||
.api()
|
||||
.repo_create_pull_review_requests(owner, name, idx, body)
|
||||
.send()?;
|
||||
println!("review requested: {} on #{}", args.user, args.number);
|
||||
}
|
||||
Ok(())
|
||||
|
|
|
|||
|
|
@ -10,15 +10,19 @@
|
|||
|
||||
use anyhow::Result;
|
||||
use clap::Args as ClapArgs;
|
||||
use forgejo_api::structs::{Commit, RepoGetPullRequestCommitsQuery};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::verbs::print_json;
|
||||
use crate::client::{Client, index};
|
||||
use crate::verbs::{print_json, rfc3339};
|
||||
|
||||
/// Page cap for the commit list. Forgejo serves up to 50 commits per
|
||||
/// page; 40 pages (2000 commits) is far beyond any real PR.
|
||||
const MAX_PAGES: u32 = 40;
|
||||
|
||||
/// Page size on the commit list endpoint (Forgejo's cap).
|
||||
const PAGE_SIZE: u32 = 50;
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
pub struct Args {
|
||||
/// PR number.
|
||||
|
|
@ -26,22 +30,35 @@ pub struct Args {
|
|||
}
|
||||
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let commits = client.get_json_all(
|
||||
&format!("/repos/{repo}/pulls/{}/commits", args.number),
|
||||
MAX_PAGES,
|
||||
)?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let idx = index(args.number)?;
|
||||
let mut commits: Vec<Commit> = Vec::new();
|
||||
for page in 1..=MAX_PAGES {
|
||||
let (_, batch) = client
|
||||
.api()
|
||||
.repo_get_pull_request_commits(
|
||||
owner,
|
||||
name,
|
||||
idx,
|
||||
RepoGetPullRequestCommitsQuery::default(),
|
||||
)
|
||||
.page(page)
|
||||
.page_size(PAGE_SIZE)
|
||||
.send()?;
|
||||
let short = batch.len() < PAGE_SIZE as usize;
|
||||
commits.extend(batch);
|
||||
if short {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let trimmed: Vec<_> = commits
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let commit = c.get("commit");
|
||||
json!({
|
||||
"sha": c.get("sha"),
|
||||
"message": commit.and_then(|x| x.get("message")),
|
||||
"author_date": commit
|
||||
.and_then(|x| x.get("author"))
|
||||
.and_then(|a| a.get("date")),
|
||||
"author": c.get("author").and_then(|u| u.get("login")),
|
||||
"sha": c.sha,
|
||||
"message": c.commit.as_ref().and_then(|x| x.message.as_deref()),
|
||||
"author_date": rfc3339(c.commit.as_ref().and_then(|x| x.author.as_ref()).and_then(|a| a.date)),
|
||||
"author": c.author.as_ref().and_then(|u| u.login.as_deref()),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
|
|
|||
|
|
@ -25,10 +25,10 @@ use std::process::{Command, Stdio};
|
|||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Args as ClapArgs;
|
||||
use serde_json::{Value, json};
|
||||
use forgejo_api::structs::{CreatePullRequestOption, EditIssueOption};
|
||||
|
||||
use crate::body;
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
pub struct Args {
|
||||
|
|
@ -97,17 +97,27 @@ pub fn run(client: &Client, args: Args) -> Result<()> {
|
|||
if args.push {
|
||||
push_branch(remote, head)?;
|
||||
}
|
||||
let repo = client.repo();
|
||||
let payload = json!({
|
||||
"title": args.title,
|
||||
"head": head,
|
||||
"base": args.base,
|
||||
"body": body,
|
||||
"draft": args.draft,
|
||||
"allow_maintainer_edit": true,
|
||||
});
|
||||
let resp = client.post_json(&format!("/repos/{repo}/pulls"), &payload)?;
|
||||
if let Some(url) = resp.get("html_url").and_then(Value::as_str) {
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
// Note: Forgejo's CreatePullRequestOption has no `draft` /
|
||||
// `allow_maintainer_edit` fields (verified against the instance's
|
||||
// swagger) — the raw client used to send both and the server
|
||||
// silently dropped them, so omitting them here changes nothing.
|
||||
let payload = CreatePullRequestOption {
|
||||
assignee: None,
|
||||
assignees: None,
|
||||
base: Some(args.base.clone()),
|
||||
body: Some(body),
|
||||
due_date: None,
|
||||
head: Some(head.to_owned()),
|
||||
labels: None,
|
||||
milestone: None,
|
||||
title: Some(args.title.clone()),
|
||||
};
|
||||
let resp = client
|
||||
.api()
|
||||
.repo_create_pull_request(owner, name, payload)
|
||||
.send()?;
|
||||
if let Some(url) = resp.html_url {
|
||||
println!("{url}");
|
||||
}
|
||||
Ok(())
|
||||
|
|
@ -182,12 +192,23 @@ fn agit_create(client: &Client, args: &Args, body: &str) -> Result<()> {
|
|||
};
|
||||
if deferred_body {
|
||||
if let Some(number) = pr_number_from_url(&url) {
|
||||
let repo = client.repo();
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let payload = EditIssueOption {
|
||||
assignee: None,
|
||||
assignees: None,
|
||||
body: Some(body.to_owned()),
|
||||
due_date: None,
|
||||
milestone: None,
|
||||
r#ref: None,
|
||||
state: None,
|
||||
title: None,
|
||||
unset_due_date: None,
|
||||
updated_at: None,
|
||||
};
|
||||
client
|
||||
.patch_json(
|
||||
&format!("/repos/{repo}/issues/{number}"),
|
||||
&json!({ "body": body }),
|
||||
)
|
||||
.api()
|
||||
.issue_edit_issue(owner, name, index(number)?, payload)
|
||||
.send()
|
||||
.with_context(|| format!("set body on AGit PR #{number}"))?;
|
||||
} else {
|
||||
eprintln!(
|
||||
|
|
|
|||
|
|
@ -14,9 +14,11 @@
|
|||
|
||||
use anyhow::{Result, bail};
|
||||
use clap::{Args as ClapArgs, ValueEnum};
|
||||
use serde_json::{Value, json};
|
||||
use forgejo_api::structs::{
|
||||
CommitStatusState, MergePullRequestOption, MergePullRequestOptionDo, PullRequest, StateType,
|
||||
};
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index, split_repo};
|
||||
|
||||
/// Merge strategy. Squash is deliberately omitted (hive convention: keep the
|
||||
/// per-commit history, so a squash option isn't exposed).
|
||||
|
|
@ -29,13 +31,22 @@ pub enum Method {
|
|||
}
|
||||
|
||||
impl Method {
|
||||
/// The Forgejo `Do` field value for this strategy.
|
||||
/// The Forgejo `Do` field value for this strategy (used for the
|
||||
/// confirmation message).
|
||||
fn forgejo_do(self) -> &'static str {
|
||||
match self {
|
||||
Method::Merge => "merge",
|
||||
Method::Rebase => "rebase",
|
||||
}
|
||||
}
|
||||
|
||||
/// The typed `Do` enum variant for the merge request body.
|
||||
fn as_option_do(self) -> MergePullRequestOptionDo {
|
||||
match self {
|
||||
Method::Merge => MergePullRequestOptionDo::Merge,
|
||||
Method::Rebase => MergePullRequestOptionDo::Rebase,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
|
|
@ -65,12 +76,17 @@ pub struct Args {
|
|||
/// be merged).
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let pull = client.get_json(&format!("/repos/{repo}/pulls/{}", args.number))?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let idx = index(args.number)?;
|
||||
let pull = client
|
||||
.api()
|
||||
.repo_get_pull_request(owner, name, idx)
|
||||
.send()?;
|
||||
|
||||
if pull.get("merged").and_then(Value::as_bool).unwrap_or(false) {
|
||||
if pull.merged.unwrap_or(false) {
|
||||
bail!("pr-merge: PR #{} is already merged", args.number);
|
||||
}
|
||||
if pull.get("state").and_then(Value::as_str) == Some("closed") {
|
||||
if pull.state == Some(StateType::Closed) {
|
||||
bail!("pr-merge: PR #{} is closed", args.number);
|
||||
}
|
||||
|
||||
|
|
@ -78,15 +94,20 @@ pub fn run(client: &Client, args: Args) -> Result<()> {
|
|||
check_ready(client, repo, args.number, &pull)?;
|
||||
}
|
||||
|
||||
let payload = json!({
|
||||
"Do": args.method.forgejo_do(),
|
||||
"delete_branch_after_merge": !args.keep_branch,
|
||||
"force_merge": args.force,
|
||||
});
|
||||
client.post_no_content(
|
||||
&format!("/repos/{repo}/pulls/{}/merge", args.number),
|
||||
&payload,
|
||||
)?;
|
||||
let payload = MergePullRequestOption {
|
||||
r#do: args.method.as_option_do(),
|
||||
merge_commit_id: None,
|
||||
merge_message_field: None,
|
||||
merge_title_field: None,
|
||||
delete_branch_after_merge: Some(!args.keep_branch),
|
||||
force_merge: Some(args.force),
|
||||
head_commit_id: None,
|
||||
merge_when_checks_succeed: None,
|
||||
};
|
||||
client
|
||||
.api()
|
||||
.repo_merge_pull_request(owner, name, idx, payload)
|
||||
.send()?;
|
||||
|
||||
let deleted = if args.keep_branch {
|
||||
""
|
||||
|
|
@ -105,8 +126,8 @@ pub fn run(client: &Client, args: Args) -> Result<()> {
|
|||
/// mergeable, CI must not be red/pending, and no review may request changes.
|
||||
/// Bails with an actionable message (pointing at `--force`) on the first
|
||||
/// failure.
|
||||
fn check_ready(client: &Client, repo: &str, number: u64, pull: &Value) -> Result<()> {
|
||||
match pull.get("mergeable").and_then(Value::as_bool) {
|
||||
fn check_ready(client: &Client, repo: &str, number: u64, pull: &PullRequest) -> Result<()> {
|
||||
match pull.mergeable {
|
||||
Some(true) => {}
|
||||
Some(false) => bail!(
|
||||
"pr-merge: PR #{number} is not mergeable (conflicts). Rebase it, or pass --force."
|
||||
|
|
@ -116,20 +137,18 @@ fn check_ready(client: &Client, repo: &str, number: u64, pull: &Value) -> Result
|
|||
),
|
||||
}
|
||||
|
||||
if let Some(sha) = pull
|
||||
.get("head")
|
||||
.and_then(|h| h.get("sha"))
|
||||
.and_then(Value::as_str)
|
||||
{
|
||||
let combined = client.get_json(&format!("/repos/{repo}/commits/{sha}/status"))?;
|
||||
let state = combined.get("state").and_then(Value::as_str).unwrap_or("");
|
||||
let has_statuses = combined
|
||||
.get("statuses")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|a| !a.is_empty());
|
||||
if let Some(sha) = pull.head.as_ref().and_then(|h| h.sha.as_deref()) {
|
||||
let (owner, name) = split_repo(repo)?;
|
||||
let (_, combined) = client
|
||||
.api()
|
||||
.repo_get_combined_status_by_ref(owner, name, sha)
|
||||
.send()?;
|
||||
let state = combined.state;
|
||||
let has_statuses = combined.statuses.as_ref().is_some_and(|a| !a.is_empty());
|
||||
// An empty status set means no CI is configured — not a blocker.
|
||||
// Anything other than success once CI exists blocks the merge.
|
||||
if has_statuses && state != "success" {
|
||||
if has_statuses && state != Some(CommitStatusState::Success) {
|
||||
let state = super::pr_status::status_state_str(state);
|
||||
bail!(
|
||||
"pr-merge: PR #{number} CI is not green (state: {state}). Wait for green, or pass --force."
|
||||
);
|
||||
|
|
@ -167,13 +186,20 @@ mod tests {
|
|||
#[test]
|
||||
fn merge_payload_shape() {
|
||||
// delete-by-default: keep_branch=false → delete_branch_after_merge=true.
|
||||
let payload = json!({
|
||||
"Do": Method::Merge.forgejo_do(),
|
||||
"delete_branch_after_merge": true,
|
||||
"force_merge": false,
|
||||
});
|
||||
assert_eq!(payload["Do"], "merge");
|
||||
assert_eq!(payload["delete_branch_after_merge"], true);
|
||||
assert_eq!(payload["force_merge"], false);
|
||||
// Pin the wire shape of the typed body — `Do` casing included.
|
||||
let payload = MergePullRequestOption {
|
||||
r#do: Method::Merge.as_option_do(),
|
||||
merge_commit_id: None,
|
||||
merge_message_field: None,
|
||||
merge_title_field: None,
|
||||
delete_branch_after_merge: Some(true),
|
||||
force_merge: Some(false),
|
||||
head_commit_id: None,
|
||||
merge_when_checks_succeed: None,
|
||||
};
|
||||
let wire = serde_json::to_value(&payload).unwrap();
|
||||
assert_eq!(wire["Do"], "merge");
|
||||
assert_eq!(wire["delete_branch_after_merge"], true);
|
||||
assert_eq!(wire["force_merge"], false);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,9 +3,10 @@
|
|||
|
||||
use anyhow::{Result, bail};
|
||||
use clap::Args as ClapArgs;
|
||||
use forgejo_api::structs::CreatePullReviewOptions;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
use crate::verbs::print_json;
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
|
|
@ -55,53 +56,69 @@ pub fn run(client: &Client, args: Args) -> Result<()> {
|
|||
/// Submit a review event (`APPROVED` / `REQUEST_CHANGES` / `COMMENT`) and print
|
||||
/// a compact summary of the created review.
|
||||
fn submit_review(client: &Client, number: u64, event: &str, body: Option<String>) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let payload = json!({
|
||||
"event": event,
|
||||
"body": body.unwrap_or_default(),
|
||||
});
|
||||
let v = client.post_json(&format!("/repos/{repo}/pulls/{number}/reviews"), &payload)?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let payload = CreatePullReviewOptions {
|
||||
body: Some(body.unwrap_or_default()),
|
||||
comments: None,
|
||||
commit_id: None,
|
||||
event: Some(event.to_owned()),
|
||||
};
|
||||
let review = client
|
||||
.api()
|
||||
.repo_create_pull_review(owner, name, index(number)?, payload)
|
||||
.send()?;
|
||||
print_json(&json!({
|
||||
"id": v.get("id"),
|
||||
"state": v.get("state"),
|
||||
"user": v.get("user").and_then(|u| u.get("login")),
|
||||
"id": review.id,
|
||||
"state": review.state,
|
||||
"user": review.user.as_ref().and_then(|u| u.login.as_deref()),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Fetch inline diff comments for a single review. Returns an empty vec on
|
||||
/// any error (missing review, network failure) so callers can degrade
|
||||
/// gracefully.
|
||||
fn fetch_inline_comments(client: &Client, repo: &str, pr: u64, review_id: u64) -> Vec<Value> {
|
||||
/// Fetch inline diff comments for a single review, serialized back to
|
||||
/// the API's JSON shape. Returns an empty vec on any error (missing
|
||||
/// review, network failure) so callers can degrade gracefully.
|
||||
fn fetch_inline_comments(client: &Client, pr: u64, review_id: i64) -> Vec<Value> {
|
||||
let Ok((owner, name)) = client.owner_repo() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Ok(idx) = index(pr) else {
|
||||
return Vec::new();
|
||||
};
|
||||
client
|
||||
.get_json(&format!(
|
||||
"/repos/{repo}/pulls/{pr}/reviews/{review_id}/comments"
|
||||
))
|
||||
.api()
|
||||
.repo_get_pull_review_comments(owner, name, idx, review_id)
|
||||
.send()
|
||||
.ok()
|
||||
.and_then(|comments| serde_json::to_value(comments).ok())
|
||||
.and_then(|v| v.as_array().cloned())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// List all reviews for a PR, dispatching to the appropriate output mode.
|
||||
fn list_reviews(client: &Client, number: u64) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let v = client.get_json(&format!("/repos/{repo}/pulls/{number}/reviews"))?;
|
||||
let reviews = v.as_array().cloned().unwrap_or_default();
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let (_, reviews) = client
|
||||
.api()
|
||||
.repo_list_pull_reviews(owner, name, index(number)?)
|
||||
.send()?;
|
||||
let reviews = serde_json::to_value(reviews)?;
|
||||
let reviews = reviews.as_array().cloned().unwrap_or_default();
|
||||
if client.json_mode() {
|
||||
list_reviews_json(client, repo, number, &reviews)
|
||||
list_reviews_json(client, number, &reviews)
|
||||
} else {
|
||||
list_reviews_text(client, repo, number, &reviews);
|
||||
list_reviews_text(client, number, &reviews);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON output: one object per review, with an inline `comments` array.
|
||||
fn list_reviews_json(client: &Client, repo: &str, number: u64, reviews: &[Value]) -> Result<()> {
|
||||
fn list_reviews_json(client: &Client, number: u64, reviews: &[Value]) -> Result<()> {
|
||||
let trimmed: Vec<Value> = reviews
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let id = r.get("id").and_then(Value::as_u64).unwrap_or(0);
|
||||
let id = r.get("id").and_then(Value::as_i64).unwrap_or(0);
|
||||
let inline: Vec<Value> = if id > 0 {
|
||||
fetch_inline_comments(client, repo, number, id)
|
||||
fetch_inline_comments(client, number, id)
|
||||
.iter()
|
||||
.map(|c| {
|
||||
json!({
|
||||
|
|
@ -130,13 +147,13 @@ fn list_reviews_json(client: &Client, repo: &str, number: u64, reviews: &[Value]
|
|||
|
||||
/// Human-readable output: Markdown-style heading per review, inline
|
||||
/// comments as `[path:line] body` (line omitted for PR-level comments).
|
||||
fn list_reviews_text(client: &Client, repo: &str, number: u64, reviews: &[Value]) {
|
||||
fn list_reviews_text(client: &Client, number: u64, reviews: &[Value]) {
|
||||
if reviews.is_empty() {
|
||||
println!("(no reviews)");
|
||||
return;
|
||||
}
|
||||
for r in reviews {
|
||||
let id = r.get("id").and_then(Value::as_u64).unwrap_or(0);
|
||||
let id = r.get("id").and_then(Value::as_i64).unwrap_or(0);
|
||||
let user = r
|
||||
.get("user")
|
||||
.and_then(|u| u.get("login"))
|
||||
|
|
@ -149,7 +166,7 @@ fn list_reviews_text(client: &Client, repo: &str, number: u64, reviews: &[Value]
|
|||
println!("{body}");
|
||||
}
|
||||
if id > 0 {
|
||||
for c in &fetch_inline_comments(client, repo, number, id) {
|
||||
for c in &fetch_inline_comments(client, number, id) {
|
||||
let path = c.get("path").and_then(Value::as_str).unwrap_or("?");
|
||||
let cbody = c.get("body").and_then(Value::as_str).unwrap_or("").trim();
|
||||
// PR-level comments have no line; omit `:line` when absent.
|
||||
|
|
|
|||
|
|
@ -11,10 +11,11 @@
|
|||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::Args as ClapArgs;
|
||||
use forgejo_api::structs::{CommitStatusState, IssueGetCommentsQuery};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::verbs::print_json;
|
||||
use crate::client::{Client, index};
|
||||
use crate::verbs::{print_json, rfc3339};
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
pub struct Args {
|
||||
|
|
@ -38,14 +39,29 @@ pub fn run(client: &Client, args: Args) -> Result<()> {
|
|||
let repo = client.repo();
|
||||
match (args.pr, args.sha) {
|
||||
(Some(pr), _) => pr_status(client, repo, pr),
|
||||
(None, Some(sha)) => sha_status(client, repo, &sha),
|
||||
(None, Some(sha)) => sha_status(client, &sha),
|
||||
(None, None) => bail!("pr-status: pass one of --pr <n> or --sha <sha>"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The wire string for a combined/per-context CI status state, matching
|
||||
/// what the raw API emitted (`""` when absent). Shared with `pr-merge`
|
||||
/// for its "CI is not green" message.
|
||||
pub(crate) fn status_state_str(state: Option<CommitStatusState>) -> &'static str {
|
||||
match state {
|
||||
Some(CommitStatusState::Pending) => "pending",
|
||||
Some(CommitStatusState::Success) => "success",
|
||||
Some(CommitStatusState::Error) => "error",
|
||||
Some(CommitStatusState::Failure) => "failure",
|
||||
Some(CommitStatusState::Warning) => "warning",
|
||||
Some(CommitStatusState::Skipped) => "skipped",
|
||||
None => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// CI-only path for an explicit commit. Exit code mirrors the CI verdict.
|
||||
fn sha_status(client: &Client, repo: &str, sha: &str) -> Result<()> {
|
||||
let (state, statuses) = fetch_combined(client, repo, sha)?;
|
||||
fn sha_status(client: &Client, sha: &str) -> Result<()> {
|
||||
let (state, statuses) = fetch_combined(client, sha)?;
|
||||
if client.json_mode() {
|
||||
print_json(&combined_json(sha, &state, &statuses))?;
|
||||
} else {
|
||||
|
|
@ -60,33 +76,36 @@ fn sha_status(client: &Client, repo: &str, sha: &str) -> Result<()> {
|
|||
|
||||
/// Full PR health view. Exit code is a merge-readiness verdict.
|
||||
fn pr_status(client: &Client, repo: &str, pr: u64) -> Result<()> {
|
||||
let pull = client.get_json(&format!("/repos/{repo}/pulls/{pr}"))?;
|
||||
let title = pull.get("title").and_then(Value::as_str).unwrap_or("");
|
||||
let state = pull.get("state").and_then(Value::as_str).unwrap_or("?");
|
||||
let merged = pull.get("merged").and_then(Value::as_bool).unwrap_or(false);
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let pull = client
|
||||
.api()
|
||||
.repo_get_pull_request(owner, name, index(pr)?)
|
||||
.send()?;
|
||||
let title = pull.title.as_deref().unwrap_or("");
|
||||
let state = pull.state.map_or("?", |s| match s {
|
||||
forgejo_api::structs::StateType::Open => "open",
|
||||
forgejo_api::structs::StateType::Closed => "closed",
|
||||
});
|
||||
let merged = pull.merged.unwrap_or(false);
|
||||
// `mergeable` is `null` while the forge is still computing it.
|
||||
let mergeable = pull.get("mergeable").and_then(Value::as_bool);
|
||||
let mergeable = pull.mergeable;
|
||||
let sha = pull
|
||||
.get("head")
|
||||
.and_then(|h| h.get("sha"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
.head
|
||||
.as_ref()
|
||||
.and_then(|h| h.sha.clone())
|
||||
.with_context(|| format!("pr-status: PR #{pr} has no head.sha"))?;
|
||||
|
||||
let requested = pull
|
||||
.get("requested_reviewers")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|u| u.get("login").and_then(Value::as_str))
|
||||
.map(str::to_owned)
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let requested: Vec<String> = pull
|
||||
.requested_reviewers
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(|u| u.login.clone())
|
||||
.collect();
|
||||
|
||||
let (ci_state, ci_statuses) = fetch_combined(client, repo, &sha)?;
|
||||
let (ci_state, ci_statuses) = fetch_combined(client, &sha)?;
|
||||
let reviews = super::latest_reviews(client, repo, pr)?;
|
||||
let last = last_comment(client, repo, pr)?;
|
||||
let last = last_comment(client, pr)?;
|
||||
|
||||
if client.json_mode() {
|
||||
print_json(&serde_json::json!({
|
||||
|
|
@ -136,37 +155,56 @@ fn pr_status(client: &Client, repo: &str, pr: u64) -> Result<()> {
|
|||
}
|
||||
|
||||
/// Fetch the combined commit status: `(overall_state, statuses[])`.
|
||||
fn fetch_combined(client: &Client, repo: &str, sha: &str) -> Result<(String, Vec<Value>)> {
|
||||
let combined = client.get_json(&format!("/repos/{repo}/commits/{sha}/status"))?;
|
||||
let state = combined
|
||||
.get("state")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
/// Statuses ride as their serialized (API-shape) JSON so the render
|
||||
/// helpers stay pure `Value` walkers.
|
||||
fn fetch_combined(client: &Client, sha: &str) -> Result<(String, Vec<Value>)> {
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let (_, combined) = client
|
||||
.api()
|
||||
.repo_get_combined_status_by_ref(owner, name, sha)
|
||||
.send()?;
|
||||
let state = status_state_str(combined.state).to_owned();
|
||||
let statuses = combined
|
||||
.get("statuses")
|
||||
.and_then(Value::as_array)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
.statuses
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(serde_json::to_value)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok((state, statuses))
|
||||
}
|
||||
|
||||
/// The most recent issue comment on the PR, as `(login, created_at)`.
|
||||
/// Comments page oldest-first; we drain (bounded) and take the max
|
||||
/// timestamp so a long thread still reports the genuinely-latest one.
|
||||
fn last_comment(client: &Client, repo: &str, pr: u64) -> Result<Option<(String, String)>> {
|
||||
let comments = client.get_json_all(&format!("/repos/{repo}/issues/{pr}/comments"), 20)?;
|
||||
let last = comments
|
||||
.iter()
|
||||
.filter_map(|c| {
|
||||
let login = c
|
||||
.get("user")
|
||||
.and_then(|u| u.get("login"))
|
||||
.and_then(Value::as_str)?;
|
||||
let created = c.get("created_at").and_then(Value::as_str)?;
|
||||
Some((login.to_owned(), created.to_owned()))
|
||||
})
|
||||
.max_by(|a, b| a.1.cmp(&b.1));
|
||||
fn last_comment(client: &Client, pr: u64) -> Result<Option<(String, String)>> {
|
||||
const PAGE_SIZE: u32 = 50;
|
||||
const MAX_PAGES: u32 = 20;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let idx = index(pr)?;
|
||||
let mut last: Option<(String, String)> = None;
|
||||
for page in 1..=MAX_PAGES {
|
||||
let (_, comments) = client
|
||||
.api()
|
||||
.issue_get_comments(owner, name, idx, IssueGetCommentsQuery::default())
|
||||
.page(page)
|
||||
.page_size(PAGE_SIZE)
|
||||
.send()?;
|
||||
let short = comments.len() < PAGE_SIZE as usize;
|
||||
for c in &comments {
|
||||
let Some(login) = c.user.as_ref().and_then(|u| u.login.clone()) else {
|
||||
continue;
|
||||
};
|
||||
let Some(created) = rfc3339(c.created_at) else {
|
||||
continue;
|
||||
};
|
||||
if last.as_ref().is_none_or(|(_, t)| created > *t) {
|
||||
last = Some((login, created));
|
||||
}
|
||||
}
|
||||
if short {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(last)
|
||||
}
|
||||
|
||||
|
|
@ -323,6 +361,19 @@ mod tests {
|
|||
assert_eq!(status_mark("weird"), "•");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_state_str_matches_wire_names() {
|
||||
assert_eq!(
|
||||
status_state_str(Some(CommitStatusState::Success)),
|
||||
"success"
|
||||
);
|
||||
assert_eq!(
|
||||
status_state_str(Some(CommitStatusState::Failure)),
|
||||
"failure"
|
||||
);
|
||||
assert_eq!(status_state_str(None), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combined_json_shape() {
|
||||
let v = combined_json("abc", "success", &[]);
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ use anyhow::Result;
|
|||
use clap::Args as ClapArgs;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
use crate::verbs::print_json;
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
|
|
@ -20,16 +20,21 @@ pub struct Args {
|
|||
/// # Errors
|
||||
///
|
||||
/// Returns an error when the `PATCH /repos/{repo}/issues/{number}` request
|
||||
/// fails (network / non-success status from `patch_json`) or when emitting
|
||||
/// the JSON summary via `print_json` fails.
|
||||
/// fails (network / non-success status) or when emitting the JSON summary
|
||||
/// via `print_json` fails.
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let resp = client.patch_json(
|
||||
&format!("/repos/{repo}/issues/{}", args.number),
|
||||
&json!({ "state": "open" }),
|
||||
)?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let resp = client
|
||||
.api()
|
||||
.issue_edit_issue(
|
||||
owner,
|
||||
name,
|
||||
index(args.number)?,
|
||||
super::close::state_edit("open"),
|
||||
)
|
||||
.send()?;
|
||||
print_json(&json!({
|
||||
"number": resp.get("number"),
|
||||
"state": resp.get("state"),
|
||||
"number": resp.number,
|
||||
"state": resp.state,
|
||||
}))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@
|
|||
use anyhow::Result;
|
||||
use clap::Args as ClapArgs;
|
||||
use clap::ValueEnum;
|
||||
use serde_json::json;
|
||||
use forgejo_api::structs::{AddCollaboratorOption, AddCollaboratorOptionPermission};
|
||||
|
||||
use crate::client::Client;
|
||||
|
||||
|
|
@ -25,7 +25,8 @@ pub enum Permission {
|
|||
}
|
||||
|
||||
impl Permission {
|
||||
/// The wire string Forgejo's API expects.
|
||||
/// The wire string Forgejo's API expects (used for the printed
|
||||
/// confirmation).
|
||||
fn as_api(self) -> &'static str {
|
||||
match self {
|
||||
Permission::Read => "read",
|
||||
|
|
@ -33,6 +34,15 @@ impl Permission {
|
|||
Permission::Admin => "admin",
|
||||
}
|
||||
}
|
||||
|
||||
/// The typed permission for the request body.
|
||||
fn as_option(self) -> AddCollaboratorOptionPermission {
|
||||
match self {
|
||||
Permission::Read => AddCollaboratorOptionPermission::Read,
|
||||
Permission::Write => AddCollaboratorOptionPermission::Write,
|
||||
Permission::Admin => AddCollaboratorOptionPermission::Admin,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
|
|
@ -53,11 +63,19 @@ pub struct Args {
|
|||
/// writing the confirmation to stdout.
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let perm = args.permission.as_api();
|
||||
client.put_no_content(
|
||||
&format!("/repos/{repo}/collaborators/{}", args.user),
|
||||
&json!({ "permission": perm }),
|
||||
)?;
|
||||
client
|
||||
.api()
|
||||
.repo_add_collaborator(
|
||||
owner,
|
||||
name,
|
||||
&args.user,
|
||||
AddCollaboratorOption {
|
||||
permission: Some(args.permission.as_option()),
|
||||
},
|
||||
)
|
||||
.send()?;
|
||||
println!("added {} to {repo} ({perm})", args.user);
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@
|
|||
|
||||
use anyhow::Result;
|
||||
use clap::Args as ClapArgs;
|
||||
use serde_json::{Value, json};
|
||||
use forgejo_api::structs::CreateRepoOption;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::verbs::print_json;
|
||||
|
|
@ -48,29 +48,31 @@ pub struct Args {
|
|||
/// permission on the target namespace, token missing/invalid) and any
|
||||
/// I/O error from writing the result to stdout.
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let mut payload = json!({
|
||||
"name": args.name,
|
||||
"private": args.private,
|
||||
"auto_init": args.auto_init,
|
||||
});
|
||||
if let Some(d) = args.description {
|
||||
payload["description"] = json!(d);
|
||||
}
|
||||
if let Some(b) = args.default_branch {
|
||||
payload["default_branch"] = json!(b);
|
||||
}
|
||||
let payload = CreateRepoOption {
|
||||
auto_init: Some(args.auto_init),
|
||||
default_branch: args.default_branch,
|
||||
description: args.description,
|
||||
gitignores: None,
|
||||
issue_labels: None,
|
||||
license: None,
|
||||
name: args.name,
|
||||
object_format_name: None,
|
||||
private: Some(args.private),
|
||||
readme: None,
|
||||
template: None,
|
||||
trust_model: None,
|
||||
};
|
||||
|
||||
let path = match args.org.as_deref() {
|
||||
Some(org) => format!("/orgs/{org}/repos"),
|
||||
None => "/user/repos".to_owned(),
|
||||
let resp = match args.org.as_deref() {
|
||||
Some(org) => client.api().create_org_repo(org, payload).send()?,
|
||||
None => client.api().create_current_user_repo(payload).send()?,
|
||||
};
|
||||
let resp = client.post_json(&path, &payload)?;
|
||||
|
||||
if client.json_mode() {
|
||||
return print_json(&resp);
|
||||
return print_json(&serde_json::to_value(&resp)?);
|
||||
}
|
||||
// Default human path: print the web URL, like issue-create / pr-create.
|
||||
if let Some(url) = resp.get("html_url").and_then(Value::as_str) {
|
||||
if let Some(url) = resp.html_url {
|
||||
println!("{url}");
|
||||
}
|
||||
Ok(())
|
||||
|
|
|
|||
|
|
@ -5,11 +5,17 @@
|
|||
|
||||
use anyhow::Result;
|
||||
use clap::Args as ClapArgs;
|
||||
use serde_json::{Value, json};
|
||||
use forgejo_api::structs::{IssueListLabelsQuery, Label};
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::verbs::print_json;
|
||||
|
||||
/// Page size on the label list endpoint.
|
||||
const PAGE_SIZE: u32 = 50;
|
||||
|
||||
/// Runaway cap on label pagination — same ceiling the raw client used.
|
||||
const MAX_PAGES: u32 = 10;
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
pub struct Args {
|
||||
/// Substring pattern to filter label names (case-sensitive).
|
||||
|
|
@ -17,34 +23,46 @@ pub struct Args {
|
|||
}
|
||||
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
// Repos can carry more than one page of labels; paginate so the list
|
||||
// is complete rather than capped at the first page.
|
||||
let labels = client.get_json_all(&format!("/repos/{repo}/labels"), 10)?;
|
||||
let filtered: Vec<&Value> = labels
|
||||
let mut labels: Vec<Label> = Vec::new();
|
||||
for page in 1..=MAX_PAGES {
|
||||
let (_, batch) = client
|
||||
.api()
|
||||
.issue_list_labels(owner, name, IssueListLabelsQuery::default())
|
||||
.page(page)
|
||||
.page_size(PAGE_SIZE)
|
||||
.send()?;
|
||||
let short = batch.len() < PAGE_SIZE as usize;
|
||||
labels.extend(batch);
|
||||
if short {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let filtered: Vec<&Label> = labels
|
||||
.iter()
|
||||
.filter(|l| {
|
||||
let name = l.get("name").and_then(Value::as_str).unwrap_or_default();
|
||||
args.pattern.as_deref().is_none_or(|p| name.contains(p))
|
||||
let label_name = l.name.as_deref().unwrap_or_default();
|
||||
args.pattern
|
||||
.as_deref()
|
||||
.is_none_or(|p| label_name.contains(p))
|
||||
})
|
||||
.collect();
|
||||
|
||||
if client.json_mode() {
|
||||
// Full label objects (id, name, color, description) as a JSON array.
|
||||
print_json(&json!(filtered))?;
|
||||
print_json(&serde_json::to_value(&filtered)?)?;
|
||||
} else {
|
||||
// One label per line: `name`, plus its description (tab-separated)
|
||||
// when set, so triage can see what each label means at a glance.
|
||||
for l in filtered {
|
||||
let name = l.get("name").and_then(Value::as_str).unwrap_or_default();
|
||||
let desc = l
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
let label_name = l.name.as_deref().unwrap_or_default();
|
||||
let desc = l.description.as_deref().unwrap_or_default();
|
||||
if desc.is_empty() {
|
||||
println!("{name}");
|
||||
println!("{label_name}");
|
||||
} else {
|
||||
println!("{name}\t{desc}");
|
||||
println!("{label_name}\t{desc}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ use anyhow::Result;
|
|||
use clap::Args as ClapArgs;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, is_not_found};
|
||||
use crate::verbs::print_json;
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
|
|
@ -38,7 +38,7 @@ pub struct Args {
|
|||
///
|
||||
/// # Errors
|
||||
/// Propagates transport / non-2xx errors from the Forgejo client calls
|
||||
/// (`get_json` / `put_json` / `delete`) and from `print_json`.
|
||||
/// and from `print_json`.
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
if args.list {
|
||||
// List every repo the authed user watches, so an agent can audit
|
||||
|
|
@ -49,48 +49,56 @@ pub fn run(client: &Client, args: Args) -> Result<()> {
|
|||
const PAGE: u32 = 50;
|
||||
let mut watching: Vec<String> = Vec::new();
|
||||
for page in 1..=MAX_PAGES {
|
||||
let v = client.get_json(&format!("/user/subscriptions?page={page}&limit={PAGE}"))?;
|
||||
let arr = v.as_array().cloned().unwrap_or_default();
|
||||
let n = arr.len();
|
||||
watching.extend(
|
||||
arr.iter()
|
||||
.filter_map(|r| r["full_name"].as_str().map(str::to_owned)),
|
||||
);
|
||||
let (_, repos) = client
|
||||
.api()
|
||||
.user_current_list_subscriptions()
|
||||
.page(page)
|
||||
.page_size(PAGE)
|
||||
.send()?;
|
||||
let n = repos.len();
|
||||
watching.extend(repos.into_iter().filter_map(|r| r.full_name));
|
||||
if n < PAGE as usize {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return print_json(&json!({ "watching": watching }));
|
||||
}
|
||||
let repo = client.repo();
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
if args.unwatch {
|
||||
client.delete(&format!("/repos/{repo}/subscription"), None)?;
|
||||
client
|
||||
.api()
|
||||
.user_current_delete_subscription(owner, name)
|
||||
.send()?;
|
||||
println!("unsubscribed");
|
||||
return Ok(());
|
||||
}
|
||||
if args.watch || args.ignore {
|
||||
let (subscribed, ignored) = if args.ignore {
|
||||
(false, true)
|
||||
} else {
|
||||
(true, false)
|
||||
};
|
||||
// Forgejo requires PUT (not POST) for this endpoint.
|
||||
let resp = client.put_json(
|
||||
&format!("/repos/{repo}/subscription"),
|
||||
&json!({ "subscribed": subscribed, "ignored": ignored }),
|
||||
)?;
|
||||
// Forgejo's PUT subscription endpoint takes no body — it always
|
||||
// subscribes (watch). The old raw client sent a
|
||||
// `{subscribed, ignored}` body which the server ignored, so
|
||||
// `--ignore` has always behaved like `--watch` server-side; the
|
||||
// typed call just makes that explicit.
|
||||
let resp = client
|
||||
.api()
|
||||
.user_current_put_subscription(owner, name)
|
||||
.send()?;
|
||||
return print_json(&json!({
|
||||
"subscribed": resp.get("subscribed"),
|
||||
"ignored": resp.get("ignored"),
|
||||
"subscribed": resp.subscribed,
|
||||
"ignored": resp.ignored,
|
||||
}));
|
||||
}
|
||||
// Forgejo returns 404 when the current user is not watching the repo
|
||||
// (rather than a response with subscribed=false).
|
||||
match client.get_json_optional(&format!("/repos/{repo}/subscription"))? {
|
||||
Some(resp) => print_json(&json!({
|
||||
"subscribed": resp.get("subscribed"),
|
||||
"ignored": resp.get("ignored"),
|
||||
match client
|
||||
.api()
|
||||
.user_current_check_subscription(owner, name)
|
||||
.send()
|
||||
{
|
||||
Ok(resp) => print_json(&json!({
|
||||
"subscribed": resp.subscribed,
|
||||
"ignored": resp.ignored,
|
||||
})),
|
||||
None => print_json(&json!({ "subscribed": false, "ignored": false })),
|
||||
Err(e) if is_not_found(&e) => print_json(&json!({ "subscribed": false, "ignored": false })),
|
||||
Err(e) => Err(e.into()),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,9 +18,10 @@
|
|||
|
||||
use anyhow::Result;
|
||||
use clap::Args as ClapArgs;
|
||||
use forgejo_api::structs::IssueGetCommentsAndTimelineQuery;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
use crate::verbs::print_json;
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
|
|
@ -33,11 +34,20 @@ pub struct Args {
|
|||
}
|
||||
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let v = client.get_json(&format!(
|
||||
"/repos/{repo}/issues/{}/timeline?limit={}",
|
||||
args.number, args.limit
|
||||
))?;
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let (_, events) = client
|
||||
.api()
|
||||
.issue_get_comments_and_timeline(
|
||||
owner,
|
||||
name,
|
||||
index(args.number)?,
|
||||
IssueGetCommentsAndTimelineQuery::default(),
|
||||
)
|
||||
.page_size(u32::try_from(args.limit).unwrap_or(u32::MAX))
|
||||
.send()?;
|
||||
// Serialize back to the API's JSON shape so the per-type render
|
||||
// arms (and their tests) keep working on plain `Value`s.
|
||||
let v = serde_json::to_value(events)?;
|
||||
if client.json_mode() {
|
||||
return print_json(&v);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
|
||||
use anyhow::Result;
|
||||
use clap::Args as ClapArgs;
|
||||
use serde_json::Value;
|
||||
use forgejo_api::structs::RepoGetSingleCommitQuery;
|
||||
|
||||
use crate::client::Client;
|
||||
|
||||
|
|
@ -14,25 +14,35 @@ pub struct Args {
|
|||
}
|
||||
|
||||
pub fn run(client: &Client, args: Args) -> Result<()> {
|
||||
let repo = client.repo();
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
// Try branch first; the bash helper silently treats failure as
|
||||
// "not a branch, use the reference as a commit sha directly".
|
||||
let commit_sha = match client.get_json(&format!("/repos/{repo}/branches/{}", args.reference)) {
|
||||
Ok(v) => v
|
||||
.get("commit")
|
||||
.and_then(|c| c.get("id"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or(&args.reference)
|
||||
.to_owned(),
|
||||
let commit_sha = match client
|
||||
.api()
|
||||
.repo_get_branch(owner, name, &args.reference)
|
||||
.send()
|
||||
{
|
||||
Ok(branch) => branch
|
||||
.commit
|
||||
.and_then(|c| c.id)
|
||||
.unwrap_or_else(|| args.reference.clone()),
|
||||
Err(_) => args.reference.clone(),
|
||||
};
|
||||
let commit = client.get_json(&format!("/repos/{repo}/git/commits/{commit_sha}"))?;
|
||||
let commit = client
|
||||
.api()
|
||||
.repo_get_single_commit(
|
||||
owner,
|
||||
name,
|
||||
&commit_sha,
|
||||
RepoGetSingleCommitQuery::default(),
|
||||
)
|
||||
.send()?;
|
||||
let sha = commit
|
||||
.get("tree")
|
||||
.and_then(|t| t.get("sha"))
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| commit.get("sha").and_then(Value::as_str))
|
||||
.unwrap_or("");
|
||||
.commit
|
||||
.and_then(|c| c.tree)
|
||||
.and_then(|t| t.sha)
|
||||
.or(commit.sha)
|
||||
.unwrap_or_default();
|
||||
println!("{sha}");
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,9 +3,9 @@
|
|||
|
||||
use anyhow::Result;
|
||||
use clap::Args as ClapArgs;
|
||||
use serde_json::Value;
|
||||
use forgejo_api::structs::{IssueGetCommentsQuery, StateType};
|
||||
|
||||
use crate::client::Client;
|
||||
use crate::client::{Client, index};
|
||||
use crate::notify;
|
||||
|
||||
#[derive(ClapArgs)]
|
||||
|
|
@ -19,16 +19,24 @@ pub fn run(client: &Client, args: Args) -> Result<()> {
|
|||
// Reading the thread clears its unread notification so the
|
||||
// read-before-comment guard (in `comment`) lets a reply through.
|
||||
notify::mark_read_best_effort(client, repo, args.number);
|
||||
let issue = client.get_json(&format!("/repos/{repo}/issues/{}", args.number))?;
|
||||
let title = issue.get("title").and_then(Value::as_str).unwrap_or("");
|
||||
let body = issue.get("body").and_then(Value::as_str).unwrap_or("");
|
||||
let state = issue.get("state").and_then(Value::as_str).unwrap_or("?");
|
||||
let (owner, name) = client.owner_repo()?;
|
||||
let issue = client
|
||||
.api()
|
||||
.issue_get_issue(owner, name, index(args.number)?)
|
||||
.send()?;
|
||||
let title = issue.title.as_deref().unwrap_or("");
|
||||
let body = issue.body.as_deref().unwrap_or("");
|
||||
let state = match issue.state {
|
||||
Some(StateType::Open) => "open",
|
||||
Some(StateType::Closed) => "closed",
|
||||
None => "?",
|
||||
};
|
||||
let user = issue
|
||||
.get("user")
|
||||
.and_then(|u| u.get("login"))
|
||||
.and_then(Value::as_str)
|
||||
.user
|
||||
.as_ref()
|
||||
.and_then(|u| u.login.as_deref())
|
||||
.unwrap_or("?");
|
||||
let kind = if issue.get("pull_request").is_some_and(|p| !p.is_null()) {
|
||||
let kind = if issue.pull_request.is_some() {
|
||||
"PR"
|
||||
} else {
|
||||
"issue"
|
||||
|
|
@ -39,23 +47,28 @@ pub fn run(client: &Client, args: Args) -> Result<()> {
|
|||
println!();
|
||||
println!("{body}");
|
||||
}
|
||||
let comments = client.get_json(&format!(
|
||||
"/repos/{repo}/issues/{}/comments?limit=50",
|
||||
args.number
|
||||
))?;
|
||||
let arr = comments.as_array().cloned().unwrap_or_default();
|
||||
if !arr.is_empty() {
|
||||
let (_, comments) = client
|
||||
.api()
|
||||
.issue_get_comments(
|
||||
owner,
|
||||
name,
|
||||
index(args.number)?,
|
||||
IssueGetCommentsQuery::default(),
|
||||
)
|
||||
.page_size(50)
|
||||
.send()?;
|
||||
if !comments.is_empty() {
|
||||
println!();
|
||||
println!("---");
|
||||
println!("## Comments ({})", arr.len());
|
||||
println!("## Comments ({})", comments.len());
|
||||
println!();
|
||||
for c in &arr {
|
||||
for c in &comments {
|
||||
let cu = c
|
||||
.get("user")
|
||||
.and_then(|u| u.get("login"))
|
||||
.and_then(Value::as_str)
|
||||
.user
|
||||
.as_ref()
|
||||
.and_then(|u| u.login.as_deref())
|
||||
.unwrap_or("?");
|
||||
let cb = c.get("body").and_then(Value::as_str).unwrap_or("");
|
||||
let cb = c.body.as_deref().unwrap_or("");
|
||||
println!("**{cu}**: {cb}");
|
||||
println!();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
//! Resolve the on-disk path to hyperhive's static assets (branding +
|
||||
//! claude prompts). Single source of truth for both the host daemon
|
||||
//! (`hive-c0re`) and the in-container harness (the `hive` binary) so
|
||||
//! they agree on the lookup contract.
|
||||
//! (`hive-c0re`) and the in-container harness binaries so they agree
|
||||
//! on the lookup contract.
|
||||
//!
|
||||
//! At runtime, the path is read from `$HIVE_ASSETS_DIR`. In nix
|
||||
//! builds that env var is set by the `hive-c0re` / `harness-base` modules
|
||||
|
|
|
|||
|
|
@ -898,12 +898,13 @@ in
|
|||
streamable-http daemon on this loopback port instead of the
|
||||
default per-turn stdio child.
|
||||
|
||||
When null (the default) claude spawns a fresh `hive … mcp` stdio
|
||||
subprocess every turn — the shape that carries the per-turn MCP
|
||||
re-registration race (a resumed turn can emit its first tool call
|
||||
before that turn's async `initialize`/`tools-list` completes,
|
||||
When null (the default) claude spawns a fresh `hive-agent-mcp`
|
||||
stdio subprocess every turn — the shape that carries the per-turn
|
||||
MCP re-registration race (a resumed turn can emit its first tool
|
||||
call before that turn's async `initialize`/`tools-list` completes,
|
||||
stranding the agent with `No such tool`). When set, a long-lived
|
||||
`hive-mcp-http` systemd unit runs `hive mcp --http 127.0.0.1:<port>`
|
||||
`hive-mcp-http` systemd unit runs
|
||||
`hive-agent-mcp --http 127.0.0.1:<port>`
|
||||
and `render_claude_config` points claude at the stable
|
||||
`http://127.0.0.1:<port>/mcp` URL, which survives the per-turn
|
||||
claude re-spawn (and a host-side hive-c0re restart — each tool call
|
||||
|
|
@ -1846,7 +1847,7 @@ in
|
|||
# `render_claude_config`). Long-lived so claude reconnects to the
|
||||
# stable URL each turn instead of respawning + re-registering a stdio
|
||||
# subprocess (the per-turn MCP registration race). It dials the
|
||||
# control socket (`/run/hive/mcp.sock`, the `hive` binary default)
|
||||
# control socket (`/run/hive/mcp.sock`, the harness binaries' default)
|
||||
# fresh on every tool call, so a host-side hive-c0re restart is
|
||||
# transparent. `before = hive-ag3nt` so the URL is already listening
|
||||
# by the time the harness renders the first turn's config; the
|
||||
|
|
@ -1858,7 +1859,7 @@ in
|
|||
before = [ "hive-ag3nt.service" ];
|
||||
environment.RUST_LOG = "info";
|
||||
serviceConfig = {
|
||||
ExecStart = "${pkgs.hyperhive}/bin/hive mcp --http 127.0.0.1:${toString config.hyperhive.mcp.httpPort}";
|
||||
ExecStart = "${pkgs.hyperhive}/bin/hive-agent-mcp --http 127.0.0.1:${toString config.hyperhive.mcp.httpPort}";
|
||||
SyslogIdentifier = "hive-mcp-http";
|
||||
# `always` (not `on-failure`): this endpoint is load-bearing when
|
||||
# `httpPort` is set — a down window is total hyperhive-MCP loss with
|
||||
|
|
@ -1936,7 +1937,7 @@ in
|
|||
# appends /bin to every entry.
|
||||
systemd.services.hive-ag3nt =
|
||||
let
|
||||
binary = "hive";
|
||||
binary = "hive-agent";
|
||||
# OTEL is shipped declaratively via the managed claude settings
|
||||
# json (`environment.etc."claude-code/managed-settings.json"`,
|
||||
# `otelSettingsEnv` in the top-level let) — claude reads it for
|
||||
|
|
@ -1982,7 +1983,7 @@ in
|
|||
HIVE_GUI_VNC_PORT = toString config.hyperhive.gui.vncPort;
|
||||
};
|
||||
serviceConfig = {
|
||||
ExecStart = "${pkgs.hyperhive}/bin/${binary} serve";
|
||||
ExecStart = "${pkgs.hyperhive}/bin/${binary}";
|
||||
# Pin the journal identity to the binary name (otherwise systemd
|
||||
# derives SyslogIdentifier from the ExecStart basename).
|
||||
SyslogIdentifier = binary;
|
||||
|
|
|
|||
Loading…
Reference in a new issue