Compare commits

...
1 Commits
Author SHA1 Message Date
kosmos 139a887c24 feat(claw): answer a thread only when somebody addresses the daemon
android / release (pull_request) Skipped
android / debug (pull_request) Successful in 2m12s
ci / checks (pull_request) Failing after 23s
ci / test (pull_request) Failing after 30s
ci / chart (pull_request) Successful in 5s
ci / docker (pull_request) Successful in 1m21s
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
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-14 13:32:50 +00:00
10 changed files with 522 additions and 5 deletions

No files matched your search

+15 -1
View File
@@ -244,7 +244,21 @@ tool wakes with the account id, never the secret, and a denial or a
15-minute silence comes back in-band so the turn can say so and move 15-minute silence comes back in-band so the turn can say so and move
on. A watch with no token of its own polls — and replies — as the on. A watch with no token of its own polls — and replies — as the
matching saved account: the same forge, and on a self-hosted forge the matching saved account: the same forge, and on a self-hosted forge the
same base URL. Acting with a stored account is `identity_exec`: it runs one shell same base URL.
A repo watch is a feed, not an invitation. The daemon answers a thread
when somebody there addresses it — a comment whose body names the handle
its credential speaks as (`@kosmos`), written by anyone but itself — and
otherwise drains the news and runs nothing: no snapshot, no turn, no
comment on somebody else's conversation. (Its own replies quote the
mention they answer, so they never reopen the gate.) Notifications are
the other door and are adjudicated before they arrive — assigned, review
requested, @-mentioned — so those always run. The handle is the account
identity's when the token has one, and the forge's own `/user` answer
when it does not; a credential the forge will not name leaves the gate
open, with a warning in the log, rather than silently muting a watch.
Acting with a stored account is `identity_exec`: it runs one shell
command in the session workspace with the secret injected — command in the session workspace with the secret injected —
`ACCOUNT_SECRET` plus the service's own `GITHUB_TOKEN`/`GITEA_TOKEN`/ `ACCOUNT_SECRET` plus the service's own `GITHUB_TOKEN`/`GITEA_TOKEN`/
`GITLAB_TOKEN`, and a git credential helper — so `git clone` and API `GITLAB_TOKEN`, and a git credential helper — so `git clone` and API
+203 -4
View File
@@ -37,6 +37,7 @@ use rhema_forge_integration::{
}; };
use rhema_identity::IdentityStore; use rhema_identity::IdentityStore;
use rhema_rsd::{InboxItem, Outcome, ResourceKey}; use rhema_rsd::{InboxItem, Outcome, ResourceKey};
use tokio::sync::OnceCell;
use crate::backends::BackendRegistry; use crate::backends::BackendRegistry;
@@ -70,7 +71,7 @@ pub struct ClawHandler {
/// agent shell: the daemon URL, the scoped agent token, the tools' /// agent shell: the daemon URL, the scoped agent token, the tools'
/// bin dir on PATH. Empty when the config issues no agent token. /// bin dir on PATH. Empty when the config issues no agent token.
tool_env: std::collections::BTreeMap<String, String>, tool_env: std::collections::BTreeMap<String, String>,
clients: Mutex<HashMap<String, Arc<dyn Forge>>>, clients: Mutex<HashMap<String, Arc<WatchClient>>>,
} }
impl ClawHandler { impl ClawHandler {
@@ -120,6 +121,18 @@ impl ClawHandler {
key: &ResourceKey, key: &ResourceKey,
as_account: Option<&str>, as_account: Option<&str>,
) -> Result<Arc<dyn Forge>, String> { ) -> Result<Arc<dyn Forge>, String> {
Ok(self.watch_client(key, as_account)?.forge.clone())
}
/// [`Self::watch_forge_as`] with the handle the credential speaks as
/// kept beside the client: the mention gate needs to recognize its own
/// name, and asking the forge is a request worth spending once per
/// credential, not once per dispatch.
fn watch_client(
&self,
key: &ResourceKey,
as_account: Option<&str>,
) -> Result<Arc<WatchClient>, String> {
let watch = watch_key(key) let watch = watch_key(key)
.ok_or_else(|| format!("resource key {key} is not a forge thread key"))?; .ok_or_else(|| format!("resource key {key} is not a forge thread key"))?;
let (forge, repo) = watch let (forge, repo) = watch
@@ -192,7 +205,7 @@ impl ClawHandler {
kind: ForgeKind, kind: ForgeKind,
host: Option<&str>, host: Option<&str>,
credential: &WatchCredential, credential: &WatchCredential,
) -> Arc<dyn Forge> { ) -> Arc<WatchClient> {
// Everything that changes the client: the kind, its host, and the // Everything that changes the client: the kind, its host, and the
// credential — the login included, since one value sent two ways // credential — the login included, since one value sent two ways
// is two credentials. // is two credentials.
@@ -206,7 +219,10 @@ impl ClawHandler {
let mut clients = self.clients.lock().unwrap_or_else(PoisonError::into_inner); let mut clients = self.clients.lock().unwrap_or_else(PoisonError::into_inner);
clients clients
.entry(cache_key) .entry(cache_key)
.or_insert_with(|| record_client(kind, host, credential)) .or_insert_with(|| {
let forge = record_client(kind, host, credential);
Arc::new(WatchClient::new(forge, credential.login.clone()))
})
.clone() .clone()
} }
@@ -224,7 +240,22 @@ impl ClawHandler {
// that account — a thread the account's feed delivered may have no // that account — a thread the account's feed delivered may have no
// repo watch row at all. // repo watch row at all.
let news = self.drain_news(ctx, &key).await?; let news = self.drain_news(ctx, &key).await?;
let forge = self.watch_forge_as(&ctx.key, delivery_account(&news))?; let client = self.watch_client(&ctx.key, delivery_account(&news))?;
// The mention gate, before anything is fetched or run: the news is
// already drained, and this decides whether it asks anything of
// the daemon at all.
let handle = client.handle().await;
if handle.is_none() && news.iter().any(|item| matches!(item, InboxNews::Event(_))) {
eprintln!(
"[claw] warning: {key}: the forge would not name this credential; \
every event on the watch dispatches"
);
}
if !addressed(&news, handle.as_deref()) {
return Ok(Outcome::Superseded);
}
let forge = client.forge.clone();
let snapshot = forge let snapshot = forge
.snapshot(&repo, thread_kind, number) .snapshot(&repo, thread_kind, number)
@@ -343,6 +374,45 @@ impl ClawHandler {
} }
} }
/// One cached forge client, with the handle it speaks as.
///
/// The credential a watch resolves carries a login only when an account
/// identity supplied the token; a token pasted into the watch row, or a
/// forge environment variable, names nobody. The mention gate still has to
/// recognize the daemon's own name — to see an @-mention in a body, and to
/// leave its own replies alone — so the forge is asked who it is, once per
/// credential, the first time a dispatch needs to know.
struct WatchClient {
forge: Arc<dyn Forge>,
/// The login the credential itself carries.
login: Option<String>,
/// The forge's own answer, asked at most once.
viewer: OnceCell<Option<String>>,
}
impl WatchClient {
fn new(forge: Arc<dyn Forge>, login: Option<String>) -> Self {
Self {
forge,
login,
viewer: OnceCell::new(),
}
}
/// The handle this client speaks as: the credential's when it has one,
/// else the forge's own answer. `None` when neither can name it — a
/// forge that is down, or a backend with no `/user`.
async fn handle(&self) -> Option<String> {
if let Some(login) = &self.login {
return Some(login.clone());
}
self.viewer
.get_or_init(|| async { self.forge.viewer_login().await.ok().flatten() })
.await
.clone()
}
}
#[async_trait] #[async_trait]
impl Handler for ClawHandler { impl Handler for ClawHandler {
async fn handle(&self, ctx: &mut SessionContext) -> Outcome { async fn handle(&self, ctx: &mut SessionContext) -> Outcome {
@@ -440,6 +510,60 @@ fn delivery_account(news: &[InboxNews]) -> Option<&str> {
}) })
} }
/// Whether `news` asks anything of the daemon — the mention gate.
///
/// A triaged notification answered this question on the way in: the
/// notifications feed handed the row over because it was assigned, a
/// review was requested, or someone @-mentioned the account, and
/// [`triage`](rhema_forge_integration::triage) let it through. It always
/// runs.
///
/// A plain repo event has been through nothing: a repo watch sees every
/// issue, pull request, review and comment on the repository. Running a
/// turn for each of them would burn a model call per comment and post an
/// unasked-for reply on threads nobody addressed the daemon in — the
/// difference between watching a repository and answering it. So a plain
/// event runs only when it addresses the daemon: a body that names the
/// handle we speak as, written by somebody else.
///
/// With no handle to look for, nothing is gated: a filter that silently
/// turns a watch off is worse than one that occasionally over-answers, and
/// the dispatch says so in the log.
fn addressed(news: &[InboxNews], handle: Option<&str>) -> bool {
if news
.iter()
.any(|news| matches!(news, InboxNews::Notified { .. }))
{
return true;
}
let Some(handle) = handle else {
return true;
};
news.iter().any(|news| match news {
InboxNews::Notified { .. } => true,
InboxNews::Event(event) => mentions(event, handle),
})
}
/// Whether `event` addresses `handle`: its body names `@handle`, and the
/// event is not the daemon's own writing. Our replies quote the mentions
/// they answer, so an event written by the handle counts as addressed by
/// nobody — otherwise every answer would feed the next turn.
fn mentions(event: &ForgeEvent, handle: &str) -> bool {
let own = event
.actor
.as_deref()
.is_some_and(|actor| actor.eq_ignore_ascii_case(handle));
if own {
return false;
}
let Some(body) = event.body.as_deref() else {
return false;
};
let needle = format!("@{}", handle.to_lowercase());
body.to_lowercase().contains(needle.as_str())
}
/// The batch's dominant role, for the prompt's persona framing: /// The batch's dominant role, for the prompt's persona framing:
/// implementing subsumes reviewing — a batch that asks for both is a /// implementing subsumes reviewing — a batch that asks for both is a
/// dispatch where the work is the point. Plain events imply no persona: /// dispatch where the work is the point. Plain events imply no persona:
@@ -712,6 +836,81 @@ mod tests {
); );
} }
/// A plain comment that names nobody is the thread's own traffic: the
/// gate stays shut, no turn runs, and nothing is posted.
#[test]
fn a_comment_that_names_nobody_does_not_address_the_daemon() {
let news = [InboxNews::Event(event(
EventKind::Comment,
"dave",
Some("any progress on this?"),
))];
assert!(!addressed(&news, Some("kosmos")));
}
/// Addressed by name, in any case, anywhere in the body — the point of
/// the feature is that the human types a sentence, not a protocol.
#[test]
fn a_comment_that_names_the_handle_addresses_it() {
for body in [
"hey @kosmos can you take a look?",
"@Kosmos, this one is yours",
"I think @kosmos should decide",
] {
let news = [InboxNews::Event(event(EventKind::Comment, "dave", Some(body)))];
assert!(addressed(&news, Some("kosmos")), "body: {body}");
}
}
/// Our own replies quote the mention they answer, so they mention the
/// handle on every line — and must never feed the next turn.
#[test]
fn the_daemons_own_comments_never_address_it() {
let news = [InboxNews::Event(event(
EventKind::Comment,
"kosmos",
Some("> @kosmos can you take a look?\n\nDone, see the branch."),
))];
assert!(!addressed(&news, Some("kosmos")));
// Case is the forge's, not the body's: the actor check folds it.
let news = [InboxNews::Event(event(EventKind::Comment, "Kosmos", Some("@kosmos on it")))];
assert!(!addressed(&news, Some("kosmos")));
}
/// Thread-level events carry no body, so a mention gate can never pass
/// them: an opened or closed issue is context, not a request.
#[test]
fn an_event_with_no_body_is_not_a_request() {
let news = [InboxNews::Event(event(EventKind::Closed, "dave", None))];
assert!(!addressed(&news, Some("kosmos")));
}
/// A triaged notification was adjudicated on the way in — assigned, a
/// review requested, or a mention — so it runs regardless of bodies.
#[test]
fn a_triaged_notification_always_addresses_the_daemon() {
let notified = decode_news(&triaged_item(
Role::Implementer,
NotificationReason::Assigned,
))
.expect("the triaged payload decodes");
let news = [notified];
assert!(addressed(&news, Some("kosmos")));
assert!(addressed(&news, None), "a notification needs no handle");
}
/// With no handle to look for, the gate stays open: silently turning a
/// watch off is worse than over-answering, and the dispatch logs it.
#[test]
fn an_unnamed_credential_gates_nothing() {
let news = [InboxNews::Event(event(
EventKind::Comment,
"dave",
Some("any progress?"),
))];
assert!(addressed(&news, None));
}
#[test] #[test]
fn thread_level_events_carry_no_body_and_the_prompt_says_so() { fn thread_level_events_carry_no_body_and_the_prompt_says_so() {
let prompt = build_prompt( let prompt = build_prompt(
+215
View File
@@ -0,0 +1,215 @@
//! The mention gate, end to end: a comment that names the daemon runs a
//! turn and posts a reply; a comment that names nobody is drained and
//! ignored — no snapshot, no model call, no comment. Zero network.
use std::sync::Arc;
use rhema_claw::{ClawConfig, run_once};
use rhema_core::{Message, MockProvider, ModelOutput, Role, StopReason, Usage};
use rhema_rsd::Outcome;
use serde_json::{Value, json};
use wiremock::matchers::{body_partial_json, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
/// The one issue the tests watch, updated inside the seeded cursor's
/// window so the pass sees it as news alongside the comment.
fn issue_row() -> Value {
json!({
"id": 1007,
"number": 7,
"state": "open",
"title": "crash on save",
"user": { "login": "alice" },
"labels": [],
"body": "steps to reproduce…",
"created_at": "2026-10-01T09:00:00Z",
"updated_at": "2026-10-02T10:00:00Z",
"closed_at": null,
"html_url": "https://github.com/acme/widgets/issues/7"
})
}
/// A comment on thread 7: the author and the body are the test's subject.
fn comment_row(author: &str, body: &str) -> Value {
json!({
"id": 8001,
"user": { "login": author },
"body": body,
"created_at": "2026-10-03T09:00:00Z",
"updated_at": "2026-10-03T09:00:00Z",
"issue_url": "https://api.github.com/repos/acme/widgets/issues/7",
"html_url": "https://github.com/acme/widgets/issues/7#issuecomment-8001"
})
}
fn reply(text: &str) -> ModelOutput {
ModelOutput {
message: Message::text(Role::Assistant, text),
stop_reason: StopReason::EndTurn,
usage: Usage::default(),
}
}
fn config(dir: &tempfile::TempDir) -> ClawConfig {
ClawConfig {
db: Some(dir.path().join("dispatch.db")),
workspace_root: Some(dir.path().join("workspaces")),
memory_root: None,
bootstrap_root: None,
poll_interval_secs: 60,
max_turn_steps: rhema_claw::config::DEFAULT_MAX_TURN_STEPS,
provider: Some("google".to_owned()),
model: Some("test-model".to_owned()),
listen: None,
token: None,
agent_token: None,
tools_bin: None,
transcript: None,
ingest_token: None,
disabled_mcp_servers: std::collections::BTreeSet::new(),
}
}
/// An established watch: the cursor is what makes the pass read the feed
/// as news rather than seeding a start line at *now*.
fn seed_watch(dir: &tempfile::TempDir, host: &str) {
let store = rhema_claw::ClawStore::open(dir.path().join("dispatch.db"))
.expect("the watch table opens");
store
.add("github", "acme/widgets", Some(host), "tok")
.expect("the seed row lands");
store
.set_cursor(rhema_claw::SCOPE_REPO, "github", "acme/widgets", "2026-10-01T00:00:00Z")
.expect("the cursor seeds");
}
/// The feeds every pass reads, plus the forge's answer to "who am I" —
/// the watch's token is a bare value that names nobody, so the mention
/// gate asks the forge rather than guess.
async fn mount_repo(server: &MockServer, author: &str, comment: &str) {
Mock::given(method("GET"))
.and(path("/repos/acme/widgets/issues"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!([issue_row()])))
.mount(server)
.await;
Mock::given(method("GET"))
.and(path("/repos/acme/widgets/issues/comments"))
.respond_with(
ResponseTemplate::new(200).set_body_json(json!([comment_row(author, comment)])),
)
.mount(server)
.await;
Mock::given(method("GET"))
.and(path("/user"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({ "login": "kosmos" })))
.mount(server)
.await;
}
/// The orientation call the turn makes once the gate has opened.
async fn mount_snapshot(server: &MockServer) {
Mock::given(method("GET"))
.and(path("/repos/acme/widgets/issues/7"))
.respond_with(ResponseTemplate::new(200).set_body_json(issue_row()))
.mount(server)
.await;
}
/// The headline case: "hey @kosmos, can you take a look at this?" — one
/// comment addressed by name, one turn, one reply.
#[tokio::test]
async fn a_comment_that_names_the_daemon_runs_a_turn() {
let server = MockServer::start().await;
mount_repo(&server, "dave", "hey @kosmos can you take a look at this?").await;
mount_snapshot(&server).await;
let posted = Mock::given(method("POST"))
.and(path("/repos/acme/widgets/issues/7/comments"))
.and(body_partial_json(json!({ "body": "on it" })))
.respond_with(ResponseTemplate::new(201).set_body_json(json!({ "id": 43 })))
.expect(1)
.mount_as_scoped(&server)
.await;
let dir = tempfile::tempdir().expect("tempdir");
seed_watch(&dir, &server.uri());
let report = run_once(
&config(&dir),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
)
.await
.expect("the pass runs");
assert_eq!(report.outcomes, vec![Outcome::Handled]);
drop(posted);
}
/// The gate's whole point: somebody else's conversation on a watched
/// repository is context, not a request. The news is drained and dropped
/// — and the snapshot is deliberately not mocked, so a dispatch that got
/// past the gate would fail loudly instead of posting quietly.
#[tokio::test]
async fn a_comment_that_names_nobody_runs_nothing() {
let server = MockServer::start().await;
mount_repo(&server, "dave", "any progress on this?").await;
let posted = Mock::given(method("POST"))
.and(path("/repos/acme/widgets/issues/7/comments"))
.respond_with(ResponseTemplate::new(201).set_body_json(json!({ "id": 43 })))
.expect(0)
.mount_as_scoped(&server)
.await;
let dir = tempfile::tempdir().expect("tempdir");
seed_watch(&dir, &server.uri());
let report = run_once(
&config(&dir),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
)
.await
.expect("the pass runs");
assert_eq!(
report.outcomes,
vec![Outcome::Superseded],
"nothing was asked, and nothing ran"
);
drop(posted);
}
/// Our own replies are news too — and they quote the mention they answer.
/// Without the actor check, every answer would open the gate for the next
/// turn: the daemon talking to itself, forever.
#[tokio::test]
async fn the_daemons_own_reply_does_not_reopen_the_gate() {
let server = MockServer::start().await;
// Written by the daemon itself, quoting the mention it answers.
mount_repo(
&server,
"kosmos",
"> hey @kosmos can you take a look?\n\nDone — branch pushed.",
)
.await;
let dir = tempfile::tempdir().expect("tempdir");
seed_watch(&dir, &server.uri());
let report = run_once(
&config(&dir),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
)
.await
.expect("the pass runs");
assert_eq!(
report.outcomes,
vec![Outcome::Superseded],
"the daemon answered itself"
);
}
/// A registry whose only backend is the scripted mock — the shape every
/// integration test runs on.
fn mock_registry(provider: Arc<dyn rhema_core::ModelProvider>) -> Arc<rhema_claw::BackendRegistry> {
Arc::new(
rhema_claw::BackendRegistry::new(
vec![rhema_claw::Backend::headless("mock", provider)],
None,
)
.expect("a single mock backend always constructs"),
)
}
@@ -99,6 +99,19 @@ pub trait Forge: Send + Sync {
&self, &self,
since: Option<&Timestamp>, since: Option<&Timestamp>,
) -> Result<NotificationPage, ForgeError>; ) -> 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)] #[cfg(test)]
@@ -690,6 +690,11 @@ impl Forge for GiteaForge {
Ok(()) Ok(())
} }
async fn viewer_login(&self) -> Result<Option<String>, ForgeError> {
let user: WireUser = decode(self.send(self.get("/user")).await?).await?;
Ok(user.login.filter(|login| !login.trim().is_empty()))
}
async fn snapshot( async fn snapshot(
&self, &self,
repo: &RepoRef, repo: &RepoRef,
@@ -646,6 +646,16 @@ impl Forge for GitHubForge {
Ok(()) Ok(())
} }
async fn viewer_login(&self) -> Result<Option<String>, ForgeError> {
let response = self
.get("/user")
.send()
.await
.map_err(ForgeError::network)?;
let user: WireUser = decode(response).await?;
Ok(user.login.filter(|login| !login.trim().is_empty()))
}
async fn snapshot( async fn snapshot(
&self, &self,
repo: &RepoRef, repo: &RepoRef,
@@ -523,6 +523,18 @@ impl Forge for GitLabForge {
Ok(()) Ok(())
} }
async fn viewer_login(&self) -> Result<Option<String>, ForgeError> {
// GitLab spells the login `username`, like every author object it
// sends.
let response = self
.get("/user")
.send()
.await
.map_err(ForgeError::network)?;
let user: WireAuthor = decode(response).await?;
Ok(user.username.filter(|login| !login.trim().is_empty()))
}
async fn snapshot( async fn snapshot(
&self, &self,
repo: &RepoRef, repo: &RepoRef,
@@ -557,3 +557,19 @@ async fn notifications_poll_maps_the_subject_feed() {
assert_eq!(note.repo, RepoRef::new("acme", "widgets")); assert_eq!(note.repo, RepoRef::new("acme", "widgets"));
assert_eq!(note.title.as_deref(), Some("Fix the gate")); assert_eq!(note.title.as_deref(), Some("Fix the gate"));
} }
/// The mention gate asks the forge who the credential is, because a token
/// read from a watch row names nobody.
#[tokio::test]
async fn the_viewer_login_is_the_instances_own_answer() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/v1/user"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({ "login": "kosmos" })))
.mount(&server)
.await;
assert_eq!(
forge(&server).viewer_login().await.expect("the call lands"),
Some("kosmos".to_owned())
);
}
@@ -532,3 +532,19 @@ async fn notifications_without_a_cursor_still_return_the_newest_seen() {
Some(Timestamp::parse("2026-10-02T00:00:00Z").expect("parses")) Some(Timestamp::parse("2026-10-02T00:00:00Z").expect("parses"))
); );
} }
/// The mention gate asks the forge who the credential is, because a token
/// read from a watch row names nobody.
#[tokio::test]
async fn the_viewer_login_is_the_instances_own_answer() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/user"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({ "login": "kosmos-ai-bot" })))
.mount(&server)
.await;
assert_eq!(
forge(&server).viewer_login().await.expect("the call lands"),
Some("kosmos-ai-bot".to_owned())
);
}
@@ -572,3 +572,20 @@ async fn todos_poll_maps_actions_targets_and_projects() {
Some("https://gitlab.com/acme/widgets/-/merge_requests/12") Some("https://gitlab.com/acme/widgets/-/merge_requests/12")
); );
} }
/// The mention gate asks the forge who the credential is, because a token
/// read from a watch row names nobody. GitLab spells the login
/// `username`.
#[tokio::test]
async fn the_viewer_login_is_the_instances_own_answer() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/api/v4/user"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({ "username": "kosmos" })))
.mount(&server)
.await;
assert_eq!(
forge(&server).viewer_login().await.expect("the call lands"),
Some("kosmos".to_owned())
);
}