Files
rhema-claw/integrations/rhema-forge-integration/src/forge.rs
T
kosmos d74b1c40df
android / release (pull_request) Skipped
android / debug (pull_request) Successful in 4m7s
ci / checks (pull_request) Successful in 1m12s
ci / test (pull_request) Successful in 39s
ci / chart (pull_request) Successful in 5s
ci / docker (pull_request) Successful in 1m22s
ci / web (pull_request) Successful in 13s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (pull_request) Skipped
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (pull_request) Skipped
ci / publish-edge-chart (pull_request) Skipped
android / debug (push) Successful in 3m51s
android / release (push) Successful in 2m2s
ci / checks (push) Successful in 59s
ci / test (push) Successful in 37s
ci / chart (push) Successful in 6s
ci / docker (push) Successful in 1m22s
ci / web (push) Successful in 13s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 1m29s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 9s
ci / publish-edge-chart (push) Successful in 4s
feat(claw): answer a thread only when somebody addresses the daemon
A repo watch saw *every* issue, pull request, review and comment on the
repository, and the handler treated each dispatch as work to do: a
snapshot fetch, a coding-agent turn, and a comment posted back. On a
repository with any traffic at all that is the wrong end of the
question — watching a repo is not volunteering to answer it — and it is
also how a daemon ends up talking to itself, since its own replies are
news too.

The dispatch now starts with a mention gate. A thread runs when:

- it delivered a triaged notification — assigned, review requested,
  @-mentioned: the notifications feed already adjudicated that one; or
- one of its plain events names the handle the daemon speaks as
  (`@kosmos`), written by anybody *but* the daemon.

Everything else is drained and dropped: no snapshot, no model call, no
comment. The outcome is `Superseded` — RSD's vocabulary has no "nothing
was asked", and the closest is that the work the event names is not
this daemon's.

Recognizing its own name took a little plumbing. The credential a watch
resolves carries a login only when an account identity supplied the
token; a token pasted into a watch row, or a forge environment variable,
names nobody — and that is the deployment the gate must not go inert on.
So `Forge::viewer_login` is the backend's own answer to "who am I", from
its `/user` (Gitea and GitHub spell it `login`, GitLab `username`), with
a `None` default for backends that cannot say; the handler asks at most
once per credential and keeps the answer beside the cached client. A
forge that will not name the credential leaves the gate *open*, with a
warning in the log: a filter that silently mutes a watch is worse than
one that occasionally over-answers.

The actor check is load-bearing for the same reason the gate exists: a
reply quotes the mention it answers, so "addressed by name" alone would
have the daemon answer itself, forever.

Tests: unit tests for the gate (name in any case, own comment, no body,
notification, unnamed credential), one end-to-end test per behaviour —
a mention runs one turn and posts one reply; a thread's own chatter runs
nothing and posts nothing; the daemon's own reply does not reopen the
gate — plus `viewer_login` against all three backends.
2026-11-17 22:41:46 +01:00

180 lines
6.9 KiB
Rust

