diff --git a/crates/rhema-claw/src/forge.rs b/crates/rhema-claw/src/forge.rs index 679752f..520eee6 100644 --- a/crates/rhema-claw/src/forge.rs +++ b/crates/rhema-claw/src/forge.rs @@ -26,7 +26,8 @@ use rhema_autonomous_agent::{Source, SourceError, async_trait}; use rhema_forge_integration::forge_key_fn; use rhema_forge_integration::triage::{self, Triage}; use rhema_forge_integration::{ - Forge, GitHubForge, GitLabForge, GiteaForge, Notification, Watcher, register_forge, + Forge, GitHubForge, GitLabForge, GiteaForge, Notification, RepoRef, Timestamp, Watcher, + register_forge, }; use rhema_identity::{IdentityStore, SecretKind}; use rhema_rsd::{Clock, Dispatcher, Event, KeyFn, SystemClock}; @@ -315,7 +316,14 @@ impl Source for ForgeSource { } }; let client = self.client_for(&record); - let polled = self.watcher.poll(client.as_ref(), &repo).await; + let since = self.cursor_for(&record)?; + let polled = self + .watcher + .poll_since(client.as_ref(), &repo, Some(&since)) + .await; + if polled.is_ok() { + self.persist_cursor(&record, &repo)?; + } // Health first, whatever the outcome: a watch that has been // failing since it was created must be able to say so. self.record_poll( @@ -366,6 +374,44 @@ impl Source for ForgeSource { } impl ForgeSource { + /// The cursor one repo watch polls from: the durable one when it has + /// one, and otherwise a seed at *now*, written before the poll so a + /// forge that is down cannot walk the start line forward on every pass + /// and lose the news arriving in between. + /// + /// A watch reports news, and a repository's history is not news. + /// Replaying it meant one dispatch per old thread — and, from the + /// handler, one comment posted on each. An unreadable cursor reads as + /// absent: a corrupted row must not fire a backlog either. + fn cursor_for(&self, record: &WatchRecord) -> Result { + let stored = self + .store + .cursor(SCOPE_REPO, &record.forge, &record.repo) + .map_err(|err| SourceError::Backend(format!("watch store: {err}")))?; + if let Some(since) = stored.as_deref().and_then(Timestamp::parse) { + return Ok(since); + } + let now = Timestamp::from_epoch_millis(SystemClock.now_millis() as i64) + .ok_or_else(|| SourceError::Backend("cannot spell this instant".to_owned()))?; + self.store + .set_cursor(SCOPE_REPO, &record.forge, &record.repo, now.raw()) + .map_err(|err| SourceError::Backend(format!("watch store: {err}")))?; + Ok(now) + } + + /// Advances a watch's durable cursor to wherever the poll got to. The + /// watcher's own map is per-process: a restart that lost it replayed + /// the repository's history, the backlog [`Self::cursor_for`] exists to + /// keep out. + fn persist_cursor(&self, record: &WatchRecord, repo: &RepoRef) -> Result<(), SourceError> { + let Some(cursor) = self.watcher.cursor(repo) else { + return Ok(()); + }; + self.store + .set_cursor(SCOPE_REPO, &record.forge, &record.repo, cursor.raw()) + .map_err(|err| SourceError::Backend(format!("watch store: {err}"))) + } + /// Records one poll's outcome, and says something the first time a /// streak begins: a watch refused on every tick looks exactly like a /// quiet repository from the outside, and only the failing tick knows @@ -547,6 +593,83 @@ fn surface_body(notification: &Notification) -> String { #[cfg(test)] mod tests { use super::*; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + /// A watch installed on a repository full of history must not replay + /// it: the first pass seeds its cursor to *now* and feeds nothing, and + /// the poll that follows asks from that instant rather than from the + /// beginning. Every replayed event used to be a dispatch, and every + /// dispatch a comment posted on a thread nobody had just touched. + #[tokio::test] + async fn a_new_watch_starts_now_instead_of_replaying_history() { + let server = MockServer::start().await; + for endpoint in [ + "/api/v1/repos/acme/barn/issues", + "/api/v1/repos/acme/barn/pulls", + "/api/v1/repos/acme/barn/issues/comments", + ] { + Mock::given(method("GET")) + .and(path(endpoint)) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([]))) + .mount(&server) + .await; + } + let store = Arc::new(ClawStore::in_memory().expect("store opens")); + store + .add("gitea", "acme/barn", Some(&server.uri()), "tok") + .expect("add"); + let (dispatcher, accounts, notifications) = test_parts(store.clone()); + let source = ForgeSource::new(&dispatcher, "gitea", store.clone(), accounts, notifications); + + assert_eq!( + source.detect().await.expect("the pass runs"), + 0, + "a watch's first pass feeds no history" + ); + let cursor = store + .cursor(SCOPE_REPO, "gitea", "acme/barn") + .expect("cursor reads") + .expect("the first pass seeded a cursor"); + assert!( + Timestamp::parse(&cursor).is_some(), + "the seed is spelled like a forge instant: {cursor}" + ); + + // The poll asked from the seed: one request per feed, each + // `since`-filtered where the feed takes one. + let requests = server.received_requests().await.expect("recording is on"); + let issue_polls: Vec<_> = requests + .iter() + .filter(|request| request.url.path() == "/api/v1/repos/acme/barn/issues") + .collect(); + assert_eq!(issue_polls.len(), 1, "one issues poll"); + let since = issue_polls[0].url.query_pairs().find_map(|(key, value)| { + if key.as_ref() == "since" { + Some(value.into_owned()) + } else { + None + } + }); + assert_eq!(since.as_deref(), Some(cursor.as_str())); + + // A second pass resumes from the same place, not from history. + assert_eq!(source.detect().await.expect("the second pass runs"), 0); + assert_eq!( + store + .cursor(SCOPE_REPO, "gitea", "acme/barn") + .expect("cursor reads"), + Some(cursor) + ); + assert_eq!( + store + .health(SCOPE_REPO, "gitea", "acme/barn") + .expect("health reads") + .map(|health| health.consecutive_failures), + Some(0), + "the watch polled cleanly" + ); + } /// The parts a test source polls through, all in memory. fn test_parts( diff --git a/crates/rhema-claw/src/lib.rs b/crates/rhema-claw/src/lib.rs index 6c356f7..0b33339 100644 --- a/crates/rhema-claw/src/lib.rs +++ b/crates/rhema-claw/src/lib.rs @@ -121,4 +121,6 @@ pub use settings::SettingsStore; pub use task_source::{TASKS_SOURCE, TaskScheduler}; pub use task_store::{TaskKind, TaskRecord, TaskStore, TaskStoreError}; pub use turn_store::{TurnStore, TurnStoreError}; -pub use watch_store::{ClawStore, Watch, WatchRecord, WatchShapeError, WatchStoreError}; +pub use watch_store::{ + ClawStore, SCOPE_ACCOUNT, SCOPE_REPO, Watch, WatchRecord, WatchShapeError, WatchStoreError, +}; diff --git a/crates/rhema-claw/src/watch_store.rs b/crates/rhema-claw/src/watch_store.rs index 0999be5..46962ea 100644 --- a/crates/rhema-claw/src/watch_store.rs +++ b/crates/rhema-claw/src/watch_store.rs @@ -114,6 +114,13 @@ CREATE TABLE IF NOT EXISTS watch_health ( consecutive_failures INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (scope, forge, subject) ); +CREATE TABLE IF NOT EXISTS watch_cursors ( + scope TEXT NOT NULL, + forge TEXT NOT NULL, + subject TEXT NOT NULL, + cursor TEXT NOT NULL, + PRIMARY KEY (scope, forge, subject) +); "; /// Why a watch-table operation failed. @@ -315,6 +322,14 @@ impl ClawStore { "DELETE FROM watches WHERE forge = ?1 AND repo = ?2", params![forge.trim(), repo.trim()], )?; + // The cursor goes with the watch: a re-add is a new watch, and it + // starts at *now* like any other rather than resuming where the + // old one stopped (which would replay everything that happened in + // between as fresh news). + conn.execute( + "DELETE FROM watch_cursors WHERE scope = ?1 AND forge = ?2 AND subject = ?3", + params![SCOPE_REPO, forge.trim(), repo.trim()], + )?; Ok(removed == 1) } @@ -419,6 +434,51 @@ impl ClawStore { .map_err(WatchStoreError::from)?; Ok(rows) } + + /// The cursor one watch polls from: the last position it reported to + /// the dispatcher, in the forge's own spelling. `None` before the + /// watch has ever polled. + pub fn cursor( + &self, + scope: &str, + forge: &str, + subject: &str, + ) -> Result, WatchStoreError> { + let conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner); + let mut statement = conn + .prepare( + "SELECT cursor FROM watch_cursors WHERE scope = ?1 AND forge = ?2 AND subject = ?3", + ) + .map_err(WatchStoreError::from)?; + let mut rows = statement + .query_map(params![scope, forge, subject], |row| row.get(0)) + .map_err(WatchStoreError::from)?; + match rows.next() { + Some(row) => Ok(Some(row.map_err(WatchStoreError::from)?)), + None => Ok(None), + } + } + + /// Advances one watch's cursor. Last write wins: the cursor only ever + /// moves forward, and a stale write is one poll's worth of replay that + /// the dispatcher's dedup lane already covers. + pub fn set_cursor( + &self, + scope: &str, + forge: &str, + subject: &str, + cursor: &str, + ) -> Result<(), WatchStoreError> { + let conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner); + conn.execute( + "INSERT INTO watch_cursors (scope, forge, subject, cursor) VALUES (?1, ?2, ?3, ?4) + ON CONFLICT(scope, forge, subject) DO UPDATE SET cursor = excluded.cursor", + params![scope, forge, subject, cursor], + ) + .map_err(WatchStoreError::from)?; + Ok(()) + } + /// Records a successful poll: the streak resets, and the row stops /// reading as broken. pub fn record_poll_ok( @@ -637,6 +697,60 @@ mod tests { assert_eq!(store.list_health().expect("list reads").len(), 1); } + /// A watch remembers where it was: the cursor is a row, so a daemon + /// restart resumes instead of replaying the repository's history. + #[test] + fn a_cursor_is_kept_per_watch_and_moves_forward() { + let store = ClawStore::in_memory().expect("store opens"); + assert_eq!( + store + .cursor(SCOPE_REPO, "gitea", "acme/barn") + .expect("read"), + None, + "a watch that never polled has no cursor" + ); + + store + .set_cursor(SCOPE_REPO, "gitea", "acme/barn", "2026-10-08T00:00:00Z") + .expect("cursor lands"); + assert_eq!( + store + .cursor(SCOPE_REPO, "gitea", "acme/barn") + .expect("read"), + Some("2026-10-08T00:00:00Z".to_owned()) + ); + // Another watch of the same forge is another cursor. + assert_eq!( + store + .cursor(SCOPE_REPO, "gitea", "acme/quarry") + .expect("read"), + None + ); + + store + .set_cursor(SCOPE_REPO, "gitea", "acme/barn", "2026-10-09T00:00:00Z") + .expect("the cursor advances"); + assert_eq!( + store + .cursor(SCOPE_REPO, "gitea", "acme/barn") + .expect("read"), + Some("2026-10-09T00:00:00Z".to_owned()) + ); + + // Removing the watch forgets its place: a re-add starts over from + // now instead of resuming into a backlog. + store + .add("gitea", "acme/barn", Some("https://git.example"), "tok") + .expect("add"); + store.remove("gitea", "acme/barn").expect("remove"); + assert_eq!( + store + .cursor(SCOPE_REPO, "gitea", "acme/barn") + .expect("read"), + None + ); + } + #[test] fn validation_fails_a_watch_loudly_and_specificly() { assert_eq!( diff --git a/crates/rhema-claw/tests/continuity.rs b/crates/rhema-claw/tests/continuity.rs index c3fbfd9..b445ba6 100644 --- a/crates/rhema-claw/tests/continuity.rs +++ b/crates/rhema-claw/tests/continuity.rs @@ -13,10 +13,22 @@ use rhema_claw::{ClawConfig, run_once}; /// carrying watches, and the test speaks to the daemon the way an /// integration would: through the store the routes share. fn seed_watch(dir: &tempfile::TempDir, host: &str) { - rhema_claw::ClawStore::open(dir.path().join("dispatch.db")) - .expect("the watch table opens") + 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"); + // An established watch: it already has a cursor, so the pass reads + // the feed from there instead of seeding one at *now* (which a + // never-polled watch does, and which feeds nothing). + store + .set_cursor( + rhema_claw::SCOPE_REPO, + "github", + "acme/widgets", + "2026-10-01T00:00:00Z", + ) + .expect("the cursor seeds"); } use rhema_core::{Message, MockProvider, ModelOutput, Role, Session, StopReason, Usage}; use rhema_rsd::{KeyState, Outcome, ResourceKey, SqliteStore, Store}; diff --git a/crates/rhema-claw/tests/e2e.rs b/crates/rhema-claw/tests/e2e.rs index 833dbdb..a1576a2 100644 --- a/crates/rhema-claw/tests/e2e.rs +++ b/crates/rhema-claw/tests/e2e.rs @@ -67,10 +67,22 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig { /// carrying watches, and the test speaks to the daemon the way an /// integration would: through the store the routes share. fn seed_watch(dir: &tempfile::TempDir, host: &str) { - rhema_claw::ClawStore::open(dir.path().join("dispatch.db")) - .expect("the watch table opens") + 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"); + // An established watch: it already has a cursor, so the pass reads + // the feed from there instead of seeding one at *now* (which a + // never-polled watch does, and which feeds nothing). + store + .set_cursor( + rhema_claw::SCOPE_REPO, + "github", + "acme/widgets", + "2026-10-01T00:00:00Z", + ) + .expect("the cursor seeds"); } #[tokio::test] diff --git a/crates/rhema-claw/tests/http.rs b/crates/rhema-claw/tests/http.rs index 7dc41c7..5e0b283 100644 --- a/crates/rhema-claw/tests/http.rs +++ b/crates/rhema-claw/tests/http.rs @@ -1109,7 +1109,23 @@ async fn watches_added_over_http_feed_the_next_detect_pass() { "the token is not serialized: {listed}" ); - // The next pass detects through the new watch — no restart. + // The next pass reads the new watch — no restart. Its first pass only + // seeds a cursor: a watch starts at *now* and reports news, so the + // repository's existing history is not replayed as a burst of + // dispatches (and, from the handler, a burst of comments). + let report = daemon.tick().await.expect("the pass runs"); + assert_eq!(report.detected, 0, "a fresh watch seeds its cursor"); + + // Rewound to before the feed's rows — an established watch — the same + // pass detects the feed's event. + Arc::new(rhema_claw::ClawStore::open(dir.path().join("dispatch.db")).expect("reopens")) + .set_cursor( + rhema_claw::SCOPE_REPO, + "github", + "acme/widgets", + "2026-10-01T00:00:00Z", + ) + .expect("the cursor rewinds"); let report = daemon.tick().await.expect("the pass runs"); assert_eq!(report.detected, 1, "the new watch's feed event was fed");