Skip to main content

taskfast_cli/cmd/events/
poll.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast events poll` — single-page read over `GET /agents/me/events`.
3//!
4//! The SDK also offers `stream_events` (long-running cursor chase);
5//! the polling subcommand stays one-shot because a JSON-lines follow
6//! mode doesn't mix with the envelope-per-invocation contract. Live
7//! tailing lives in [`super::stream`] over WebSocket instead.
8//!
9//! # Cursor persistence
10//!
11//! With `--cursor` absent, the previous invocation's `next_cursor` is
12//! read from `<config_dir>/events.cursor` so back-to-back polls in an
13//! agent loop resume past the last batch without orchestrator
14//! bookkeeping. After a successful poll the new `next_cursor` is
15//! written back. `--cursor -` and `TASKFAST_NO_CURSOR_STATE=1` both
16//! disable read+write for ad-hoc inspection runs that shouldn't
17//! mutate the persisted offset.
18
19use std::fs;
20use std::path::{Path, PathBuf};
21
22use clap::Parser;
23use serde_json::json;
24
25use super::super::{CmdError, CmdResult, Ctx};
26use crate::envelope::Envelope;
27
28use taskfast_agent::events::list_events_page_tolerant;
29
30#[derive(Debug, Parser)]
31pub struct PollArgs {
32    /// Opaque pagination cursor from a previous response's `next_cursor`.
33    /// Pass `-` to bypass the persisted cursor file (no read, no write)
34    /// for one-shot inspection without mutating the agent loop's offset.
35    #[arg(long)]
36    pub cursor: Option<String>,
37
38    /// Max events per page. Defaults to 25 — comfortable batch for an
39    /// agent loop tick without dragging in a wall of backlog.
40    #[arg(long, default_value_t = 25)]
41    pub limit: i64,
42}
43
44pub async fn run(ctx: &Ctx, args: PollArgs) -> CmdResult {
45    let cursor_state = CursorState::resolve(args.cursor.as_deref(), ctx);
46    let effective_cursor = cursor_state.effective_cursor();
47
48    let client = ctx.client()?;
49    let page = list_events_page_tolerant(&client, effective_cursor, Some(args.limit))
50        .await
51        .map_err(CmdError::from)?;
52
53    if cursor_state.persistence_enabled() {
54        if let Some(path) = cursor_state.path() {
55            persist_cursor(path, page.meta.next_cursor.as_deref(), ctx);
56        }
57    }
58
59    for item in &page.unparseable {
60        tracing::warn!(
61            target: "taskfast::events",
62            raw = %item.raw,
63            error = %item.error,
64            "unparseable event surfaced via tolerant decode"
65        );
66    }
67
68    let unparseable: Vec<serde_json::Value> = page
69        .unparseable
70        .iter()
71        .map(|u| json!({ "raw": u.raw, "error": u.error }))
72        .collect();
73
74    Ok(Envelope::success(
75        ctx.environment,
76        ctx.dry_run,
77        json!({
78            "events": page.events,
79            "unparseable": unparseable,
80            "meta": page.meta,
81        }),
82    ))
83}
84
85/// Filename relative to the config directory. Living next to `config.json`
86/// keeps a project's TaskFast state self-contained (one dir to back up,
87/// one dir to gitignore) rather than scattering across XDG paths.
88const CURSOR_FILENAME: &str = "events.cursor";
89
90/// Sentinel passed via `--cursor -` to bypass the file completely.
91const DISABLE_SENTINEL: &str = "-";
92
93/// Env var that disables cursor persistence globally (read + write). Useful
94/// for CI or transient debug runs that share a config dir with a real loop.
95const DISABLE_ENV: &str = "TASKFAST_NO_CURSOR_STATE";
96
97/// Carries the cursor value the request will use plus, if persistence
98/// is enabled, the file path to overwrite with `next_cursor` after the
99/// poll succeeds. The two are decoupled because an explicit `--cursor`
100/// must still hit the API even when the file path is unavailable
101/// (e.g. tests that point `config_path` at `/dev/null`).
102struct CursorState {
103    /// Cursor sent to the API on this call. None = first page.
104    request_cursor: Option<String>,
105    /// File path to write `next_cursor` into on success. None = no
106    /// persistence (sentinel passed, env opt-out, or no config dir).
107    persist_to: Option<PathBuf>,
108}
109
110impl CursorState {
111    fn resolve(cursor_arg: Option<&str>, ctx: &Ctx) -> Self {
112        let env_disabled = std::env::var(DISABLE_ENV).is_ok_and(|v| v == "1");
113        let sentinel = matches!(cursor_arg, Some(s) if s == DISABLE_SENTINEL);
114        let persist_to = if env_disabled || sentinel {
115            None
116        } else {
117            cursor_path(ctx)
118        };
119
120        let request_cursor = match cursor_arg {
121            Some(s) if s == DISABLE_SENTINEL => None,
122            Some(s) => Some(s.to_string()),
123            None => persist_to.as_deref().and_then(read_cursor),
124        };
125
126        Self {
127            request_cursor,
128            persist_to,
129        }
130    }
131
132    fn effective_cursor(&self) -> Option<&str> {
133        self.request_cursor.as_deref()
134    }
135
136    fn persistence_enabled(&self) -> bool {
137        self.persist_to.is_some()
138    }
139
140    fn path(&self) -> Option<&Path> {
141        self.persist_to.as_deref()
142    }
143}
144
145/// Resolve the cursor file location from the config path. `/dev/null` (used
146/// by tests) returns None so unit tests don't hit the filesystem.
147fn cursor_path(ctx: &Ctx) -> Option<PathBuf> {
148    let parent = ctx.config_path.parent()?;
149    if parent.as_os_str().is_empty() {
150        return Some(PathBuf::from(CURSOR_FILENAME));
151    }
152    if parent == Path::new("/dev") {
153        return None;
154    }
155    Some(parent.join(CURSOR_FILENAME))
156}
157
158fn read_cursor(path: &Path) -> Option<String> {
159    let raw = fs::read_to_string(path).ok()?;
160    let trimmed = raw.trim().to_string();
161    if trimmed.is_empty() {
162        None
163    } else {
164        Some(trimmed)
165    }
166}
167
168/// Best-effort write. A failure (read-only FS, permission denied) is logged
169/// to stderr but does not fail the command — the user already got their
170/// page; losing the cursor only costs one redundant poll on next run.
171///
172/// When the server returns `next_cursor: null` (tip reached) the on-disk
173/// cursor is left untouched. Overwriting with an empty string would make
174/// the next `events poll` (without `--cursor`) restart from the beginning
175/// and replay backlog.
176fn persist_cursor(path: &Path, next_cursor: Option<&str>, ctx: &Ctx) {
177    let Some(payload) = next_cursor else {
178        return;
179    };
180    if let Some(dir) = path.parent() {
181        if let Err(e) = fs::create_dir_all(dir) {
182            warn_persist_failed(ctx, path, &e.to_string());
183            return;
184        }
185    }
186    if let Err(e) = fs::write(path, payload) {
187        warn_persist_failed(ctx, path, &e.to_string());
188    }
189}
190
191fn warn_persist_failed(ctx: &Ctx, path: &Path, reason: &str) {
192    if ctx.quiet {
193        return;
194    }
195    eprintln!(
196        "warning: failed to persist events cursor to {}: {reason}",
197        path.display()
198    );
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204    use std::path::PathBuf;
205
206    fn ctx_with_config(path: PathBuf) -> Ctx {
207        Ctx {
208            config_path: path,
209            ..Default::default()
210        }
211    }
212
213    #[test]
214    fn cursor_path_uses_config_parent() {
215        let ctx = ctx_with_config(PathBuf::from("/tmp/foo/.taskfast/config.json"));
216        assert_eq!(
217            cursor_path(&ctx),
218            Some(PathBuf::from("/tmp/foo/.taskfast/events.cursor"))
219        );
220    }
221
222    #[test]
223    fn cursor_path_skips_dev_null() {
224        let ctx = ctx_with_config(PathBuf::from("/dev/null"));
225        assert_eq!(cursor_path(&ctx), None);
226    }
227
228    #[test]
229    fn dash_sentinel_disables_both_request_and_persistence() {
230        let ctx = ctx_with_config(PathBuf::from("/tmp/x/.taskfast/config.json"));
231        let s = CursorState::resolve(Some("-"), &ctx);
232        assert!(!s.persistence_enabled());
233        assert_eq!(s.effective_cursor(), None);
234    }
235
236    #[test]
237    fn explicit_cursor_uses_passed_value() {
238        let ctx = ctx_with_config(PathBuf::from("/tmp/x/.taskfast/config.json"));
239        let s = CursorState::resolve(Some("abc"), &ctx);
240        assert_eq!(s.effective_cursor(), Some("abc"));
241        assert!(s.persistence_enabled());
242    }
243
244    #[test]
245    fn explicit_cursor_still_sent_when_persistence_unavailable() {
246        let ctx = ctx_with_config(PathBuf::from("/dev/null"));
247        let s = CursorState::resolve(Some("abc"), &ctx);
248        assert_eq!(s.effective_cursor(), Some("abc"));
249        assert!(!s.persistence_enabled());
250    }
251
252    #[test]
253    fn dev_null_config_disables_persistence() {
254        let ctx = ctx_with_config(PathBuf::from("/dev/null"));
255        let s = CursorState::resolve(None, &ctx);
256        assert_eq!(s.effective_cursor(), None);
257        assert!(!s.persistence_enabled());
258    }
259
260    #[test]
261    fn write_then_read_round_trips() {
262        let dir = tempfile::tempdir().unwrap();
263        let cfg = dir.path().join("config.json");
264        let ctx = ctx_with_config(cfg);
265        let path = cursor_path(&ctx).unwrap();
266        persist_cursor(&path, Some("xyz"), &ctx);
267        assert_eq!(read_cursor(&path), Some("xyz".into()));
268    }
269
270    #[test]
271    fn persist_none_preserves_last_known_cursor() {
272        let dir = tempfile::tempdir().unwrap();
273        let cfg = dir.path().join("config.json");
274        let ctx = ctx_with_config(cfg);
275        let path = cursor_path(&ctx).unwrap();
276        persist_cursor(&path, Some("abc"), &ctx);
277        persist_cursor(&path, None, &ctx);
278        assert_eq!(read_cursor(&path), Some("abc".into()));
279    }
280}