//! The forge client contract: one trait, three calls.
//!
//! [`Forge`] is the whole surface a consumer needs: poll a repo's
//! activity against a cursor, post a comment, and fetch a thread
//! snapshot so an answering handler can orient without a second API
//! round-trip. Implementations are cheap to clone and share — the
//! reqwest client inside is reference-counted — and object-safe so a
//! backend can be swapped without generics.
//!
//! Polls are at-least-once. The forges' `since`-style filters match rows
//! at-or-after the cursor, so boundary rows repeat across polls, and a
//! row that changes between a backend's feeds can surface twice under
//! different ids. Both are harmless under the RSD dedup: consumers must
//! treat the event `id` as the only dedup key, never `(repo, number)`.
use async_trait::async_trait;
use crate::error::ForgeError;
use crate::event::{ForgeEvent, ForgeThreadKind, NotificationPage, RepoRef, Snapshot, Timestamp};
/// One poll's worth of activity, with the cursor to continue from.
#[derive(Debug, Clone, PartialEq)]
pub struct ForgePage {
/// The events, oldest first, ties broken by id — a deterministic
/// order regardless of which feed produced an event.
pub events: Vec<ForgeEvent>,
/// The cursor for the next poll: the newest event time seen, never
/// earlier than the poll's `since`. `None` only when the poll had no
/// anchor and came back empty — the repo is simply quiet.
pub cursor: Option<Timestamp>,
}
impl ForgePage {
/// Folds collected events into a page: sorts them and advances the
/// cursor past everything seen.
pub(crate) fn finish(mut events: Vec<ForgeEvent>, since: Option<&Timestamp>) -> Self {
events.sort_by(|a, b| (&a.timestamp, &a.id).cmp(&(&b.timestamp, &b.id)));
let mut cursor = since.cloned();
for timestamp in events.iter().map(|event| &event.timestamp) {
cursor = Some(match cursor {
Some(current) if current >= *timestamp => current,
_ => timestamp.clone(),
});
}
Self { events, cursor }
}
}
/// A forge backend: the client for one REST dialect.
#[async_trait]
pub trait Forge: Send + Sync {
/// Recent activity for `repo`, oldest first, all pages collected.
///
/// `since` anchors the poll: `None` lists from the beginning (a first
/// poll); `Some(cursor)` asks for rows at-or-after the cursor, whose
/// boundary rows may repeat — their stable ids make the repetition
/// dedupable downstream, never duplicated work.
async fn poll(
&self,
repo: &RepoRef,
since: Option<&Timestamp>,
) -> Result<ForgePage, ForgeError>;
/// Posts `body` as a new comment on the thread `kind` + `number`
/// name.
///
/// On GitLab the kind picks the sequence the iid is read against:
/// issues and merge requests are numbered independently, and only
/// the named one is addressed — a miss surfaces as a 404, never a
/// silent post to the other sequence. GitHub and Gitea share one
/// number space across issues and pull requests (every pull request
/// is an issue there), so they accept the kind for signature
/// uniformity and either value addresses the same thread.
async fn comment(
&self,
repo: &RepoRef,
kind: ForgeThreadKind,
number: u64,
body: &str,
) -> Result<(), ForgeError>;
/// The thread's current state, so a handler can orient without a
/// second API round-trip. `kind` selects the sequence `number` is
/// read against, under the same rules as [`Forge::comment`].
async fn snapshot(
&self,
repo: &RepoRef,
kind: ForgeThreadKind,
number: u64,
) -> Result<Snapshot, ForgeError>;
/// The account's notification feed: everything addressed to the
/// account this client authenticates as, across every repository it
/// can see — the account-scoped counterpart of [`Forge::poll`],
/// whose feeds are repo-scoped. `since` anchors the poll with the
/// same at-least-once semantics as `poll`: boundary rows repeat, and
/// the stable ids make the repetition dedupable downstream.
async fn notifications(
&self,
since: Option<&Timestamp>,
) -> Result<NotificationPage, ForgeError>;
/// The login this client authenticates as — the backend's own answer
/// to "who am I".
///
/// A consumer that must recognize its own handle (to see an @-mention
/// in a body, and to ignore its own replies) cannot always read it off
/// its credential: a token pasted into a watch row, or an environment
/// variable, names nobody. `None` is the honest default — a backend
/// with no such route simply cannot say who it is — and a backend that
/// can say answers with its `/user` row.
async fn viewer_login(&self) -> Result<Option<String>, ForgeError> {
Ok(None)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::event::EventKind;
use serde_json::json;
fn event(id: &str, at: &str) -> ForgeEvent {
ForgeEvent {
id: id.to_owned(),
kind: EventKind::Comment,
repo: RepoRef::new("acme", "widgets"),
number: 7,
is_pr: false,
actor: None,
body: None,
url: None,
timestamp: Timestamp::parse(at).expect("timestamp parses"),
raw: json!({}),
}
}
#[test]
fn events_sort_oldest_first_with_id_ties() {
let page = ForgePage::finish(
vec![
event("b", "2026-10-08T00:00:00Z"),
event("z", "2026-10-07T00:00:00Z"),
event("a", "2026-10-08T00:00:00Z"),
],
None,
);
let ids: Vec<&str> = page.events.iter().map(|event| event.id.as_str()).collect();
assert_eq!(ids, ["z", "a", "b"]);
}
#[test]
fn the_cursor_never_goes_backwards() {
// A since newer than everything seen holds: the next poll repeats
// the boundary instead of re-listing old history.
let since = Timestamp::parse("2026-10-09T00:00:00Z").expect("parses");
let page = ForgePage::finish(vec![event("a", "2026-10-08T00:00:00Z")], Some(&since));
assert_eq!(page.cursor, Some(since));
let page = ForgePage::finish(
vec![event("a", "2026-10-10T00:00:00Z")],
Some(&Timestamp::parse("2026-10-09T00:00:00Z").expect("parses")),
);
assert_eq!(
page.cursor,
Some(Timestamp::parse("2026-10-10T00:00:00Z").expect("parses"))
);
}
#[test]
fn empty_pages_keep_or_drop_the_cursor_depending_on_the_anchor() {
let since = Timestamp::parse("2026-10-09T00:00:00Z").expect("parses");
let page = ForgePage::finish(vec![], Some(&since));
assert_eq!(page.cursor, Some(since));
let page = ForgePage::finish(vec![], None);
assert_eq!(page.cursor, None);
}
}