From fcae1161410cfd9a5f4531cd84a58cc3348b75e0 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Fri, 20 Nov 2026 08:10:39 -0400 Subject: [PATCH 1/4] Add in-session cron tasks, --until-goal, loop notifications and the LoopIteration hook The model can now schedule prompts in its own Session with cron_create, cron_list and cron_delete. A task is a Loop of kind cron (cron_ ID) that reuses the loop events, sweep, overlap, budgets and restore, and shares the loops.max_per_session cap with /loop. Expressions are 5-field cron in local time (cyber-core::cron, DST-aware); one-shot tasks take an at time. The tools are offered only to root Sessions outside Workflow Runs, and cron_delete cannot stop a user's /loop. Restore applies the missed-run policy to cron tasks; a one-shot task whose time passed under skip ends expired. /loop gains --until-goal (stops with goal_ended when the recorded Goal ends) and --notify always|on_change|never. Iterations that report noop: false or fail, and failed or budget_exceeded stops, record a Session notification. LoopIteration hooks fire after loop.iteration.ended.1. /loop list rows show the kind, the next run and the stop conditions. Adds the OpenSpec change implement-m2-4-schedules (proposal, design, tasks, spec deltas) covering both this part and persistent schedules. --- ROADMAP.md | 2 +- crates/cyber-app/tests/loops.rs | 102 ++++ crates/cyber-core/src/cron.rs | 572 ++++++++++++++++++ crates/cyber-core/src/lib.rs | 1 + crates/cyber-core/src/loops.rs | 93 ++- crates/cyber-server/src/runtime/loops/cron.rs | 170 ++++++ .../src/runtime/loops/followups.rs | 252 ++++++++ crates/cyber-server/src/runtime/loops/mod.rs | 38 +- .../cyber-server/src/runtime/loops/records.rs | 57 +- .../src/runtime/loops/schedule.rs | 172 ++++-- crates/cyber-server/src/runtime/usage_wait.rs | 7 +- crates/cyber-server/tests/loops.rs | 403 ++++++++++++ crates/cyber-tools/src/host.rs | 7 + crates/cyber-tools/src/lifecycle_hooks.rs | 2 + crates/cyber-tools/src/tools/loops.rs | 125 +++- crates/cyber-tools/src/tools/mod.rs | 3 + crates/cyber-tui/src/loops.rs | 97 ++- docs/local-core-guide.md | 19 +- .../implement-m2-4-schedules/design.md | 216 +++++++ .../implement-m2-4-schedules/proposal.md | 61 ++ .../specs/loops-scheduling/spec.md | 76 +++ .../changes/implement-m2-4-schedules/tasks.md | 39 ++ sdk/openapi.json | 58 +- sdk/typescript/src/generated/types.ts | 16 +- 24 files changed, 2517 insertions(+), 71 deletions(-) create mode 100644 crates/cyber-core/src/cron.rs create mode 100644 crates/cyber-server/src/runtime/loops/cron.rs create mode 100644 crates/cyber-server/src/runtime/loops/followups.rs create mode 100644 openspec/changes/implement-m2-4-schedules/design.md create mode 100644 openspec/changes/implement-m2-4-schedules/proposal.md create mode 100644 openspec/changes/implement-m2-4-schedules/specs/loops-scheduling/spec.md create mode 100644 openspec/changes/implement-m2-4-schedules/tasks.md diff --git a/ROADMAP.md b/ROADMAP.md index 06b343434..3e6a3b9cd 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -123,7 +123,7 @@ The [current inventory](docs/implementation/spec-doc-reconciliation.md) contains 1. **M2.1 Workflow runtime:** QuickJS sandbox, `agent()/parallel()/pipeline()/phase()`, determinism guards, event-sourced resume, budgets, model tiers (`fast` / `smart` / `verify`). *Status: implemented and accepted end to end with the real binary and a scripted local provider, including the gaps (`ask()`, direct read-only tools, prompt-cache warm-up, `exec --workflow`, `/tasks`, the Workflow library over HTTP, Save); reserved budgets are implemented for bounded official OpenAI Responses requests ([limits and owner reconciliation](docs/reserved-budgets.md)); finished-transcript retention remains (Session export includes run summaries); see [P2 evidence](docs/implementation/p2-status.md).* 2. **M2.2 Verified workflow library:** *Status: the five original bundled Workflows and the `solve` candidate/check/judge protocol are implemented; solve has scripted real-binary acceptance and green platform CI in PR #23.* The bundled review, audit (find → verify), migrate (fan-out with worktrees), research (cross-checked) and plan-from-angles ship in the binary (change `implement-m2-2-bundled-workflows`) with library listing, `show`/`eject`, args validation, host preparation, `/review` and `cyber review` routed to `review`, and the `/workflows` Library tab; each runs end to end on the real binary against a scripted model (`crates/cyber-cli/tests/bundled_workflows.rs`). Open: TUI pty/PNG captures, a live-model run and the archive; see [P2 evidence](docs/implementation/p2-status.md#m22-bundled-workflows-2026-10-22). The `solve` workflow adds 2–4 independent model attempts in worktrees → host-run checks tied to exact source revisions → an independent judge → an evidence report and optional recommendation; no automatic merge. Default soft budget: 5 USD / 30 minutes. See [solve acceptance](docs/measurements/verified-solve-acceptance.md) and the [archived change](openspec/changes/archive/2026-10-23-add-verified-solve-workflow/proposal.md). 3. **M2.3 Goals:** active goal + goal queue, evaluator verdicts, `check` commands, budgets, `exec --goal` exit codes. **Status: implemented** (change `implement-m2-3-goals`): `/goal` with queue, pause/resume/skip/clear/edit and reorder, the evaluator after each Turn with continuation and completion, checks, budgets, blocking-error pauses, deferred evaluation during background work, restore after restart, `core/goal` context, notifications, hooks, HTTP routes, the TUI panel, footer and sidebar, `exec --goal`, templates, `/goal fork` into a worktree Session, goals on subagents and workflow `agent()`, the model `goal` tool and unattended-ask pauses. The live end-to-end acceptance on the real binary remains. -4. **M2.4 Loops & cron:** `/loop` fixed and self-paced, in-session cron, daemon-backed persistent loops. **Status: Session loops implemented** (change `implement-m2-4-loops`): fixed-interval and self-paced `/loop` with `schedule_wakeup`, queued delivery with overlap skip/coalesce, noop collapsing, `--max`/`--for`/`--until`/budget stops, restore after restart, HTTP routes and the TUI. In-session cron tools, persistent `cyber loops` schedules, jitter, notifications, loop hooks and `--until-goal` remain. +4. **M2.4 Loops & cron:** `/loop` fixed and self-paced, in-session cron, daemon-backed persistent loops. **Status: Session loops and in-session cron implemented** (changes `implement-m2-4-loops`, `implement-m2-4-schedules` part A): fixed-interval and self-paced `/loop` with `schedule_wakeup`, queued delivery with overlap skip/coalesce, noop collapsing, `--max`/`--for`/`--until`/`--until-goal`/budget stops, restore after restart with the missed-run policy, the model's `cron_create`/`cron_list`/`cron_delete` tasks, loop notifications (`--notify`), the `LoopIteration` hook, HTTP routes and the TUI. Persistent `cyber loops` schedules run by the service (unattended Mode, jitter, desktop notifications, `schedule.run.1`, `ScheduleRun`) remain. 5. **M2.5 Agent view & teams:** `cyber agents` dashboard; experimental lead/teammates with a shared task list. **Status: agent teams implemented, behind the experimental `teams` feature** (change `implement-agent-teams`, sections 1–9): definitions, spawning with worktree isolation and the lead's Mode ceiling and deny rules, the shared task board with dependencies and atomic claims, team messaging and idle notices, file ownership, `team_merge` that leaves the lead's checkout unchanged on conflicts, team budgets, stop/resume with restart recovery, HTTP/SDK/CLI and the TUI team view; accepted by hand on 2026-10-20 with the real binary and a scripted local provider (15 scenarios, [evidence](docs/implementation/p2-status.md#agent-teams-2026-10-20)). The `cyber agents` dashboard (agent view), an automated end-to-end suite, Windows runs and the archive remain; distributed teammates are P3. **Direct peers (`cross-session-messaging`, P2, not owned by an M2.x milestone): Status: implemented** (change `add-messaging-direct-peers`; [guide](docs/peers.md)). Pairing with pinned TLS fingerprints and hashed grant tokens, `name@machine` sends held on the receiver, polled outcomes, listing and watches, revocation, `cyber attach @` and opt-in mDNS discovery have production-path tests and were accepted by hand on 2026-10-19 with two real servers on one macOS host. Open: OS keyring evidence (mocked with `--token-env`), two-way pairing with a reply, the SSH-tunnel flow, a two-host run, Linux and Windows CI on this work, and the archive; see [P2 evidence](docs/implementation/p2-status.md#cross-session-messaging-direct-peers-2026-10-19). diff --git a/crates/cyber-app/tests/loops.rs b/crates/cyber-app/tests/loops.rs index fdc36af70..d630b1530 100644 --- a/crates/cyber-app/tests/loops.rs +++ b/crates/cyber-app/tests/loops.rs @@ -183,3 +183,105 @@ async fn until_runs_a_real_check_through_the_app_host() { assert_eq!(ended["status"], "until_met", "{ended}"); assert_eq!(ended["iterations"], 0); } + +/// `loops-scheduling` → In-session cron tools: the real tools, offered to a root +/// Session; `cron_delete` cannot reach a `/loop` the user started. +#[tokio::test] +async fn the_model_manages_scheduled_tasks_with_the_cron_tools() { + let app = ModeApp::start(Setup::default()).await; + let id = session(&app).await; + let at = (chrono::Utc::now() + chrono::Duration::hours(2)).to_rfc3339(); + app.run( + &id, + &format!(r#"TOOL<>{{"at": "{at}", "prompt": "summarize overnight CI"}}"#), + ) + .await; + let outputs = app.outputs(&id).await; + let created: Value = serde_json::from_str(&outputs[0]).unwrap_or(Value::Null); + let task_id = created["id"] + .as_str() + .unwrap_or_else(|| panic!("{outputs:?}")) + .to_owned(); + assert!(task_id.starts_with("cron_"), "{created}"); + assert!(created["next_run"].is_string(), "{created}"); + let requests = app.model.requests(); + let turn = requests.iter().find(|r| !offered(r).is_empty()).unwrap(); + for tool in ["cron_create", "cron_list", "cron_delete"] { + assert!(offered(turn).contains(&tool.to_string()), "{tool}"); + } + + let (_, listed) = app + .send("GET", &format!("/sessions/{id}/loops"), None) + .await; + let task = &listed["data"][0]; + assert_eq!( + (task["kind"].as_str(), task["loop_id"].as_str()), + (Some("cron"), Some(task_id.as_str())) + ); + assert!(task["at_ms"].is_i64(), "{task}"); + + // A `/loop` of the user (here one whose check already passed) is not a task. + let user_loop = create(&app, &id, r#"1h --until "test -d .git" check the deploy"#).await; + let loop_id = user_loop["loop_id"].as_str().unwrap().to_owned(); + app.run(&id, &format!(r#"TOOL<>{{"id": "{loop_id}"}}"#)) + .await; + assert_output(&app, &id, &format!("Unknown scheduled task {loop_id}")).await; + app.run(&id, "TOOL<>{}").await; + assert_output(&app, &id, "\"tasks\":[{\"id\":\"cron_").await; + app.run(&id, &format!(r#"TOOL<>{{"id": "{task_id}"}}"#)) + .await; + let ended = wait_loop(&app, &id, &task_id, |l| l["status"] != "active").await; + assert_eq!(ended["status"], "stopped"); +} + +/// `loops-scheduling` → Loop events and hooks: `LoopIteration` receives the loop and the +/// iteration on stdin after `loop.iteration.ended.1` commits. +#[tokio::test] +async fn loop_iteration_hook_receives_the_iteration() { + let app = ModeApp::start(Setup { + config: json!({"hooks": {"LoopIteration": [{"hooks": [ + {"type": "command", "command": "cat > iteration.json"}]}]}}), + ..Setup::default() + }) + .await; + let id = session(&app).await; + let created = create(&app, &id, "5m --max 1 check the deploy").await; + let loop_id = created["loop_id"].as_str().unwrap(); + wait_loop(&app, &id, loop_id, |l| l["status"] != "active").await; + let path = app.repo.join("iteration.json"); + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + let written = loop { + if let Ok(text) = std::fs::read_to_string(&path) + && let Ok(value) = serde_json::from_str::(&text) + { + break value; + } + assert!(tokio::time::Instant::now() < deadline, "the hook never ran"); + tokio::time::sleep(Duration::from_millis(50)).await; + }; + assert_eq!( + written["hook_event_name"] + .as_str() + .or(written["event"].as_str()), + Some("LoopIteration"), + "{written}" + ); + assert_eq!(written["loop"]["loop_id"], loop_id, "{written}"); + assert_eq!(written["iteration"]["n"], 1); + assert_eq!(written["iteration"]["outcome"], "completed"); + assert_eq!(written["iteration"]["noop"], false); + let kinds: Vec = app.events(&id).into_iter().map(|e| e.kind).collect(); + assert!( + kinds.iter().any(|k| k == "loop.iteration.ended.1"), + "{kinds:?}" + ); +} + +/// Some settled call of the Session returned output containing `needle`. +async fn assert_output(app: &ModeApp, id: &str, needle: &str) { + let outputs = app.outputs(id).await; + assert!( + outputs.iter().any(|o| o.contains(needle)), + "{needle}: {outputs:?}" + ); +} diff --git a/crates/cyber-core/src/cron.rs b/crates/cyber-core/src/cron.rs new file mode 100644 index 000000000..eefad5cc5 --- /dev/null +++ b/crates/cyber-core/src/cron.rs @@ -0,0 +1,572 @@ +//! Five-field cron expressions and one-shot times (`loops-scheduling` → In-session cron +//! tools, Persistent local schedules), shared by the cron tools and persistent schedules. +//! +//! ```text +//! minute hour day-of-month month day-of-week +//! ``` +//! +//! Each field takes `*`, `N`, `A-B`, `*/S`, `A-B/S`, `N/S` and comma lists; months take +//! `JAN`–`DEC` and days `SUN`–`SAT` (any case), and day-of-week `7` is Sunday. When both +//! day fields are restricted a day matches if either does, as classic cron does. The +//! macros `@hourly`, `@daily`, `@weekly`, `@monthly` and `@yearly` are accepted. +//! +//! Occurrences are computed in a caller-chosen time zone: a local time a DST change skips +//! does not occur, and an ambiguous one occurs once, at its earlier instant. + +use chrono::{ + DateTime, Datelike, Duration, LocalResult, NaiveDate, NaiveDateTime, TimeZone, Timelike, Utc, +}; + +/// How far ahead an occurrence is searched for. +const HORIZON_YEARS: i32 = 5; +/// The longest expression accepted. +const MAX_EXPRESSION: usize = 200; + +const MONTHS: [&str; 12] = [ + "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", +]; +const DAYS: [&str; 7] = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]; + +/// A parsed cron expression. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Cron { + source: String, + minutes: u64, + hours: u64, + days: u64, + months: u64, + weekdays: u64, + /// Day of month or day of week is `*…`: both must then match (otherwise either). + any_day: bool, +} + +/// The bounds and names of one field. +struct Field { + name: &'static str, + min: u32, + max: u32, + names: &'static [&'static str], + /// The value of the first name (`JAN` is 1, `SUN` is 0). + first: u32, +} + +const MINUTE: Field = Field { + name: "minute", + min: 0, + max: 59, + names: &[], + first: 0, +}; +const HOUR: Field = Field { + name: "hour", + min: 0, + max: 23, + names: &[], + first: 0, +}; +const DAY: Field = Field { + name: "day of month", + min: 1, + max: 31, + names: &[], + first: 0, +}; +const MONTH: Field = Field { + name: "month", + min: 1, + max: 12, + names: &MONTHS, + first: 1, +}; +const WEEKDAY: Field = Field { + name: "day of week", + min: 0, + max: 7, + names: &DAYS, + first: 0, +}; + +impl Cron { + /// Parse `expression`; the error is `Invalid cron expression "": `. + pub fn parse(expression: &str) -> Result { + let invalid = |reason: String| format!("Invalid cron expression {expression:?}: {reason}"); + if expression.len() > MAX_EXPRESSION { + return Err(invalid(format!("longer than {MAX_EXPRESSION} characters"))); + } + let text = expression.trim(); + let expanded = macro_expansion(text).unwrap_or(text); + let fields: Vec<&str> = expanded.split_whitespace().collect(); + let [minute, hour, day, month, weekday] = fields.as_slice() else { + return Err(invalid(format!( + "expected 5 fields (minute hour day-of-month month day-of-week), got {}", + fields.len() + ))); + }; + let mut weekdays = field(weekday, &WEEKDAY).map_err(invalid)?; + if weekdays & (1 << 7) != 0 { + weekdays = (weekdays & !(1 << 7)) | 1; + } + let cron = Self { + source: text.to_owned(), + minutes: field(minute, &MINUTE).map_err(invalid)?, + hours: field(hour, &HOUR).map_err(invalid)?, + days: field(day, &DAY).map_err(invalid)?, + months: field(month, &MONTH).map_err(invalid)?, + weekdays, + any_day: day.starts_with('*') || weekday.starts_with('*'), + }; + let epoch = Utc.with_ymd_and_hms(2001, 1, 1, 0, 0, 0).single(); + if epoch + .and_then(|start| cron.next_after(start, &Utc)) + .is_none() + { + return Err(invalid("it never matches a date".into())); + } + Ok(cron) + } + + /// The expression as given (a macro stays a macro). + pub fn as_str(&self) -> &str { + &self.source + } + + /// The first whole minute strictly after `after` that matches in `tz`; `None` when + /// none does within five years. + pub fn next_after(&self, after: DateTime, tz: &Tz) -> Option> { + let local = after.with_timezone(tz).naive_local(); + let mut candidate = local.with_second(0)?.with_nanosecond(0)? + Duration::minutes(1); + let limit = + NaiveDate::from_ymd_opt(candidate.year() + HORIZON_YEARS, candidate.month(), 1)?; + while candidate.date() <= limit { + if let Some(next) = self.advance(candidate) { + candidate = next; + continue; + } + match tz.from_local_datetime(&candidate) { + LocalResult::Single(time) | LocalResult::Ambiguous(time, _) + if time.with_timezone(&Utc) > after => + { + return Some(time.with_timezone(&Utc)); + } + // Skipped by a DST change, or the earlier instant of a fold already passed. + _ => candidate += Duration::minutes(1), + } + } + None + } + + /// The next candidate after a local time that does not match, `None` when it does. + fn advance(&self, at: NaiveDateTime) -> Option { + let date = at.date(); + if !bit(self.months, at.month()) { + return first_of_next_month(date)?.and_hms_opt(0, 0, 0); + } + if !self.day_matches(date) { + return date.succ_opt()?.and_hms_opt(0, 0, 0); + } + if !bit(self.hours, at.hour()) { + let hour = at.with_minute(0)?; + return Some(hour + Duration::hours(1)); + } + if !bit(self.minutes, at.minute()) { + return Some(at + Duration::minutes(1)); + } + None + } + + fn day_matches(&self, date: NaiveDate) -> bool { + let day = bit(self.days, date.day()); + let weekday = bit(self.weekdays, date.weekday().num_days_from_sunday()); + if self.any_day { + day && weekday + } else { + day || weekday + } + } +} + +fn macro_expansion(text: &str) -> Option<&'static str> { + Some(match text.to_ascii_lowercase().as_str() { + "@hourly" => "0 * * * *", + "@daily" | "@midnight" => "0 0 * * *", + "@weekly" => "0 0 * * 0", + "@monthly" => "0 0 1 * *", + "@yearly" | "@annually" => "0 0 1 1 *", + _ => return None, + }) +} + +fn bit(set: u64, value: u32) -> bool { + set & (1u64 << value) != 0 +} + +fn first_of_next_month(date: NaiveDate) -> Option { + let (year, month) = match date.month() { + 12 => (date.year() + 1, 1), + m => (date.year(), m + 1), + }; + NaiveDate::from_ymd_opt(year, month, 1) +} + +/// One field as a bit set of the values it matches. +fn field(text: &str, spec: &Field) -> Result { + let mut set = 0u64; + for part in text.split(',') { + set |= part_bits(part, spec)?; + } + Ok(set) +} + +fn part_bits(part: &str, spec: &Field) -> Result { + let (range, step) = match part.split_once('/') { + Some((range, step)) => { + let step = step + .parse::() + .ok() + .filter(|s| *s > 0) + .ok_or_else(|| format!("bad step {step:?} in the {} field", spec.name))?; + (range, Some(step)) + } + None => (part, None), + }; + let (low, high) = bounds(range, step.is_some(), spec)?; + let mut set = 0u64; + let mut value = low; + while value <= high { + set |= 1u64 << value; + value += step.unwrap_or(1); + } + Ok(set) +} + +/// The inclusive bounds of `*`, `A-B` or `N` (`N/S` runs from `N` to the field's end). +fn bounds(range: &str, stepped: bool, spec: &Field) -> Result<(u32, u32), String> { + if range == "*" { + return Ok((spec.min, spec.max)); + } + if let Some((low, high)) = range.split_once('-') { + let (low, high) = (value(low, spec)?, value(high, spec)?); + if low > high { + return Err(format!( + "range {range} of the {} field is reversed", + spec.name + )); + } + return Ok((low, high)); + } + let single = value(range, spec)?; + Ok((single, if stepped { spec.max } else { single })) +} + +fn value(text: &str, spec: &Field) -> Result { + let named = spec + .names + .iter() + .position(|name| name.eq_ignore_ascii_case(text)) + .and_then(|index| u32::try_from(index).ok()) + .map(|index| index + spec.first); + let parsed = named.or_else(|| { + text.bytes() + .all(|b| b.is_ascii_digit()) + .then(|| text.parse::().ok()) + .flatten() + }); + parsed + .filter(|v| (spec.min..=spec.max).contains(v)) + .ok_or_else(|| { + format!( + "{text:?} is not a {} ({}-{})", + spec.name, spec.min, spec.max + ) + }) +} + +/// When a one-shot task runs: RFC 3339 (`2026-10-03T09:00:00Z`, or with an offset), or a +/// local `YYYY-MM-DDTHH:MM[:SS]` in `tz`. It must lie after `now` and within one year. +pub fn parse_at( + text: &str, + now: DateTime, + tz: &Tz, +) -> Result, String> { + let text = text.trim(); + let time = match DateTime::parse_from_rfc3339(text) { + Ok(time) => time.with_timezone(&Utc), + Err(_) => local_time(text, tz)?, + }; + if time <= now { + return Err("at must be in the future".into()); + } + if time > now + Duration::days(366) { + return Err("at must be within one year".into()); + } + Ok(time) +} + +fn local_time(text: &str, tz: &Tz) -> Result, String> { + let naive = [ + "%Y-%m-%dT%H:%M:%S", + "%Y-%m-%dT%H:%M", + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M", + ] + .iter() + .find_map(|format| NaiveDateTime::parse_from_str(text, format).ok()) + .ok_or_else(|| { + format!("at {text:?} is not a time: use 2026-10-03T09:00 or an RFC 3339 timestamp") + })?; + match tz.from_local_datetime(&naive) { + LocalResult::Single(time) | LocalResult::Ambiguous(time, _) => Ok(time.with_timezone(&Utc)), + LocalResult::None => Err(format!("at {text:?} does not exist in the local time zone")), + } +} + +/// `ms` since the Unix epoch as an RFC 3339 time in the local time zone, to the second. +pub fn local_time_text(ms: i64) -> String { + DateTime::::from_timestamp_millis(ms) + .map(|time| { + time.with_timezone(&chrono::Local) + .to_rfc3339_opts(chrono::SecondsFormat::Secs, false) + }) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use chrono::FixedOffset; + + use super::*; + + fn utc(text: &str) -> DateTime { + DateTime::parse_from_rfc3339(text) + .unwrap() + .with_timezone(&Utc) + } + + fn next(expr: &str, after: &str) -> String { + Cron::parse(expr) + .unwrap() + .next_after(utc(after), &Utc) + .unwrap() + .to_rfc3339() + } + + #[test] + fn every_minute_and_fixed_times() { + assert_eq!( + next("* * * * *", "2026-10-03T09:00:30Z"), + "2026-10-03T09:01:00+00:00" + ); + // Strictly after: an exact match moves on. + assert_eq!( + next("0 9 * * *", "2026-10-03T09:00:00Z"), + "2026-10-04T09:00:00+00:00" + ); + assert_eq!( + next("0 2 * * *", "2026-10-03T01:59:59Z"), + "2026-10-03T02:00:00+00:00" + ); + assert_eq!( + next("30 23 31 12 *", "2026-01-01T00:00:00Z"), + "2026-12-31T23:30:00+00:00" + ); + } + + #[test] + fn ranges_steps_lists_and_names() { + assert_eq!( + next("*/15 * * * *", "2026-10-03T09:01:00Z"), + "2026-10-03T09:15:00+00:00" + ); + assert_eq!( + next("5/20 * * * *", "2026-10-03T09:30:00Z"), + "2026-10-03T09:45:00+00:00" + ); + assert_eq!( + next("0 9-17/4 * * *", "2026-10-03T13:00:00Z"), + "2026-10-03T17:00:00+00:00" + ); + assert_eq!( + next("0 9,18 * * *", "2026-10-03T10:00:00Z"), + "2026-10-03T18:00:00+00:00" + ); + // 2026-10-03 is a Saturday: weekdays resume on Monday. + assert_eq!( + next("0 9 * * MON-fri", "2026-10-03T10:00:00Z"), + "2026-10-05T09:00:00+00:00" + ); + assert_eq!( + next("0 0 1 jan,JUL *", "2026-02-01T00:00:00Z"), + "2026-07-01T00:00:00+00:00" + ); + // 7 is Sunday too. + assert_eq!( + next("0 0 * * 7", "2026-10-03T00:00:00Z"), + "2026-10-04T00:00:00+00:00" + ); + } + + #[test] + fn restricted_day_fields_match_either() { + // The 15th (a Thursday) or any Monday, whichever is first. + assert_eq!( + next("0 0 15 * 1", "2026-10-06T00:00:00Z"), + "2026-10-12T00:00:00+00:00" + ); + assert_eq!( + next("0 0 15 * 1", "2026-10-12T00:00:00Z"), + "2026-10-15T00:00:00+00:00" + ); + // With a `*` day of week, the day of month alone decides. + assert_eq!( + next("0 0 15 * *", "2026-10-06T00:00:00Z"), + "2026-10-15T00:00:00+00:00" + ); + } + + #[test] + fn macros() { + assert_eq!( + next("@daily", "2026-10-03T09:00:00Z"), + "2026-10-04T00:00:00+00:00" + ); + assert_eq!( + next("@hourly", "2026-10-03T09:00:00Z"), + "2026-10-03T10:00:00+00:00" + ); + assert_eq!(Cron::parse("@weekly").unwrap().as_str(), "@weekly"); + } + + #[test] + fn errors_name_the_problem() { + let error = Cron::parse("61 * * * *").unwrap_err(); + assert!( + error.starts_with("Invalid cron expression \"61 * * * *\": "), + "{error}" + ); + assert!(error.contains("minute"), "{error}"); + assert!( + Cron::parse("* * * *") + .unwrap_err() + .contains("expected 5 fields") + ); + assert!(Cron::parse("*/0 * * * *").unwrap_err().contains("bad step")); + assert!(Cron::parse("* 5-2 * * *").unwrap_err().contains("reversed")); + assert!(Cron::parse("* * * foo *").unwrap_err().contains("month")); + assert!( + Cron::parse("0 0 30 2 *") + .unwrap_err() + .contains("never matches") + ); + assert!(Cron::parse("0 0 29 2 *").is_ok(), "leap days occur"); + } + + #[test] + fn local_time_zones_shift_occurrences() { + let east = FixedOffset::east_opt(2 * 3600).unwrap(); + let cron = Cron::parse("0 9 * * *").unwrap(); + let next = cron.next_after(utc("2026-10-03T06:00:00Z"), &east).unwrap(); + assert_eq!(next.to_rfc3339(), "2026-10-03T07:00:00+00:00"); + } + + /// A zone that skips 02:00–03:00 on 2026-03-29 and repeats 01:00–02:00 on 2026-10-25, + /// as central Europe does, to test DST without the system zone database. + #[derive(Clone, Copy, Debug)] + struct Dst; + + impl Dst { + fn offset_at_utc(utc: &NaiveDateTime) -> FixedOffset { + let summer_start = NaiveDate::from_ymd_opt(2026, 3, 29) + .unwrap() + .and_hms_opt(1, 0, 0) + .unwrap(); + let summer_end = NaiveDate::from_ymd_opt(2026, 10, 25) + .unwrap() + .and_hms_opt(0, 0, 0) + .unwrap(); + let hours = if *utc >= summer_start && *utc < summer_end { + 2 + } else { + 1 + }; + FixedOffset::east_opt(hours * 3600).unwrap() + } + } + + impl TimeZone for Dst { + type Offset = FixedOffset; + fn from_offset(_: &FixedOffset) -> Self { + Dst + } + fn offset_from_local_date(&self, _: &NaiveDate) -> LocalResult { + unimplemented!() + } + fn offset_from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult { + let candidates: Vec = [1, 2] + .into_iter() + .map(|h| FixedOffset::east_opt(h * 3600).unwrap()) + .filter(|offset| { + let utc = *local - Duration::seconds(i64::from(offset.local_minus_utc())); + Self::offset_at_utc(&utc) == *offset + }) + .collect(); + match candidates.as_slice() { + [] => LocalResult::None, + [one] => LocalResult::Single(*one), + // The larger offset is the earlier instant. + [plus_one, plus_two] => LocalResult::Ambiguous(*plus_two, *plus_one), + _ => unreachable!(), + } + } + fn offset_from_utc_date(&self, _: &NaiveDate) -> FixedOffset { + unimplemented!() + } + fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> FixedOffset { + Self::offset_at_utc(utc) + } + } + + #[test] + fn dst_gaps_are_skipped_and_folds_run_once() { + let cron = Cron::parse("30 2 * * *").unwrap(); + // 02:30 does not exist on 2026-03-29; the next one is on the 30th (summer time). + let next = cron.next_after(utc("2026-03-28T23:00:00Z"), &Dst).unwrap(); + assert_eq!(next.to_rfc3339(), "2026-03-30T00:30:00+00:00"); + let fold = Cron::parse("30 1 * * *").unwrap(); + // 01:30 happens twice on 2026-10-25; it runs at the earlier instant only. + let first = fold.next_after(utc("2026-10-24T22:00:00Z"), &Dst).unwrap(); + assert_eq!(first.to_rfc3339(), "2026-10-24T23:30:00+00:00"); + let after = fold.next_after(first, &Dst).unwrap(); + assert_eq!(after.to_rfc3339(), "2026-10-26T00:30:00+00:00"); + } + + #[test] + fn one_shot_times() { + let now = utc("2026-10-02T12:00:00Z"); + let east = FixedOffset::east_opt(3600).unwrap(); + assert_eq!( + parse_at("2026-10-03T09:00", now, &east) + .unwrap() + .to_rfc3339(), + "2026-10-03T08:00:00+00:00" + ); + assert_eq!( + parse_at("2026-10-03T09:00:00Z", now, &east) + .unwrap() + .to_rfc3339(), + "2026-10-03T09:00:00+00:00" + ); + assert_eq!( + parse_at("2026-10-01T09:00", now, &Utc).unwrap_err(), + "at must be in the future" + ); + assert_eq!( + parse_at("2028-10-01T09:00", now, &Utc).unwrap_err(), + "at must be within one year" + ); + assert!( + parse_at("tomorrow", now, &Utc) + .unwrap_err() + .contains("is not a time") + ); + } +} diff --git a/crates/cyber-core/src/lib.rs b/crates/cyber-core/src/lib.rs index 24fca8122..e94bc80c7 100644 --- a/crates/cyber-core/src/lib.rs +++ b/crates/cyber-core/src/lib.rs @@ -8,6 +8,7 @@ pub mod budget; pub mod commands; pub mod config; pub mod construction_discard; +pub mod cron; pub mod env; pub mod eval; pub mod features; diff --git a/crates/cyber-core/src/loops.rs b/crates/cyber-core/src/loops.rs index 9a1d0c6af..cf93ea33f 100644 --- a/crates/cyber-core/src/loops.rs +++ b/crates/cyber-core/src/loops.rs @@ -2,9 +2,9 @@ //! server so both accept and reject exactly the same commands. //! //! ```text -//! /loop [] [--max N] [--for ] [--until ""] [--overlap skip|coalesce] -//! [--missed skip|run-once] [--max-cost USD] [--max-tokens N] [--max-turns N] -//! [--timeout ] +//! /loop [] [--max N] [--for ] [--until ""] [--until-goal] +//! [--overlap skip|coalesce] [--missed skip|run-once] [--notify always|on_change|never] +//! [--max-cost USD] [--max-tokens N] [--max-turns N] [--timeout ] //! /loop list //! /loop stop [|all] //! ``` @@ -45,6 +45,39 @@ pub enum Missed { RunOnce, } +/// When a loop's iterations notify the user (`loops-scheduling` → Completion +/// notifications): `on_change` notifies iterations that report `noop: false` or fail. +#[derive( + Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema, +)] +#[serde(rename_all = "snake_case")] +pub enum Notify { + Always, + #[default] + OnChange, + Never, +} + +impl Notify { + pub fn parse(text: &str) -> Option { + match text { + "always" => Some(Self::Always), + "on_change" | "on-change" => Some(Self::OnChange), + "never" => Some(Self::Never), + _ => None, + } + } + + /// Whether an iteration or run that ended with `failed` and `noop` notifies. + pub fn notifies(self, failed: bool, noop: bool) -> bool { + match self { + Self::Always => true, + Self::OnChange => failed || !noop, + Self::Never => false, + } + } +} + /// A loop to create. `interval_seconds: None` makes it self-paced. #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)] #[serde(deny_unknown_fields)] @@ -58,10 +91,15 @@ pub struct LoopSpec { pub for_seconds: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub until: Option, + /// Stop when the Session's current Goal reaches a terminal status. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub until_goal: bool, #[serde(default)] pub overlap: Overlap, #[serde(default)] pub missed: Missed, + #[serde(default)] + pub notify: Notify, #[serde(default, skip_serializing_if = "Option::is_none")] pub budget: Option, } @@ -145,6 +183,11 @@ fn create(args: &str) -> Result { let Some(flag) = word.strip_prefix("--").filter(|f| !f.is_empty()) else { break; }; + if flag == "until-goal" { + spec.until_goal = true; + rest = after; + continue; + } let (value, after) = take_value(after).ok_or_else(|| format!("--{flag} needs a value"))?; apply_flag(&mut spec, flag, &value)?; rest = after; @@ -174,6 +217,9 @@ fn apply_flag(spec: &mut LoopSpec, flag: &str, value: &str) -> Result<(), String _ => return Err("--missed is skip or run-once".into()), } } + "notify" => { + spec.notify = Notify::parse(value).ok_or("--notify is always, on_change or never")?; + } "max-cost" => { let usd = value .parse::() @@ -252,13 +298,28 @@ fn looks_like_duration(word: &str) -> bool { && word.bytes().any(|b| b.is_ascii_alphabetic()) } -/// Whether `text` has the shape of a loop ID. +/// Whether `text` has the shape of a loop ID: `lop_` (`/loop`) or `cron_` (a scheduled +/// task). pub fn is_loop_id(text: &str) -> bool { - text.strip_prefix("lop_").is_some_and(|rest| { + has_id_shape(text, "lop_") || is_cron_id(text) +} + +/// Whether `text` has the shape of a scheduled task or schedule ID (`cron_`). +pub fn is_cron_id(text: &str) -> bool { + has_id_shape(text, "cron_") +} + +fn has_id_shape(text: &str, prefix: &str) -> bool { + text.strip_prefix(prefix).is_some_and(|rest| { !rest.is_empty() && rest.len() <= 64 && rest.bytes().all(|b| b.is_ascii_alphanumeric()) }) } +/// The error when a Session's loops and scheduled tasks reach `loops.max_per_session`. +pub fn limit_error(max: u64) -> String { + format!("Scheduled task limit reached ({max})") +} + /// The first whitespace-separated word and the rest. fn split_word(text: &str) -> (&str, &str) { let text = text.trim_start(); @@ -400,6 +461,24 @@ mod tests { assert!(parse("").is_err()); } + #[test] + fn until_goal_and_notify() { + let s = spec("5m --until-goal --notify never check CI"); + assert!(s.until_goal); + assert_eq!(s.notify, Notify::Never); + assert_eq!(s.prompt, "check CI"); + assert_eq!(spec("5m check").notify, Notify::OnChange); + assert_eq!( + parse("5m --notify loud x").unwrap_err(), + "--notify is always, on_change or never" + ); + assert!(Notify::OnChange.notifies(true, true)); + assert!(Notify::OnChange.notifies(false, false)); + assert!(!Notify::OnChange.notifies(false, true)); + assert!(Notify::Always.notifies(false, true)); + assert!(!Notify::Never.notifies(true, false)); + } + #[test] fn list_and_stop() { assert_eq!(parse("list").unwrap(), LoopCommand::List); @@ -410,6 +489,10 @@ mod tests { LoopCommand::Stop(Some("lop_01ABC".into())) ); assert_eq!(parse("stop nope").unwrap_err(), "Unknown loop nope"); + assert_eq!( + parse("stop cron_01ABC").unwrap(), + LoopCommand::Stop(Some("cron_01ABC".into())) + ); // "list" followed by text is a prompt, not the subcommand. assert_eq!(spec("list the open PRs").prompt, "list the open PRs"); } diff --git a/crates/cyber-server/src/runtime/loops/cron.rs b/crates/cyber-server/src/runtime/loops/cron.rs new file mode 100644 index 000000000..7fa0f813f --- /dev/null +++ b/crates/cyber-server/src/runtime/loops/cron.rs @@ -0,0 +1,170 @@ +//! Scheduled tasks the model creates (`loops-scheduling` → In-session cron tools): Loops +//! of kind `cron` with `cron_` IDs that share every Loop mechanism and the per-Session +//! cap. Only root Sessions outside Workflow Runs have them, and the model can stop only +//! these, never a `/loop` the user started. + +use chrono::{DateTime, Local, Utc}; +use cyber_core::cron::{Cron, parse_at}; +use cyber_core::loops::{MAX_TEXT, Missed, Notify, Overlap}; +use serde::Deserialize; + +use super::records::{self, LoopKind, LoopState, StopConditions, StopStatus}; +use super::schedule::now_ms; +use crate::runtime::events::event; +use crate::runtime::{Runtime, RuntimeError}; + +/// `cron_create`: exactly one of `cron` and `at`. +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CronRequest { + #[serde(default)] + pub cron: Option, + #[serde(default)] + pub at: Option, + pub prompt: String, + #[serde(default)] + pub missed: Missed, + #[serde(default)] + pub notify: Notify, +} + +/// When a task first runs: its expression's next occurrence, or its one-shot time. +enum Timing { + Cron(Cron), + At(DateTime), +} + +impl CronRequest { + fn timing(&self, now: DateTime) -> Result { + match (&self.cron, &self.at) { + (Some(expression), None) => Cron::parse(expression).map(Timing::Cron), + (None, Some(at)) => parse_at(at, now, &Local).map(Timing::At), + _ => Err("Give exactly one of cron (a 5-field expression) and at (a time)".into()), + } + } + + fn prompt(&self) -> Result { + let prompt = self.prompt.trim(); + if prompt.is_empty() { + return Err("The scheduled task's prompt is empty".into()); + } + if prompt.chars().count() > MAX_TEXT { + return Err(format!("The prompt is longer than {MAX_TEXT} characters")); + } + Ok(prompt.to_owned()) + } +} + +/// The next occurrence of a recurring task strictly after `now_ms`, in local time. +pub(super) fn next_occurrence(expression: &str, now_ms: i64) -> Option { + let cron = Cron::parse(expression).ok()?; + let now = DateTime::::from_timestamp_millis(now_ms)?; + cron.next_after(now, &Local).map(|t| t.timestamp_millis()) +} + +impl Runtime { + /// Create a scheduled task in `session_id` (`cron_create`). + pub async fn create_cron( + &self, + session_id: &str, + request: CronRequest, + ) -> Result { + let prompt = request.prompt().map_err(RuntimeError::Invalid)?; + let now = now_ms(); + let now_utc = DateTime::::from_timestamp_millis(now).unwrap_or_default(); + let timing = request.timing(now_utc).map_err(RuntimeError::Invalid)?; + self.inner.ensure_admission_open(session_id)?; + let handle = self.inner.handle(session_id).await?; + let directory = handle.state.lock().await.info.directory.clone(); + let (settings, budget) = self + .inner + .tools + .loop_settings(&directory) + .map_err(RuntimeError::Invalid)?; + let (cron, at_ms, next_due_ms) = match &timing { + Timing::Cron(cron) => { + let next = cron + .next_after(now_utc, &Local) + .ok_or_else(|| RuntimeError::Invalid("the expression never matches".into()))?; + ( + Some(cron.as_str().to_owned()), + None, + next.timestamp_millis(), + ) + } + Timing::At(at) => (None, Some(at.timestamp_millis()), at.timestamp_millis()), + }; + let loop_id = cyber_core::ids::new_id("cron"); + let created = records::Created { + reservation_scope_version: u32::from( + budget + .as_ref() + .is_some_and(|b| b.enforcement == cyber_core::budget::Enforcement::Reserved), + ), + loop_id: loop_id.clone(), + kind: LoopKind::Cron, + prompt, + interval_seconds: None, + cron, + at_ms, + overlap: Overlap::Skip, + missed: request.missed, + notify: request.notify, + stop: StopConditions::default(), + budget, + iteration_cap: settings.max_iterations, + created_ms: now, + next_due_ms, + }; + let state = { + let mut state = handle.state.lock().await; + if state.info.parent_id.is_some() || state.info.workflow_run_id.is_some() { + return Err(RuntimeError::Invalid( + "Scheduled tasks belong to root Sessions outside Workflow Runs".into(), + )); + } + super::ensure_room(&state, &settings)?; + self.inner + .commit_locked(&mut state, vec![event(records::CREATED, &created)])?; + state.loops[&loop_id].clone() + }; + self.nudge_loops(); + Ok(state) + } + + /// The Session's active scheduled tasks (`cron_list`). + pub async fn cron_tasks(&self, session_id: &str) -> Result, RuntimeError> { + let handle = self.inner.handle(session_id).await?; + let state = handle.state.lock().await; + Ok(state + .loops + .values() + .filter(|l| l.kind == LoopKind::Cron && l.active()) + .cloned() + .collect()) + } + + /// Stop one active scheduled task (`cron_delete`); a `/loop` is not one, so it is + /// reported unknown and keeps running. + pub async fn delete_cron(&self, session_id: &str, task_id: &str) -> Result<(), RuntimeError> { + let handle = self.inner.handle(session_id).await?; + let mut state = handle.state.lock().await; + let known = state + .loops + .get(task_id) + .is_some_and(|l| l.kind == LoopKind::Cron && l.active()); + if !known { + return Err(RuntimeError::Invalid(format!( + "Unknown scheduled task {task_id}" + ))); + } + let stopped = records::Stopped { + loop_id: task_id.to_owned(), + status: StopStatus::Stopped, + reason: "deleted with cron_delete".into(), + }; + self.inner + .commit_locked(&mut state, vec![event(records::STOPPED, &stopped)])?; + Ok(()) + } +} diff --git a/crates/cyber-server/src/runtime/loops/followups.rs b/crates/cyber-server/src/runtime/loops/followups.rs new file mode 100644 index 000000000..bbbcbcdb2 --- /dev/null +++ b/crates/cyber-server/src/runtime/loops/followups.rs @@ -0,0 +1,252 @@ +//! What follows a committed loop record (`loops-scheduling` → Completion notifications, +//! Loop events and hooks): a notification under the loop's `notify` policy, and the +//! observational `LoopIteration` hook. Both run after the Session lock is released; +//! neither changes what was recorded. + +use cyber_core::loops::Notify; +use cyber_store::NewEvent; +use serde_json::json; + +use super::records::{self, IterationEnded, LoopKind, LoopState, Outcome, StopStatus, Stopped}; +use crate::runtime::{Notification, Runtime}; + +/// The longest prompt excerpt a notification shows. +const PROMPT_EXCERPT: usize = 60; +/// The longest reason a notification shows. +const REASON_EXCERPT: usize = 160; + +/// One committed record that may notify or fire a hook. +enum Record { + Ended(IterationEnded), + Stopped(Stopped), +} + +fn records_of(events: &[NewEvent]) -> Vec { + events + .iter() + .filter_map(|e| match e.kind.as_str() { + records::ITERATION_ENDED => serde_json::from_value(e.data.clone()) + .ok() + .map(Record::Ended), + records::STOPPED => serde_json::from_value(e.data.clone()) + .ok() + .map(Record::Stopped), + _ => None, + }) + .collect() +} + +/// Whether an ended iteration notifies under `notify`. +fn iteration_notifies(notify: Notify, ended: &IterationEnded) -> bool { + match ended.outcome { + Outcome::Completed => notify.notifies(false, ended.noop), + Outcome::Failed => notify.notifies(true, false), + Outcome::Interrupted => notify == Notify::Always, + Outcome::SkippedOverlap | Outcome::SkippedMissed => false, + } +} + +/// Whether a stop notifies: a failure or an exhausted budget, unless `never`. +fn stop_notifies(notify: Notify, stopped: &Stopped) -> bool { + notify != Notify::Never + && matches!( + stopped.status, + StopStatus::Failed | StopStatus::BudgetExceeded + ) +} + +fn clip(text: &str, max: usize) -> String { + let line = text.split_whitespace().collect::>().join(" "); + if line.chars().count() <= max { + return line; + } + let cut: String = line.chars().take(max - 1).collect(); + format!("{}…", cut.trim_end()) +} + +fn title(lp: &LoopState) -> String { + let id = lp.loop_id.rsplit('_').next().unwrap_or_default(); + let short = id + .get(id.len().saturating_sub(4)..) + .unwrap_or(id) + .to_lowercase(); + match lp.kind { + LoopKind::Cron => format!("Scheduled task {short}"), + LoopKind::Interval | LoopKind::SelfPaced => format!("Loop {short}"), + } +} + +fn iteration_result(ended: &IterationEnded) -> String { + let reason = ended.reason.as_deref().map(|r| clip(r, REASON_EXCERPT)); + match (ended.outcome, reason) { + (Outcome::Failed, Some(reason)) => format!("iteration {} failed: {reason}", ended.n), + (Outcome::Failed, None) => format!("iteration {} failed", ended.n), + (Outcome::Interrupted, _) => format!("iteration {} was interrupted", ended.n), + (_, Some(reason)) => format!("iteration {}: {reason}", ended.n), + (_, None) => format!("iteration {} finished", ended.n), + } +} + +impl Runtime { + /// Notify and run hooks for loop records `session_id` just committed. + pub(crate) async fn loop_followups(&self, session_id: &str, events: &[NewEvent]) { + let records = records_of(events); + if records.is_empty() || self.is_shutting_down() { + return; + } + let Ok(handle) = self.inner.handle(session_id).await else { + return; + }; + let loops = handle.state.lock().await.loops.clone(); + // A loop that stopped with a notice says so once, in place of its iteration's. + let stopping: Vec<&str> = records + .iter() + .filter_map(|r| match r { + Record::Stopped(s) => loops + .get(&s.loop_id) + .filter(|lp| stop_notifies(lp.notify, s)) + .map(|_| s.loop_id.as_str()), + Record::Ended(_) => None, + }) + .collect(); + for record in &records { + match record { + Record::Ended(ended) => { + let Some(lp) = loops.get(&ended.loop_id) else { + continue; + }; + if iteration_notifies(lp.notify, ended) + && !stopping.contains(&ended.loop_id.as_str()) + { + self.loop_notify(session_id, lp, &iteration_result(ended)) + .await; + } + self.loop_iteration_hook(session_id, lp, ended).await; + } + Record::Stopped(stopped) => { + if let Some(lp) = loops.get(&stopped.loop_id) + && stop_notifies(lp.notify, stopped) + { + let status = records::status_name(stopped.status); + let result = format!( + "stopped ({status}): {}", + clip(&stopped.reason, REASON_EXCERPT) + ); + self.loop_notify(session_id, lp, &result).await; + } + } + } + } + } + + async fn loop_notify(&self, session_id: &str, lp: &LoopState, result: &str) { + let notification = Notification { + call_id: lp.loop_id.clone(), + title: title(lp), + body: format!("{}: {result}", clip(&lp.prompt, PROMPT_EXCERPT)), + }; + // A notice past the per-Session rate limit is dropped; the loop events keep it. + let _ = self.record_notification(session_id, notification).await; + } + + /// `LoopIteration` (observational) for an iteration that ran; skipped ticks have none. + async fn loop_iteration_hook(&self, session_id: &str, lp: &LoopState, ended: &IterationEnded) { + if ended.n == 0 { + return; + } + let Ok(handle) = self.inner.handle(session_id).await else { + return; + }; + let fields = json!({ + "loop": lp, + "iteration": { + "n": ended.n, + "outcome": ended.outcome, + "noop": ended.noop, + "duration_ms": ended.duration_ms, + "cost": ended.cost, + "tokens": ended.tokens, + "turns": ended.turns, + "reason": ended.reason, + }, + }); + let hook = self + .inner + .lifecycle_hook(&handle, "LoopIteration", lp.loop_id.clone(), fields) + .await; + self.inner.observe_lifecycle(hook).await; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ended(outcome: Outcome, noop: bool) -> IterationEnded { + IterationEnded { + loop_id: "lop_01TEST".into(), + n: 1, + outcome, + noop, + duration_ms: 1, + cost: 0.0, + tokens: 0, + turns: 0, + next_due_ms: None, + reason: Some("CI is green".into()), + } + } + + #[test] + fn notify_policy_by_outcome() { + use Outcome::*; + assert!(iteration_notifies( + Notify::OnChange, + &ended(Completed, false) + )); + assert!(!iteration_notifies( + Notify::OnChange, + &ended(Completed, true) + )); + assert!(iteration_notifies(Notify::OnChange, &ended(Failed, false))); + assert!(!iteration_notifies( + Notify::OnChange, + &ended(Interrupted, false) + )); + assert!(iteration_notifies(Notify::Always, &ended(Completed, true))); + assert!(!iteration_notifies( + Notify::Always, + &ended(SkippedOverlap, false) + )); + assert!(!iteration_notifies(Notify::Never, &ended(Failed, false))); + let stop = |status| Stopped { + loop_id: "lop_01TEST".into(), + status, + reason: "max_cost_usd 2.01/2.00".into(), + }; + assert!(stop_notifies( + Notify::OnChange, + &stop(StopStatus::BudgetExceeded) + )); + assert!(stop_notifies(Notify::OnChange, &stop(StopStatus::Failed))); + assert!(!stop_notifies(Notify::OnChange, &stop(StopStatus::Stopped))); + assert!(!stop_notifies( + Notify::Never, + &stop(StopStatus::BudgetExceeded) + )); + } + + #[test] + fn results_are_one_line() { + assert_eq!( + iteration_result(&ended(Outcome::Completed, false)), + "iteration 1: CI is green" + ); + assert_eq!( + iteration_result(&ended(Outcome::Failed, false)), + "iteration 1 failed: CI is green" + ); + assert_eq!(clip("a\nb c", 10), "a b c"); + assert_eq!(clip("abcdefghijk", 5), "abcd…"); + } +} diff --git a/crates/cyber-server/src/runtime/loops/mod.rs b/crates/cyber-server/src/runtime/loops/mod.rs index dccf0620e..4c0a41961 100644 --- a/crates/cyber-server/src/runtime/loops/mod.rs +++ b/crates/cyber-server/src/runtime/loops/mod.rs @@ -8,12 +8,16 @@ //! retried admission after a crash is idempotent. [`schedule`] runs them: a background //! sweep admits due iterations, and the Drain's idle exit ends them. +mod cron; +mod followups; pub mod records; mod schedule; use cyber_core::loops::{LoopSettings, LoopSpec, WAKEUP_RANGE}; use serde::Serialize; +pub use cron::CronRequest; + pub use records::{ Inflight, IterationRecord, LoopKind, LoopState, Outcome, StopConditions, StopStatus, }; @@ -55,6 +59,14 @@ impl Runtime { let loop_id = cyber_core::ids::new_id("lop"); let now = schedule::now_ms(); let budget = spec.budget.or(default_budget); + let until_goal = if spec.until_goal { + let current = handle.state.lock().await.goals.current.clone(); + Some(current.ok_or_else(|| { + RuntimeError::Invalid("--until-goal needs a Goal in this Session".into()) + })?) + } else { + None + }; let created = records::Created { reservation_scope_version: u32::from( budget @@ -69,12 +81,16 @@ impl Runtime { }, prompt: spec.prompt.trim().to_owned(), interval_seconds: spec.interval_seconds, + cron: None, + at_ms: None, overlap: spec.overlap, missed: spec.missed, + notify: spec.notify, stop: StopConditions { max_iterations: spec.max_iterations, for_seconds: spec.for_seconds, until: spec.until, + until_goal, }, budget, iteration_cap: settings.max_iterations, @@ -194,6 +210,23 @@ impl Runtime { .unwrap_or(false) } + /// Whether `session_id` may have scheduled tasks (`cron_*` tools): a root Session + /// outside Workflow Runs. Reads only the index; an unknown Session has none. + pub fn cron_tools_offered(&self, session_id: &str) -> bool { + let id = session_id.to_owned(); + self.inner + .store + .read(move |db| { + Ok(db + .prepare( + "SELECT 1 FROM session + WHERE id = ?1 AND parent_id IS NULL AND workflow_run_id IS NULL", + )? + .exists([id])?) + }) + .unwrap_or(false) + } + /// Rebuild `session_loop` from the `loop.*` events; the number of events re-projected. pub fn rebuild_loops(&self) -> Result { Ok(self.inner.store.reproject( @@ -204,7 +237,10 @@ impl Runtime { } } -fn ensure_room(state: &SessionState, settings: &LoopSettings) -> Result<(), RuntimeError> { +pub(super) fn ensure_room( + state: &SessionState, + settings: &LoopSettings, +) -> Result<(), RuntimeError> { let active = state.loops.values().filter(|l| l.active()).count() as u64; if active >= settings.max_per_session { return Err(RuntimeError::LoopLimit(settings.max_per_session)); diff --git a/crates/cyber-server/src/runtime/loops/records.rs b/crates/cyber-server/src/runtime/loops/records.rs index f085d113d..0aa162a04 100644 --- a/crates/cyber-server/src/runtime/loops/records.rs +++ b/crates/cyber-server/src/runtime/loops/records.rs @@ -6,7 +6,7 @@ use std::collections::{BTreeMap, VecDeque}; use cyber_core::budget::Budget; -use cyber_core::loops::{Missed, Overlap}; +use cyber_core::loops::{Missed, Notify, Overlap}; use rusqlite::{Transaction, params}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; @@ -32,6 +32,8 @@ pub const HISTORY: usize = 50; pub enum LoopKind { Interval, SelfPaced, + /// A scheduled task the model created with `cron_create` (`cron_` ID). + Cron, } /// Why a loop ended. @@ -47,6 +49,11 @@ pub enum StopStatus { UntilMet, BudgetExceeded, Failed, + /// A one-shot scheduled task whose time passed while the server was not running + /// (missed-run policy `skip`). + Expired, + /// The Goal named by `--until-goal` reached a terminal status. + GoalEnded, } /// How an iteration ended. @@ -71,6 +78,9 @@ pub struct StopConditions { pub for_seconds: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub until: Option, + /// `--until-goal`: the Goal whose terminal status ends the loop. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub until_goal: Option, } /// `loop.created.1`. @@ -84,8 +94,16 @@ pub struct Created { pub prompt: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub interval_seconds: Option, + /// A recurring scheduled task's 5-field cron expression (local time). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cron: Option, + /// A one-shot scheduled task's time. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub at_ms: Option, pub overlap: Overlap, pub missed: Missed, + #[serde(default)] + pub notify: Notify, pub stop: StopConditions, #[serde(default, skip_serializing_if = "Option::is_none")] pub budget: Option, @@ -190,8 +208,13 @@ pub struct LoopState { pub prompt: String, #[serde(skip_serializing_if = "Option::is_none")] pub interval_seconds: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub cron: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub at_ms: Option, pub overlap: Overlap, pub missed: Missed, + pub notify: Notify, pub stop: StopConditions, #[serde(skip_serializing_if = "Option::is_none")] pub budget: Option, @@ -246,8 +269,11 @@ impl LoopState { kind: c.kind, prompt: c.prompt, interval_seconds: c.interval_seconds, + cron: c.cron, + at_ms: c.at_ms, overlap: c.overlap, missed: c.missed, + notify: c.notify, stop: c.stop, budget: c.budget, iteration_cap: c.iteration_cap, @@ -302,13 +328,33 @@ pub(crate) fn register(registry: &mut EventRegistry) { fn validate_created(data: &Value) -> Result<(), String> { let c: Created = decode(data)?; - if !cyber_core::loops::is_loop_id(&c.loop_id) { - return Err(format!("loop ID {:?} is not a lop_ ID", c.loop_id)); + let cron = c.kind == LoopKind::Cron; + if cron != cyber_core::loops::is_cron_id(&c.loop_id) + || !cyber_core::loops::is_loop_id(&c.loop_id) + { + return Err(format!( + "loop ID {:?} is not a lop_ ID (cron_ for a scheduled task)", + c.loop_id + )); } let interval = c.interval_seconds.is_some(); if interval != (c.kind == LoopKind::Interval) { return Err("an interval loop, and only one, has an interval".into()); } + let (has_cron, has_at) = (c.cron.is_some(), c.at_ms.is_some()); + let timed = if cron { + has_cron != has_at + } else { + !has_cron && !has_at + }; + if !timed { + return Err( + "a scheduled task, and only one, has either a cron expression or a time".into(), + ); + } + if let Some(expression) = &c.cron { + cyber_core::cron::Cron::parse(expression)?; + } if c.prompt.trim().is_empty() || c.iteration_cap == 0 { return Err("a loop has a prompt and an iteration cap".into()); } @@ -424,6 +470,8 @@ pub fn status_name(status: StopStatus) -> &'static str { StopStatus::UntilMet => "until_met", StopStatus::BudgetExceeded => "budget_exceeded", StopStatus::Failed => "failed", + StopStatus::Expired => "expired", + StopStatus::GoalEnded => "goal_ended", } } @@ -521,8 +569,11 @@ pub(crate) mod tests { kind, prompt: "check".into(), interval_seconds: (kind == LoopKind::Interval).then_some(60), + cron: (kind == LoopKind::Cron).then(|| "* * * * *".into()), + at_ms: None, overlap: Overlap::Skip, missed: Missed::Skip, + notify: Notify::OnChange, stop: StopConditions::default(), budget: None, reservation_scope_version: 0, diff --git a/crates/cyber-server/src/runtime/loops/schedule.rs b/crates/cyber-server/src/runtime/loops/schedule.rs index b8502c65a..06da42f22 100644 --- a/crates/cyber-server/src/runtime/loops/schedule.rs +++ b/crates/cyber-server/src/runtime/loops/schedule.rs @@ -35,8 +35,22 @@ fn warn(what: &str, error: &RuntimeError) { ); } -/// The first interval tick after `now`, counted from the loop's creation. +/// When the next iteration after `now` is due: the next interval tick, or the next +/// occurrence of a recurring scheduled task; `None` for a self-paced loop (its wakeup +/// paces it) and a one-shot task. fn next_tick(state: &LoopState, now: i64) -> Option { + match state.kind { + LoopKind::Interval => interval_tick(state, now), + LoopKind::Cron => state + .cron + .as_deref() + .and_then(|expression| super::cron::next_occurrence(expression, now)), + LoopKind::SelfPaced => None, + } +} + +/// The first interval tick after `now`, counted from the loop's creation. +fn interval_tick(state: &LoopState, now: i64) -> Option { let interval = i64::try_from(state.interval_seconds?) .ok()? .saturating_mul(1000); @@ -58,6 +72,22 @@ fn stop_reason(state: &LoopState, now: i64) -> Option<(StopStatus, String)> { budget_exceeded(state, now).map(|reason| (StopStatus::BudgetExceeded, reason)) } +/// `--until-goal`: the loop stops once its Goal reached a terminal status (or is gone). +fn goal_stop(session: &SessionState, state: &LoopState) -> Option<(StopStatus, String)> { + let goal_id = state.stop.until_goal.as_ref()?; + match session.goals.goals.get(goal_id) { + Some(goal) if !goal.status.is_terminal() => None, + Some(goal) => Some(( + StopStatus::GoalEnded, + format!("goal {goal_id} {}", goal.status.as_str()), + )), + None => Some(( + StopStatus::GoalEnded, + format!("goal {goal_id} no longer exists"), + )), + } +} + fn budget_exceeded(state: &LoopState, now: i64) -> Option { let budget = state.budget.as_ref()?; if let Some(max) = budget.max_cost_usd @@ -114,7 +144,8 @@ fn totals(state: &SessionState) -> (f64, u64, u64) { /// What the locked step of a due loop decided. enum Due { - Nothing, + /// Nothing to admit; the records committed, if any, for follow-ups. + Nothing(Vec), Run(Box), } @@ -148,8 +179,12 @@ impl Runtime { } async fn run_due(&self, session_id: &str, loop_id: &str, now: i64) -> Result<(), RuntimeError> { - let Due::Run(iteration) = self.decide_due(session_id, loop_id, now).await? else { - return Ok(()); + let iteration = match self.decide_due(session_id, loop_id, now).await? { + Due::Run(iteration) => iteration, + Due::Nothing(committed) => { + self.loop_followups(session_id, &committed).await; + return Ok(()); + } }; let mut until_tail = None; if let Some(command) = &iteration.until { @@ -186,15 +221,15 @@ impl Runtime { let handle = self.inner.handle(session_id).await?; let mut state = handle.state.lock().await; let Some(lp) = state.loops.get(loop_id).filter(|l| l.active()).cloned() else { - return Ok(Due::Nothing); + return Ok(Due::Nothing(Vec::new())); }; if lp.next_due_ms.is_none_or(|due| due > now) { - return Ok(Due::Nothing); + return Ok(Due::Nothing(Vec::new())); } - if let Some((status, reason)) = stop_reason(&lp, now) { - self.inner - .commit_locked(&mut state, vec![stopped(loop_id, status, reason)])?; - return Ok(Due::Nothing); + if let Some((status, reason)) = stop_reason(&lp, now).or_else(|| goal_stop(&state, &lp)) { + let events = vec![stopped(loop_id, status, reason)]; + self.inner.commit_locked(&mut state, events.clone())?; + return Ok(Due::Nothing(events)); } if lp.inflight.is_some() { if lp.overlap == cyber_core::loops::Overlap::Coalesce { @@ -202,7 +237,7 @@ impl Runtime { } let skip = skipped(&lp, Outcome::SkippedOverlap, next_tick(&lp, now)); self.inner.commit_locked(&mut state, vec![skip])?; - return Ok(Due::Nothing); + return Ok(Due::Nothing(Vec::new())); } let (cost_before, tokens_before, turns_before) = totals(&state); let n = lp.iterations + 1; @@ -321,6 +356,20 @@ impl Runtime { if matches!(error, RuntimeError::ShuttingDown) { return Ok(()); } + let events = self + .refuse_iteration(session_id, iteration, error, now) + .await?; + self.loop_followups(session_id, &events).await; + Ok(()) + } + + async fn refuse_iteration( + &self, + session_id: &str, + iteration: &Iteration, + error: &RuntimeError, + now: i64, + ) -> Result, RuntimeError> { let handle = self.inner.handle(session_id).await?; let mut state = handle.state.lock().await; let Some(lp) = state @@ -329,12 +378,9 @@ impl Runtime { .filter(|l| l.active()) .cloned() else { - return Ok(()); - }; - let next = match lp.kind { - LoopKind::Interval => next_tick(&lp, now), - LoopKind::SelfPaced => None, + return Ok(Vec::new()); }; + let next = next_tick(&lp, now); let ended = records::IterationEnded { loop_id: lp.loop_id.clone(), n: iteration.n, @@ -351,7 +397,8 @@ impl Runtime { if lp.failures + 1 >= MAX_FAILURES || next.is_none() { events.push(stopped(&lp.loop_id, StopStatus::Failed, error.to_string())); } - self.inner.commit_locked(&mut state, events).map(drop) + self.inner.commit_locked(&mut state, events.clone())?; + Ok(events) } async fn commit_loop( @@ -384,8 +431,9 @@ impl Runtime { Ok(false) => return, Err(error) => return warn("reading loops failed", &RuntimeError::Store(error)), } - if let Err(error) = self.end_iterations(session_id, status, now_ms()).await { - warn("ending a loop iteration failed", &error); + match self.end_iterations(session_id, status, now_ms()).await { + Ok(events) => self.loop_followups(session_id, &events).await, + Err(error) => warn("ending a loop iteration failed", &error), } self.nudge_loops(); } @@ -395,7 +443,7 @@ impl Runtime { session_id: &str, status: Option<&str>, now: i64, - ) -> Result<(), RuntimeError> { + ) -> Result, RuntimeError> { let handle = self.inner.handle(session_id).await?; let mut state = handle.state.lock().await; // A Turn that failed or was interrupted ends the Drain normally; its last run says so. @@ -421,9 +469,9 @@ impl Runtime { events.extend(iteration_end(&state, lp, status, coalesced, now)); } if !events.is_empty() { - self.inner.commit_locked(&mut state, events)?; + self.inner.commit_locked(&mut state, events.clone())?; } - Ok(()) + Ok(events) } /// Run the sweep soon, without waiting for its next period. @@ -454,21 +502,31 @@ impl Runtime { .read(|db| Ok(records::active_sessions(db)?))?; let mut changed = 0; for session_id in sessions { - let handle = self.inner.handle(&session_id).await?; - let mut state = handle.state.lock().await; - let running = self.is_running(&session_id); - let mut events = Vec::new(); - for lp in state.loops.values().filter(|l| l.active()) { - events.extend(restored(&state, lp, running, now)); - } - if !events.is_empty() { - changed += events.len(); - self.inner.commit_locked(&mut state, events)?; - } + let events = self.restore_session_loops(&session_id, now).await?; + changed += events.len(); + self.loop_followups(&session_id, &events).await; } Ok(changed) } + async fn restore_session_loops( + &self, + session_id: &str, + now: i64, + ) -> Result, RuntimeError> { + let handle = self.inner.handle(session_id).await?; + let mut state = handle.state.lock().await; + let running = self.is_running(session_id); + let mut events = Vec::new(); + for lp in state.loops.values().filter(|l| l.active()) { + events.extend(restored(&state, lp, running, now)); + } + if !events.is_empty() { + self.inner.commit_locked(&mut state, events.clone())?; + } + Ok(events) + } + /// Run the sweep every [`SWEEP_EVERY`] until shutdown. pub fn spawn_loop_sweep(&self) { let weak = self.downgrade(); @@ -552,8 +610,8 @@ fn iteration_end( }; let wakeup = lp.wakeup.as_ref().filter(|w| w.n == inflight.n); let next = match lp.kind { - LoopKind::Interval if coalesced => Some(now), - LoopKind::Interval => lp.next_due_ms.or_else(|| next_tick(lp, now)), + LoopKind::Interval | LoopKind::Cron if coalesced => Some(now), + LoopKind::Interval | LoopKind::Cron => lp.next_due_ms.or_else(|| next_tick(lp, now)), LoopKind::SelfPaced => { wakeup.map(|w| now + i64::try_from(w.delay_seconds).unwrap_or(3600) * 1000) } @@ -586,13 +644,10 @@ fn iteration_end( let mut events = vec![event(records::ITERATION_ENDED, &ended)]; let stop = if failures >= MAX_FAILURES { Some((StopStatus::Failed, status.unwrap_or("failed").to_owned())) - } else if lp.kind == LoopKind::SelfPaced && wakeup.is_none() { - Some(( - StopStatus::Completed, - "the iteration ended without schedule_wakeup".to_owned(), - )) } else { - stop_reason(&after, now) + completion(lp, wakeup.is_some()) + .or_else(|| stop_reason(&after, now)) + .or_else(|| goal_stop(state, lp)) }; if let Some((status, reason)) = stop { events.push(stopped(&lp.loop_id, status, reason)); @@ -600,6 +655,21 @@ fn iteration_end( events } +/// Why `lp` completes after an iteration: a self-paced iteration that did not pace +/// itself, or a one-shot scheduled task, which runs once. +fn completion(lp: &LoopState, woken: bool) -> Option<(StopStatus, String)> { + match lp.kind { + LoopKind::SelfPaced if !woken => Some(( + StopStatus::Completed, + "the iteration ended without schedule_wakeup".to_owned(), + )), + LoopKind::Cron if lp.at_ms.is_some() => { + Some((StopStatus::Completed, "the one-shot task ran".to_owned())) + } + _ => None, + } +} + /// What restoring `lp` after a restart records. fn restored(state: &SessionState, lp: &LoopState, running: bool, now: i64) -> Vec { if let Some(inflight) = &lp.inflight { @@ -616,14 +686,28 @@ fn restored(state: &SessionState, lp: &LoopState, running: bool, now: i64) -> Ve return iteration_end(state, lp, Some(reason), false, now); } match lp.next_due_ms { - Some(due) if lp.kind == LoopKind::Interval && lp.missed == Missed::Skip && due < now => { - vec![skipped(lp, Outcome::SkippedMissed, next_tick(lp, now))] - } + Some(due) if lp.missed == Missed::Skip && due < now => missed_skip(lp, now), // `run-once`, and a self-paced wakeup that passed: the sweep runs it once. _ => Vec::new(), } } +/// Missed ticks under `skip`: resume at the next one; a one-shot task's single time +/// passed, so it expires. A self-paced wakeup that passed runs once anyway. +fn missed_skip(lp: &LoopState, now: i64) -> Vec { + match lp.kind { + LoopKind::Cron if lp.at_ms.is_some() => vec![stopped( + &lp.loop_id, + StopStatus::Expired, + "its time passed while the server was not running".into(), + )], + LoopKind::Interval | LoopKind::Cron => { + vec![skipped(lp, Outcome::SkippedMissed, next_tick(lp, now))] + } + LoopKind::SelfPaced => Vec::new(), + } +} + fn interrupted_retry( lp: &LoopState, inflight: &records::Inflight, diff --git a/crates/cyber-server/src/runtime/usage_wait.rs b/crates/cyber-server/src/runtime/usage_wait.rs index c10fef120..923cdfad8 100644 --- a/crates/cyber-server/src/runtime/usage_wait.rs +++ b/crates/cyber-server/src/runtime/usage_wait.rs @@ -448,7 +448,12 @@ impl Inner { reason: reason.into(), }; let stop = event(super::loops::records::STOPPED, &stopped); - self.commit(handle, vec![stop]).await.map(drop) + self.commit(handle, vec![stop.clone()]).await?; + let session_id = handle.state.lock().await.info.id.clone(); + if let Some(inner) = self.me.upgrade() { + Runtime { inner }.loop_followups(&session_id, &[stop]).await; + } + Ok(()) } } } diff --git a/crates/cyber-server/tests/loops.rs b/crates/cyber-server/tests/loops.rs index 34905d2b7..75ffb8e80 100644 --- a/crates/cyber-server/tests/loops.rs +++ b/crates/cyber-server/tests/loops.rs @@ -371,3 +371,406 @@ async fn an_iteration_cut_off_by_a_restart_ends_interrupted() { assert_eq!(state.next_due_ms, Some(created.created_ms + 60_000)); h.tools.release.notify_one(); } + +// ---- In-session cron tasks, --until-goal and notifications (`implement-m2-4-schedules`). + +use cyber_core::loops::Notify; +use cyber_server::runtime::loops::{CronRequest, LoopKind}; + +fn rfc3339(ms: i64) -> String { + chrono::DateTime::::from_timestamp_millis(ms) + .unwrap() + .to_rfc3339() +} + +fn at(prompt: &str, at_ms: i64) -> CronRequest { + CronRequest { + at: Some(rfc3339(at_ms)), + prompt: prompt.into(), + ..CronRequest::default() + } +} + +fn now_ms() -> i64 { + chrono::Utc::now().timestamp_millis() +} + +/// The notification events of a Session, as `title: body`. +fn notices(h: &Harness, id: &str) -> Vec { + h.store + .read_events(id, -1, 500) + .unwrap() + .events + .into_iter() + .filter(|e| e.kind == "session.notification.sent.1") + .map(|e| format!("{}: {}", e.data["title"], e.data["body"])) + .collect() +} + +#[tokio::test] +async fn a_one_shot_reminder_runs_at_its_time_then_completes() { + let h = Harness::new(Setup { + scripts: vec![("test/main", vec![text("CI was green overnight")])], + ..Setup::default() + }); + let id = h.session().await; + let when = now_ms() + 3_600_000; + let task = h + .runtime + .create_cron(&id, at("summarize overnight CI", when)) + .await + .unwrap(); + assert!(task.loop_id.starts_with("cron_"), "{}", task.loop_id); + assert_eq!((task.kind, task.at_ms), (LoopKind::Cron, Some(when))); + let due = task.next_due_ms.unwrap(); + assert_eq!( + h.runtime.sweep_loops(due - 1).await.unwrap(), + 0, + "not due yet" + ); + assert_eq!(h.runtime.sweep_loops(due).await.unwrap(), 1); + let ended = wait_for(&h, &id, &task.loop_id, |l| !l.active()).await; + assert_eq!(ended.status, "completed"); + assert_eq!(ended.iterations, 1); + let state = h.state(&id).await; + let row = state + .inbox + .iter() + .find(|r| r.message_id.starts_with("loopi_cron_")) + .unwrap(); + assert_eq!(row.source, "loop"); + assert!( + transcript(&h.models.requests("test/main")[0]).contains("summarize overnight CI"), + "the prompt was admitted" + ); + // An iteration that reported nothing quiet notifies under the default `on_change`. + let sent = notices(&h, &id); + assert_eq!(sent.len(), 1, "{sent:?}"); + assert!(sent[0].contains("Scheduled task"), "{sent:?}"); +} + +#[tokio::test] +async fn a_recurring_task_is_due_at_its_next_local_occurrence() { + let h = Harness::new(Setup::default()); + let id = h.session().await; + let before = now_ms(); + let task = h + .runtime + .create_cron( + &id, + CronRequest { + cron: Some("0 9 * * 1-5".into()), + prompt: "standup notes".into(), + ..CronRequest::default() + }, + ) + .await + .unwrap(); + let expected = cyber_core::cron::Cron::parse("0 9 * * 1-5") + .unwrap() + .next_after( + chrono::DateTime::from_timestamp_millis(before).unwrap(), + &chrono::Local, + ) + .unwrap() + .timestamp_millis(); + assert_eq!(task.next_due_ms, Some(expected)); + assert_eq!(task.cron.as_deref(), Some("0 9 * * 1-5")); + let listed = h.runtime.cron_tasks(&id).await.unwrap(); + assert_eq!(listed.len(), 1); +} + +#[tokio::test] +async fn invalid_schedules_are_rejected_with_the_reason() { + let h = Harness::new(Setup::default()); + let id = h.session().await; + let bad = |request: CronRequest| { + let runtime = h.runtime.clone(); + let id = id.clone(); + async move { + runtime + .create_cron(&id, request) + .await + .unwrap_err() + .to_string() + } + }; + let error = bad(CronRequest { + cron: Some("61 * * * *".into()), + prompt: "x".into(), + ..CronRequest::default() + }) + .await; + assert!( + error.contains("Invalid cron expression \"61 * * * *\""), + "{error}" + ); + let error = bad(at("x", now_ms() - 60_000)).await; + assert!(error.contains("at must be in the future"), "{error}"); + let error = bad(CronRequest { + cron: Some("* * * * *".into()), + at: Some(rfc3339(now_ms() + 60_000)), + prompt: "x".into(), + ..CronRequest::default() + }) + .await; + assert!(error.contains("exactly one of cron"), "{error}"); + assert!(h.state(&id).await.loops.is_empty()); +} + +#[tokio::test] +async fn loops_and_scheduled_tasks_share_the_per_session_cap() { + let h = Harness::new(Setup::default()); + let id = h.session().await; + let later = now_ms() + 86_400_000; + for n in 0..50 { + h.runtime + .create_cron(&id, at(&format!("task {n}"), later)) + .await + .unwrap(); + } + let error = h + .runtime + .create_cron(&id, at("one more", later)) + .await + .unwrap_err(); + assert_eq!( + error.to_string(), + "LoopLimitError: Scheduled task limit reached (50)" + ); + let error = h + .runtime + .create_loop(&id, every(60, "and a loop")) + .await + .unwrap_err(); + assert!(matches!(error, RuntimeError::LoopLimit(50)), "{error}"); +} + +#[tokio::test] +async fn cron_delete_stops_only_scheduled_tasks() { + let h = Harness::new(Setup { + scripts: vec![("test/main", vec![text("checked")])], + ..Setup::default() + }); + let id = h.session().await; + let user_loop = h + .runtime + .create_loop(&id, every(300, "deploy")) + .await + .unwrap(); + h.settle(&id).await; + let error = h + .runtime + .delete_cron(&id, &user_loop.loop_id) + .await + .unwrap_err(); + assert!( + error.to_string().contains("Unknown scheduled task"), + "{error}" + ); + assert!(loop_state(&h, &id, &user_loop.loop_id).await.active()); + let task = h + .runtime + .create_cron(&id, at("later", now_ms() + 3_600_000)) + .await + .unwrap(); + h.runtime.delete_cron(&id, &task.loop_id).await.unwrap(); + assert_eq!(loop_state(&h, &id, &task.loop_id).await.status, "stopped"); + assert!(h.runtime.cron_tasks(&id).await.unwrap().is_empty()); +} + +#[tokio::test] +async fn scheduled_tasks_belong_to_root_sessions() { + let h = Harness::new(Setup::default()); + let root = h.session().await; + let child = h + .runtime + .create_session(cyber_server::runtime::CreateSession { + directory: h.repo.display().to_string(), + model: "test/main".into(), + parent_id: Some(root.clone()), + ..Default::default() + }) + .await + .unwrap() + .id; + assert!(h.runtime.cron_tools_offered(&root)); + assert!(!h.runtime.cron_tools_offered(&child)); + let error = h + .runtime + .create_cron(&child, at("x", now_ms() + 3_600_000)) + .await + .unwrap_err(); + assert!(error.to_string().contains("root Sessions"), "{error}"); +} + +#[tokio::test] +async fn missed_scheduled_tasks_follow_the_policy_after_a_restart() { + for missed in [Missed::Skip, Missed::RunOnce] { + let h = Harness::new(Setup { + scripts: vec![("test/main", vec![text("caught up")])], + ..Setup::default() + }); + let id = h.session().await; + let when = now_ms() + 3_600_000; + let once = h + .runtime + .create_cron( + &id, + CronRequest { + missed, + ..at("reminder", when) + }, + ) + .await + .unwrap(); + let daily = h + .runtime + .create_cron( + &id, + CronRequest { + cron: Some("0 2 * * *".into()), + prompt: "nightly".into(), + missed: Missed::Skip, + ..CronRequest::default() + }, + ) + .await + .unwrap(); + // The server was down past both due times. + let now = once.next_due_ms.unwrap().max(daily.next_due_ms.unwrap()) + 60_000; + let restarted = h.restart(); + restarted.recover_loops_at(now).await.unwrap(); + let state = restarted.state(&id).await.unwrap(); + let recurring = &state.loops[&daily.loop_id]; + assert_eq!( + recurring.history.back().unwrap().outcome, + Outcome::SkippedMissed + ); + assert!(recurring.next_due_ms.unwrap() > now); + let reminder = &state.loops[&once.loop_id]; + match missed { + Missed::Skip => { + assert_eq!(reminder.status, "expired"); + assert_eq!(restarted.sweep_loops(now).await.unwrap(), 0); + } + Missed::RunOnce => { + assert!(reminder.active()); + assert_eq!(restarted.sweep_loops(now).await.unwrap(), 1); + tokio::time::timeout(Duration::from_secs(30), restarted.wait_idle(&id)) + .await + .unwrap(); + let after = restarted.state(&id).await.unwrap().loops[&once.loop_id].clone(); + assert_eq!((after.status.as_str(), after.iterations), ("completed", 1)); + } + } + } +} + +#[tokio::test] +async fn until_goal_stops_the_loop_once_the_goal_ends() { + let h = Harness::new(Setup { + scripts: vec![ + ( + "test/main", + vec![ + tools(&[("c1", "write", "{}")]), + text("goal work"), + text("loop work"), + ], + ), + ( + "test/evaluator", + vec![text("{\"verdict\": \"not_met\", \"reason\": \"x\"}")], + ), + ], + roles: vec![("evaluator", "test/evaluator")], + ..Setup::default() + }); + h.tools.set("write", Behavior::Gated); + let id = h.session().await; + let no_goal = LoopSpec { + until_goal: true, + ..every(60, "watch") + }; + let error = h + .runtime + .create_loop(&id, no_goal.clone()) + .await + .unwrap_err(); + assert!( + error.to_string().contains("--until-goal needs a Goal"), + "{error}" + ); + + let goal = h + .runtime + .set_goal( + &id, + cyber_server::runtime::goals::GoalRequest { + condition: "the build is green".into(), + ..Default::default() + }, + ) + .await + .unwrap(); + h.tools.started.notified().await; + let created = h.runtime.create_loop(&id, no_goal).await.unwrap(); + assert_eq!( + created.stop.until_goal.as_deref(), + Some(goal.goal_id.as_str()) + ); + h.runtime.clear_goals(&id, None).await.unwrap(); + h.tools.release.notify_one(); + let ended = wait_for(&h, &id, &created.loop_id, |l| !l.active()).await; + assert_eq!(ended.status, "goal_ended"); + assert_eq!( + ended.stop_reason.as_deref(), + Some(format!("goal {} cleared", goal.goal_id).as_str()) + ); +} + +#[tokio::test] +async fn notify_never_keeps_iterations_and_stops_quiet() { + let h = Harness::new(Setup { + scripts: vec![("test/main", vec![text("1")])], + ..Setup::default() + }); + let id = h.session().await; + let spec = LoopSpec { + notify: Notify::Never, + budget: Some(Budget { + max_turns: Some(1), + ..Budget::default() + }), + ..every(60, "quiet") + }; + let created = h.runtime.create_loop(&id, spec).await.unwrap(); + let ended = wait_for(&h, &id, &created.loop_id, |l| !l.active()).await; + assert_eq!(ended.status, "budget_exceeded"); + assert!(notices(&h, &id).is_empty()); +} + +#[tokio::test] +async fn a_budget_stop_notifies_once() { + let h = Harness::new(Setup { + scripts: vec![("test/main", vec![text("1")])], + ..Setup::default() + }); + let id = h.session().await; + let spec = LoopSpec { + budget: Some(Budget { + max_turns: Some(1), + ..Budget::default() + }), + ..every(60, "spend") + }; + let created = h.runtime.create_loop(&id, spec).await.unwrap(); + wait_for(&h, &id, &created.loop_id, |l| !l.active()).await; + let sent = notices(&h, &id); + assert_eq!(sent.len(), 1, "{sent:?}"); + assert!( + sent[0].contains("stopped (budget_exceeded): max_turns 1/1"), + "{sent:?}" + ); +} diff --git a/crates/cyber-tools/src/host.rs b/crates/cyber-tools/src/host.rs index b3af7806c..13900c230 100644 --- a/crates/cyber-tools/src/host.rs +++ b/crates/cyber-tools/src/host.rs @@ -1698,6 +1698,13 @@ impl ToolHost for BuiltinHost { .runtime() .is_some_and(|runtime| runtime.loop_iteration_running(&turn.session_id)) }) + .filter(|d| { + // `loops-scheduling`: scheduled tasks belong to root, non-workflow Sessions. + !tools::loops::CRON_TOOLS.contains(&d.spec.name.as_str()) + || self + .runtime() + .is_some_and(|runtime| runtime.cron_tools_offered(&turn.session_id)) + }) .filter(|d| { // `agent-teams`: only while `teams` is on, and to a lead or a non-member. tools::team::offered( diff --git a/crates/cyber-tools/src/lifecycle_hooks.rs b/crates/cyber-tools/src/lifecycle_hooks.rs index 5c014d82b..41d4622dd 100644 --- a/crates/cyber-tools/src/lifecycle_hooks.rs +++ b/crates/cyber-tools/src/lifecycle_hooks.rs @@ -48,12 +48,14 @@ const DISTINCT_UNAVAILABLE: &[&str] = &[ "FileChanged", "GoalEvaluated", "GoalCompleted", + "LoopIteration", ]; /// Lifecycle events the runtime dispatches through its narrow host port. const RUNTIME_EVENTS: &[&str] = &[ "GoalEvaluated", "GoalCompleted", + "LoopIteration", "Stop", "StopFailure", "UserPromptSubmit", diff --git a/crates/cyber-tools/src/tools/loops.rs b/crates/cyber-tools/src/tools/loops.rs index 6ddfe8d5f..56a9fbee8 100644 --- a/crates/cyber-tools/src/tools/loops.rs +++ b/crates/cyber-tools/src/tools/loops.rs @@ -1,16 +1,22 @@ //! `schedule_wakeup` (`loops-scheduling` → Self-paced loop): the model paces a `/loop` by //! naming the delay before its next iteration and whether this one found anything new. //! Offered only while an iteration of an active loop runs. +//! +//! `cron_create`, `cron_list` and `cron_delete` (`loops-scheduling` → In-session cron +//! tools): Session-scoped scheduled tasks, offered only to root Sessions outside Workflow +//! Runs. They never create a persistent schedule. use futures::future::BoxFuture; -use serde_json::json; +use serde_json::{Value, json}; use super::{Tool, ToolError, def, failed, number, text}; use crate::host::Ctx; use cyber_server::runtime::RetrySafety; -use cyber_server::runtime::loops::LoopKind; +use cyber_server::runtime::loops::{CronRequest, LoopKind, LoopState}; pub(crate) const NAME: &str = "schedule_wakeup"; +/// The scheduled task tools. +pub(crate) const CRON_TOOLS: [&str; 3] = ["cron_create", "cron_list", "cron_delete"]; /// Guidance shown to the model while an iteration runs (Context Source `core/loop`). pub(crate) const GUIDANCE_KEY: &str = "core/loop"; @@ -59,7 +65,122 @@ impl Tool for ScheduleWakeup { LoopKind::Interval => { "Recorded; the loop's interval sets the next iteration".into() } + LoopKind::Cron => "Recorded; the task's schedule sets the next iteration".into(), }) }) } } + +fn runtime(ctx: &Ctx<'_>) -> Result { + ctx.host + .runtime() + .ok_or_else(|| failed("Scheduled tasks require the runtime")) +} + +/// A task as the tools report it. +fn task(state: &LoopState) -> Value { + let mut out = json!({ + "id": state.loop_id, + "prompt": state.prompt, + "iterations": state.iterations, + "next_run": state.next_due_ms.map(cyber_core::cron::local_time_text), + }); + if let Some(cron) = &state.cron { + out["cron"] = json!(cron); + } + if let Some(at) = state.at_ms { + out["at"] = json!(cyber_core::cron::local_time_text(at)); + } + out +} + +pub(crate) struct CronCreate; + +impl Tool for CronCreate { + fn def(&self) -> cyber_server::runtime::ToolDef { + def( + CRON_TOOLS[0], + "Schedule a prompt to run later in this Session. Give either cron (a 5-field expression: minute hour day-of-month month day-of-week, in the user's local time) for a recurring task, or at (a local time such as 2026-10-03T09:00, or an RFC 3339 timestamp) for a one-shot task. The prompt is admitted when no Turn runs. missed (skip or run-once) decides what happens to runs missed while the server was down; notify (always, on_change or never) when the user is notified. Returns the task ID and its next run.", + json!({"type": "object", "required": ["prompt"], "properties": { + "cron": {"type": "string"}, + "at": {"type": "string"}, + "prompt": {"type": "string"}, + "missed": {"type": "string", "enum": ["skip", "run-once"]}, + "notify": {"type": "string", "enum": ["always", "on_change", "never"]}}}), + // A retry would create a second task. + RetrySafety::Never, + false, + ) + } + + fn run<'a>(&'a self, ctx: &'a Ctx<'a>) -> BoxFuture<'a, Result> { + Box::pin(async move { + let request: CronRequest = serde_json::from_value(ctx.inv.input.clone()) + .map_err(|error| failed(format!("Invalid cron_create input: {error}")))?; + let created = runtime(ctx)? + .create_cron(&ctx.inv.session_id, request) + .await + .map_err(|error| failed(refusal(error)))?; + Ok(task(&created).to_string()) + }) + } +} + +pub(crate) struct CronList; + +impl Tool for CronList { + fn def(&self) -> cyber_server::runtime::ToolDef { + def( + CRON_TOOLS[1], + "List this Session's active scheduled tasks with their schedule, prompt and next run.", + json!({"type": "object", "properties": {}}), + RetrySafety::ReadOnly, + true, + ) + } + + fn run<'a>(&'a self, ctx: &'a Ctx<'a>) -> BoxFuture<'a, Result> { + Box::pin(async move { + let tasks = runtime(ctx)? + .cron_tasks(&ctx.inv.session_id) + .await + .map_err(|error| failed(refusal(error)))?; + Ok(json!({"tasks": tasks.iter().map(task).collect::>()}).to_string()) + }) + } +} + +pub(crate) struct CronDelete; + +impl Tool for CronDelete { + fn def(&self) -> cyber_server::runtime::ToolDef { + def( + CRON_TOOLS[2], + "Delete one of this Session's scheduled tasks by its cron_ ID.", + json!({"type": "object", "required": ["id"], "properties": { + "id": {"type": "string"}}}), + RetrySafety::Idempotent, + false, + ) + } + + fn run<'a>(&'a self, ctx: &'a Ctx<'a>) -> BoxFuture<'a, Result> { + Box::pin(async move { + let id = text(&ctx.inv.input, "id").trim(); + runtime(ctx)? + .delete_cron(&ctx.inv.session_id, id) + .await + .map_err(|error| failed(refusal(error)))?; + Ok(json!({"deleted": id}).to_string()) + }) + } +} + +/// A runtime refusal without its error-type prefix. +fn refusal(error: cyber_server::runtime::RuntimeError) -> String { + let text = error.to_string(); + match text.split_once(": ") { + Some((tag, rest)) if tag.ends_with("Error") => rest.to_owned(), + _ => text, + } +} diff --git a/crates/cyber-tools/src/tools/mod.rs b/crates/cyber-tools/src/tools/mod.rs index aec8393ee..3581acf1b 100644 --- a/crates/cyber-tools/src/tools/mod.rs +++ b/crates/cyber-tools/src/tools/mod.rs @@ -95,6 +95,9 @@ pub(crate) fn all() -> Vec> { Box::new(messaging::SendMessage), Box::new(messaging::WatchSession), Box::new(loops::ScheduleWakeup), + Box::new(loops::CronCreate), + Box::new(loops::CronList), + Box::new(loops::CronDelete), Box::new(goal::GoalTool), Box::new(computer::Computer), Box::new(team::TeamSpawn), diff --git a/crates/cyber-tui/src/loops.rs b/crates/cyber-tui/src/loops.rs index 7ed8cd426..98bc31339 100644 --- a/crates/cyber-tui/src/loops.rs +++ b/crates/cyber-tui/src/loops.rs @@ -249,17 +249,63 @@ fn every(seconds: u64) -> String { } fn short_id(loop_id: &str) -> String { - let ulid = loop_id.trim_start_matches("lop_"); + let ulid = loop_id + .trim_start_matches("lop_") + .trim_start_matches("cron_"); ulid.get(ulid.len().saturating_sub(4)..) .unwrap_or(ulid) .to_lowercase() } -/// A picker row: the active ones stop on Enter; ended ones only inform. -fn choice(l: &Value) -> Choice { - let pace = l["interval_seconds"] +/// How a loop is paced: `every 5m`, `self-paced`, `cron 0 9 * * 1-5` or `at 09:00`. +fn pace(l: &Value) -> String { + if let Some(expression) = l["cron"].as_str() { + return format!("cron {expression}"); + } + if let Some(at) = l["at_ms"].as_i64() { + return format!("at {}", clock(at)); + } + l["interval_seconds"] .as_u64() - .map_or("self-paced".into(), |s| format!("every {}", every(s))); + .map_or("self-paced".into(), |s| format!("every {}", every(s))) +} + +/// A local time: `09:00` today, else `Oct 3 09:00`. +fn clock(ms: i64) -> String { + use chrono::TimeZone; + let Some(time) = chrono::Local.timestamp_millis_opt(ms).single() else { + return String::new(); + }; + if time.date_naive() == chrono::Local::now().date_naive() { + time.format("%H:%M").to_string() + } else { + time.format("%b %-d %H:%M").to_string() + } +} + +/// The stop conditions a loop was given, as `max 10, for 2h, until-goal`. +fn stops(l: &Value) -> Vec { + let stop = &l["stop"]; + let mut out = Vec::new(); + if let Some(max) = stop["max_iterations"].as_u64() { + out.push(format!("max {max}")); + } + if let Some(seconds) = stop["for_seconds"].as_u64() { + out.push(format!("for {}", every(seconds))); + } + if stop["until"].is_string() { + out.push("until check".into()); + } + if stop["until_goal"].is_string() { + out.push("until-goal".into()); + } + out +} + +/// A picker row's detail: status, iterations, the quiet streak (so whether the last +/// iteration was a noop), and the next run and stop conditions of an active loop; the +/// stop reason of an ended one. +fn detail(l: &Value, now_ms: i64) -> String { let status = l["status"].as_str().unwrap_or("active"); let iterations = l["iterations"].as_u64().unwrap_or(0); let quiet = l["noop_streak"].as_u64().unwrap_or(0); @@ -267,9 +313,24 @@ fn choice(l: &Value) -> Choice { if quiet > 0 { detail.push_str(&format!(" · {quiet} quiet")); } + if let Some(due) = l["next_due_ms"].as_i64().filter(|_| status == "active") { + detail.push_str(&format!(" · next in {}", until(due - now_ms))); + } + let stops = stops(l); + if status == "active" && !stops.is_empty() { + detail.push_str(&format!(" · {}", stops.join(", "))); + } if let Some(reason) = l["stop_reason"].as_str() { detail.push_str(&format!(" · {reason}")); } + detail +} + +/// A picker row: the active ones stop on Enter; ended ones only inform. +fn choice(l: &Value) -> Choice { + let pace = pace(l); + let status = l["status"].as_str().unwrap_or("active"); + let detail = detail(l, now_ms()); Choice { key: if status == "active" { l["loop_id"].as_str().unwrap_or_default().to_owned() @@ -352,4 +413,30 @@ mod tests { "stopped · 3 iterations · 2 quiet · stopped by the user" ); } + + #[test] + fn scheduled_task_rows_show_the_kind_next_run_and_stops() { + let row = choice(&json!({"loop_id": "cron_01ABCD", "kind": "cron", + "cron": "0 9 * * 1-5", "status": "active", "iterations": 0, "prompt": "standup"})); + assert_eq!(row.key, "cron_01ABCD"); + assert_eq!(row.label, "↻ abcd · cron 0 9 * * 1-5 · standup"); + let detail = detail( + &json!({"status": "active", "iterations": 4, "noop_streak": 0, "next_due_ms": 120_000, + "stop": {"max_iterations": 10, "until_goal": "goal_1"}}), + 0, + ); + assert_eq!( + detail, + "active · 4 iterations · next in 2m · max 10, until-goal" + ); + let one_shot = choice( + &json!({"loop_id": "cron_01WXYZ", "at_ms": 0, "status": "active", + "prompt": "remind me"}), + ); + assert!( + one_shot.label.starts_with("↻ wxyz · at "), + "{}", + one_shot.label + ); + } } diff --git a/docs/local-core-guide.md b/docs/local-core-guide.md index e748375cf..3dd347774 100644 --- a/docs/local-core-guide.md +++ b/docs/local-core-guide.md @@ -2198,8 +2198,9 @@ In the `/goal` panel, `e` edits, `p` pauses, `r` resumes and `c` clears the sele /loop watch CI until it is green # self-paced: the model calls schedule_wakeup /loop 2m --max 20 --for 1h --until "curl -sf https://staging/health" poll staging /loop 10m --overlap coalesce --missed run-once --max-cost 2 summarize new issues +/loop 15m --until-goal --notify never check progress # ends when the Session's Goal ends /loop list # Enter on a row stops that loop -/loop stop [lop_… | all] +/loop stop [lop_… | cron_… | all] ``` - **Iterations are queued input** (`source: "loop"`), so they never interrupt a running Turn; they run when the Session would otherwise go idle. If an iteration is still running when the next tick comes, the tick is skipped (`--overlap skip`, the default) or one tick waits behind it (`coalesce`). A slow iteration never makes ticks drift: the next one is the next multiple of the interval since the loop started. @@ -2210,15 +2211,25 @@ In the `/goal` panel, `e` edits, `p` pauses, `r` resumes and `c` clears the sele - `--for `. - `--until ""`, run before each iteration, sandboxed in the Location without a permission prompt, like `!` (timeout `loops.until_timeout_seconds`, default 60). The loop stops the first time it exits 0. - A budget: `--max-cost`, `--max-tokens`, `--max-turns` or `--timeout`, else `budgets.loop`. It is checked between iterations. + - `--until-goal`: the Session's current Goal (active or paused) is recorded when the loop starts, and the loop stops with status `goal_ended` once that Goal is met, impossible, cleared or over budget. Without a current Goal the loop is rejected. - 3 failed iterations in a row. - `/loop stop`. -- **Limits.** A Session holds at most `loops.max_per_session` (default 50) active loops. +- **Notifications.** `--notify on_change` (the default) notifies when an iteration reports `noop: false` or fails, `always` notifies every iteration, `never` none. A loop that stops `failed` or `budget_exceeded` notifies unless `never`. They are Session notifications (TUI toast, desktop while unfocused, remote devices), limited to 10 per hour per Session. +- **Limits.** A Session holds at most `loops.max_per_session` (default 50) active loops and scheduled tasks together (`Scheduled task limit reached (50)`). +- **Scheduled tasks (`cron_create`, `cron_list`, `cron_delete`).** The model can schedule a prompt for later in its own Session: + - `cron_create {cron: "0 9 * * 1-5", prompt}` runs at each occurrence of a 5-field cron expression in the user's local time (`*`, ranges, steps, lists, `JAN`–`DEC`, `SUN`–`SAT`, `@daily`…; when both day fields are set, either matches); + - `cron_create {at: "2026-10-03T09:00", prompt}` runs once (local time, or RFC 3339; within one year); + - optional `missed` (`skip`, `run-once`) and `notify`; + - a task is a Loop of kind `cron` with a `cron_` ID: it shows in `/loop list` (`cron 0 9 * * 1-5`, `at 09:00`, next run) and `/loop stop` ends it; `cron_delete` stops only `cron_` tasks, never a `/loop` you started; + - the tools are offered only to root Sessions outside Workflow Runs, and nothing the model calls creates a persistent schedule. - **Restarts.** Loops are `loop.*` events on the Session's stream (`session_loop` indexes their due times), so they survive a server restart: - an iteration cut off by the restart ends `interrupted`; - missed ticks are skipped (`--missed skip`) or one catch-up runs (`run-once`); - - a self-paced loop whose wakeup passed runs once. + - a self-paced loop whose wakeup passed runs once; + - a one-shot scheduled task whose time passed ends `expired` under `skip`, and runs once under `run-once`. +- **Hooks.** `LoopIteration` hooks receive `{loop, iteration: {n, outcome, noop, duration_ms, cost, tokens, turns, reason}}` on stdin after each iteration ends (skipped ticks excluded). They are observational. - **API:** `GET|POST /api/v1/sessions/{id}/loops` (`POST` takes `{"command": "5m check"}` or the parsed fields), `DELETE /api/v1/sessions/{id}/loops[/{loop_id}]`. -- **Not yet:** in-session cron tools, persistent `cyber loops add` schedules run by the service, notifications, the `LoopIteration` hook, `--until-goal` (not yet connected to Session goals) and `/loop` in `cyber exec`. +- **Not yet:** persistent `cyber loops add` schedules run by the service, and `/loop` in `cyber exec`. ## Workflows (P2 M2.1) diff --git a/openspec/changes/implement-m2-4-schedules/design.md b/openspec/changes/implement-m2-4-schedules/design.md new file mode 100644 index 000000000..abeff6b79 --- /dev/null +++ b/openspec/changes/implement-m2-4-schedules/design.md @@ -0,0 +1,216 @@ +## Context + +`implement-m2-4-loops` built Session loops on four pieces: + +- the `loop.*` events of the Session stream; +- the `session_loop` due-time index; +- a background sweep that admits queued iterations (`loopi__`); +- the Drain's idle exit (`loops_drain_ended`), which ends them. + +Budgets, overlap, missed-run restore and usage-limit waits for loops already work. This change adds a third Loop kind for in-session cron, and a separate scheduler for persistent schedules. That scheduler runs in the `cyber serve` process that `cyber service start` registers. + +## Decisions + +### 1. In-session cron tasks are Loops of kind `cron` + +A cron task is a Loop whose `kind` is `cron` and whose ID starts with `cron_`. It reuses every Loop mechanism: events, fold, `session_loop`, sweep, overlap, budgets, restore, the `/loop list` picker, the HTTP routes and `/loop stop `. `loop.created.1` gains three optional fields: `cron` (the expression), `at_ms` (a one-shot time) and `notify`. Exactly one of `cron` and `at_ms` is set when `kind` is `cron`, and neither otherwise. As for interval loops, `next_due_ms` is the next occurrence after the iteration starts. An occurrence that comes while an iteration still runs is skipped (overlap `skip`), so occurrences never pile up. + +A one-shot task stops `completed` after its single iteration. Iterations use `source: "loop"`, like `/loop`, so taint, usage origin and the Copilot initiator treat them as before. + +The cap is shared: `/loop` loops and cron tasks together count against `loops.max_per_session` (default 50). The error is `Scheduled task limit reached (50)`. + +### 2. Cron expressions (`cyber-core::cron`) + +- **Fields:** five, separated by whitespace: minute, hour, day of month, month and day of week. + - Each field accepts `*`, `N`, `A-B`, `*/S`, `A-B/S`, `N/S` and comma lists. + - Month names `JAN`–`DEC` and day names `SUN`–`SAT` are accepted in any case. Day of week `7` is Sunday. +- **Macros:** `@hourly`, `@daily`, `@weekly`, `@monthly` and `@yearly`. +- **Day matching:** when both day of month and day of week are restricted, a day matches if either does, as classic cron does. +- **Next occurrence:** `next_after(after, tz)` returns the first whole minute strictly after `after` that matches in `tz`. + - It is generic over `chrono::TimeZone`. The server uses `Local`; tests use UTC and fixed offsets. + - A local time skipped by a DST change does not exist, so it is skipped. + - An ambiguous local time takes its earlier instant. +- **Search bound:** the search is limited to 5 years. An expression with no occurrence in that time, such as `0 0 30 2 *`, is rejected when the task is created. +- **Errors:** `Invalid cron expression "": `. +- **`at`:** accepts RFC 3339 (`2026-10-03T09:00:00Z`, or with an offset) or a local `YYYY-MM-DDTHH:MM[:SS]`. + - A time that is not in the future is rejected with `at must be in the future`. + - A time more than one year ahead is rejected with `at must be within one year`. + +### 3. The cron tools + +- **`cron_create`:** + - input `{cron?: string, at?: string, prompt: string, missed?: "skip"|"run-once", notify?: "always"|"on_change"|"never"}`, with exactly one of `cron` and `at`; + - returns `{id, next_run}`. +- **`cron_list`:** the Session's active cron tasks, with `{id, cron|at, prompt, next_run, iterations}`. +- **`cron_delete`:** + - `{id}`; it stops one active `cron_` task of this Session; + - a `lop_` ID, or an unknown ID, fails with `Unknown scheduled task `; + - the model cannot stop the user's `/loop`. +- **Availability:** the tools are offered only to root Sessions (no `parent_id`) that are not Workflow agents (no `workflow_run_id`). + - A child or a Workflow agent has a bounded lifetime its parent owns, and a timer there would outlive its purpose. +- **Permissions:** they need no permission. Their retry safety is `Never` for `cron_create` (a retry would create a second task), `ReadOnly` for `cron_list` and `Idempotent` for `cron_delete`. + - Each task runs later in the Session's own Mode, with the authority the model already has now. + - The cap and `loops.max_iterations` bound them. +- **Persistent schedules:** nothing the model can call creates one (decision 6). + +### 4. `--until-goal` + +`/loop … --until-goal` records the ID of the Session's current Goal (active or paused) in `stop.until_goal`. With no current Goal, the loop is rejected with `--until-goal needs a Goal in this Session`. The sweep checks before each iteration, and the iteration end checks again: when that Goal's status is terminal, the loop stops with the new status `goal_ended` and the reason `goal `. + +### 5. Notifications + +- **Which statuses:** a Loop has `notify` (`always`, `on_change` (default) or `never`; `/loop --notify`, `cron_create.notify`). + - An ended iteration notifies when `notify` is `always`, or when it is `on_change` and the outcome is `failed`, or `completed` with `noop: false`. + - A stop with status `failed` or `budget_exceeded` notifies unless `notify` is `never`. +- **How:** notifications are `session.notification.sent.1` events through `record_notification`. Clients already show them (TUI toast and desktop) and relay them to remote devices. +- **Rate limit:** the per-Session limit (10 per hour) applies. A notification past the limit is dropped, as for Goals, because the loop events still record the outcome. +- **Text:** title `Loop ` or `Cron `, body `: `. + +### 6. Persistent schedules (`runtime/schedules`) + +**Storage.** A schedule is its own aggregate, keyed by its `cron_` ID. The `schedule.*` events are projected into new tables (new migration files): + +```sql +CREATE TABLE schedule ( + id TEXT PRIMARY KEY, name TEXT NOT NULL, cron TEXT NOT NULL, directory TEXT NOT NULL, + spec TEXT NOT NULL, -- JSON: prompt, agent, mode, target, notify, missed, budget, jitter_ms + status TEXT NOT NULL, -- active | paused | budget_exceeded | deleted + next_due_ms INTEGER, inflight TEXT, -- run ID in flight + runs INTEGER NOT NULL DEFAULT 0, cost_usd REAL NOT NULL DEFAULT 0, + tokens INTEGER NOT NULL DEFAULT 0, turns INTEGER NOT NULL DEFAULT 0, + created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL) STRICT; +CREATE TABLE schedule_run ( + id TEXT PRIMARY KEY, schedule_id TEXT NOT NULL REFERENCES schedule(id) ON DELETE CASCADE, + n INTEGER NOT NULL, due_ms INTEGER NOT NULL, started_ms INTEGER, ended_ms INTEGER, + session_id TEXT, message_id TEXT, outcome TEXT NOT NULL, noop INTEGER NOT NULL DEFAULT 0, + cost_usd REAL NOT NULL DEFAULT 0, reason TEXT) STRICT; +``` + +The tables are not named `schedule_occurrence`, which the reserved-budget collector already watches. Schedule budgets are soft (decision 9). + +**Events.** + +| Event | Payload | +|---|---| +| `schedule.created.1` | `{schedule_id, name, cron, directory, prompt, agent?, mode, target: new_session\|{session_id}, notify, missed, budget?, jitter_ms, created_ms, next_due_ms}` | +| `schedule.updated.1` | `{schedule_id, status: active\|paused\|budget_exceeded\|deleted, reason?, next_due_ms?}` | +| `schedule.run.1` | `{schedule_id, run_id, n, phase: started\|reported\|ended, due_ms, session_id?, message_id?, outcome?, noop, duration_ms, cost, tokens, turns, reason?, next_due_ms?}` | + +`schedule.run.1` is the single durable run record the spec names: + +- the `started` phase is appended before the run is admitted; +- `reported` records `schedule_wakeup`'s `noop` and `reason`; +- `ended` carries the outcome: `completed`, `failed`, `interrupted`, `refused`, `skipped_overlap` or `skipped_missed`. + +`rm` appends `updated {deleted}`. The row is kept for its history, and every listing hides it. + +**Lifecycle.** + +1. A sweep every 5 s (plus nudges) visits active schedules with `next_due_ms <= now`. +2. A schedule with a run in flight records `skipped_overlap` and moves on. +3. Otherwise the gate runs (decision 7). When it refuses, the run ends `refused` with the reason. +4. The target Session is prepared: + - `new_session`: a new root Session in `directory`, with the schedule's agent and Mode, `unattended: true`, and the title ` · `; + - `session_id`: the Session must exist, be a root Session in `directory`, and not be archived. When its Mode differs from the schedule's, it is switched first. +5. The prompt is admitted queued with `source: "loop"` and the deterministic ID `schedi__`, so a retry after a crash is idempotent. +6. The Drain's idle exit (`schedules_drain_ended`, next to the loop hook) ends the run: + - the outcome comes from the Drain status; + - `noop` comes from the last `reported` phase; + - cost, tokens and turns are the Session's totals minus those at admission. + + Then the budget is checked, notifications go out (decision 8), and the `ScheduleRun` hook fires. + +**Restore.** + +- A started run whose message was promoted, in a Session that does not run, ends `interrupted`. +- A run that was never promoted stays queued. +- A due time that passed while the server was down follows the schedule's `missed` policy, as interval loops do: `skip` records `skipped_missed` and moves to the next occurrence; `run-once` runs once. + +**Next run with jitter.** `jitter_ms` is fixed when the schedule is created: the first 8 bytes of SHA-256 of the ID, modulo `loops.jitter_seconds × 1000` (default 60 s; `0` disables it). It is stored, so it never changes. The next run is `cron.next_after(now − jitter) + jitter`, which is always in the future. `list` and `show` print it. + +**CLI** (`cyber loops`, through the background server like `cyber teams`): + +``` +cyber loops add --cron "" [--name N] [--dir P] [--agent A] [--mode M] [--new-session|--session ID] + [--notify always|on_change|never] [--missed skip|run-once] + [--max-cost USD] [--max-tokens N] [--max-turns N] [--timeout DUR] "" +cyber loops list | show | pause | resume | run | rm +``` + +- **When the server is down:** `add` warns, when no healthy server was registered before it ran, that schedules run only while the Cyber service runs and that `cyber service start` starts it. + - This replaces the spec's `cyber service install`, which does not exist: the service is the registered `cyber serve`, started on demand. +- **`run`:** runs now, outside the cron schedule, through the same gate. +- **Inside an agent subprocess:** `add`, `resume` and `run` are refused when `CYBER_SESSION_ID` is set, as `cyber features` does for `computer_use`. The model cannot create or wake a persistent schedule. + - The routes already require the owner credential, which model subprocesses never receive. + +**HTTP.** + +- `GET|POST /api/v1/schedules` +- `GET|DELETE /api/v1/schedules/{id}` +- `POST /api/v1/schedules/{id}/pause|resume|run` + +They are not in the IDE token scope. The error types are `ScheduleNotFoundError` and `InvalidRequestError`. + +### 7. The unattended gate + +Every scheduled run checks, at creation (so that `add` fails early) and again at run time, because config, trust and checkouts change: + +1. **The directory:** + - it must exist and be a directory, and its configuration must load (a load error refuses); + - its checkout must be trusted (`TrustReport.trusted`: nothing to approve, or the approved digest). Otherwise: `Refused: is not trusted; run cyber trust inspect there`. +2. **`bypass`:** the Mode may be `bypass` only when `loops.allow_bypass` is `true` and the setting came from a `global:` or `managed:` layer (`Resolved.sources["/loops/allow_bypass"]`). + - A project, local, environment, profile or `--config` layer cannot enable it, whether or not the checkout is trusted. + - The server's own `bypass` gate (`admit_mode`: a sandbox or `--dangerously-bypass-permissions`) and org policy still apply on top. +3. **Asks:** in a scheduled run, an `ask` under `dont-ask`, or an `ask` that no approver could answer, is denied with `Denied: no approver in unattended schedule`, and the Drain continues. The tool host uses this message while a `schedi_` input is the Session's current run. + +A refused run notifies (unless `notify` is `never`) and does not pause the schedule. The next occurrence tries again. + +### 8. Notifications for scheduled runs + +- **Rules:** the same rules as decision 5, applied to the run's outcome. A `refused` run counts as a failure. +- **In the Session:** a notification is recorded in the run's Session (`record_notification`), so clients and remote devices see it. +- **On the desktop:** usually no client is attached, so the server also calls a `DesktopNotifier` port. `cyber-app` wires an OS notifier: + - macOS runs `osascript` with title and body passed as `argv`, never inlined in the script; + - Linux runs `notify-send`; + - other platforms use none. + - It is best effort and never blocks the run. Tests inject a recording notifier. + +### 9. Budgets across scheduled runs + +- **Where the budget comes from:** the `add` flags, else `Budget::from_config(directory config, "loop")`. +- **What is checked:** before each run, the accumulated `cost_usd`, `tokens` and `turns`, and `created_ms + max_wall_seconds`. After each run, the accumulated totals are checked again. +- **When it is exceeded:** `schedule.updated {budget_exceeded, reason}`, a notification, and no further runs. The budget is fixed at `add`, so `resume` refuses a `budget_exceeded` schedule; the user removes it and adds a new one. +- **Each run's Session:** a new Session also gets the directory's `budgets.session` as usual. + +### 10. Usage-limit waits + +`unattended_marker` also returns true when the Session's last promoted input is a `schedi_` row. A scheduled run that resumes an attended Session therefore waits for the reset instead of failing. New run Sessions are already `unattended: true`. The schedule's own `max_wall_seconds` is not a deadline of the wait: it is checked between runs. + +### 11. Hooks + +`LoopIteration` and `ScheduleRun` join the runtime lifecycle events. Both are observational: decisions are ignored and failures are logged. + +- **`LoopIteration`** fires after `loop.iteration.ended.1` commits. It receives `{loop: , iteration: {n, outcome, noop, duration_ms, cost, reason}}`. +- **`ScheduleRun`** fires after the run's `ended` phase commits, in the run's Session. It receives `{schedule: {id, name, cron, directory}, run: {run_id, n, outcome, noop, duration_ms, cost, reason}}`. + - A `refused` run has no Session, so its `ScheduleRun` has none and is not dispatched; its `schedule.run.1` record remains. + +## Spec deltas + +The spec deltas are in `specs/loops-scheduling/spec.md`: + +- **Persistent local schedules:** `cyber service start` replaces `cyber service install`. Management from an agent subprocess is refused. +- **Unattended Mode for schedules:** trusted directories, the re-check at every run, `refused`, and the scope of the deny message. +- **In-session cron tools:** root Sessions only, the `at` bounds, `cron_delete` limited to `cron_` tasks, and `notify`. +- **Restore on resume:** a one-shot task whose time passed under `skip` ends `expired`. This includes the restore rules of `implement-m2-4-loops`. +- **Completion notifications:** `schedule_wakeup` during scheduled runs, `/loop --notify`, and the rate limit. + +## Risks / Trade-offs + +- **[The model schedules work in its own Session]** That work is bounded: + - by the shared cap of 50 and `loops.max_iterations`; + - by the Session's Mode and budget, which still apply to every Turn; + - by `/loop stop`, which the user can always use. +- **[A schedule configured with `bypass`]** It needs a user- or managed-layer opt-in and the server's own `bypass` gate, both re-checked at every run. +- **[A checkout edited between runs]** The trust digest changes and the next run is refused until the user approves it again. +- **[Desktop notifications spawn a process]** Only for scheduled runs, with arguments passed as `argv` and a 5 s timeout. +- **[The scheduler lives in `cyber serve`]** Schedules run only while it runs. `add` says so. A launchd or systemd unit is future work. diff --git a/openspec/changes/implement-m2-4-schedules/proposal.md b/openspec/changes/implement-m2-4-schedules/proposal.md new file mode 100644 index 000000000..9c6406e40 --- /dev/null +++ b/openspec/changes/implement-m2-4-schedules/proposal.md @@ -0,0 +1,61 @@ +## Why + +`implement-m2-4-loops` shipped the Session loops users type (`/loop`). The rest of M2.4 is still missing: the model cannot schedule a reminder for later, nothing runs while every terminal is closed, and loops have no hooks, notifications or `--until-goal`. `cyber loops` still answers "not available in this build yet". + +## What Changes + +The remaining (P2) `loops-scheduling` requirements, delivered in two pull requests. + +**Part A — in-session cron** + +- **In-session cron tools:** the model gets `cron_create` (a 5-field cron expression in local time, or `at` for one shot), `cron_list` and `cron_delete`. A task is a `cron` Loop of the Session with a `cron_` ID. It shares the `loops.max_per_session` cap (default 50) with `/loop`. +- **Restore on resume:** cron tasks are restored like loops. Missed runs follow the missed-run policy. A one-shot task whose time passed under `skip` ends `expired`. +- **Loop status visibility:** `/loop list` and `GET /sessions/{id}/loops` show the `cron` kind, its expression or time, and the next run time. +- **Loop events and hooks:** cron tasks use the `loop.*` events. The `LoopIteration` hook fires when an iteration ends. +- **Loop stop conditions:** `--until-goal`. +- **Completion notifications:** iterations that report `noop: false` or fail notify, and so do loop stops for `failed` or `budget_exceeded`. `/loop --notify always|on_change|never` controls them. + +**Part B — persistent schedules** + +- **Persistent local schedules:** `cyber loops add|list|show|pause|resume|run|rm` manage schedules stored in the database. The `cyber service` server runs them with no client open. Each run creates a new Session or resumes one and records its outcome. +- **Unattended Mode for schedules:** the default Mode is `dont-ask`. `bypass` needs `loops.allow_bypass` from user or managed config. Asks are denied with `Denied: no approver in unattended schedule`. Runs happen only in trusted directories. +- **Jitter:** each schedule gets a deterministic offset of up to `loops.jitter_seconds` (default 60). It is included in the next run time. +- **Completion notifications** for scheduled runs: in the run's Session, and on the desktop through the server. +- **Budgets for loops** across scheduled runs. +- **Loop events and hooks:** `schedule.run.1` and the `ScheduleRun` hook. +- **Usage limit waits:** a scheduled run counts as unattended. + +Out of scope: **Cloud handoff of schedules** (P3, `cyber loops promote`). + +Spec deltas (`loops-scheduling`) are listed in `design.md` → Spec deltas: + +- **Persistent local schedules:** there is no `cyber service install`, so the warning offers `cyber service start`. An agent subprocess cannot manage schedules. +- **Unattended Mode for schedules:** the trusted-directory rule, re-checking at every run, and the `refused` outcome. +- **In-session cron tools:** offered only to root Sessions outside Workflow Runs. A one-shot time in the past is rejected. +- **Restore on resume:** a missed one-shot cron task under `skip` expires. +- **Completion notifications:** scheduled runs report `noop` through `schedule_wakeup`, `/loop` accepts `--notify`, and the per-Session notification rate limit applies. + +## Impact + +- **`cyber-core`:** + - a `cron` module with the parser and the next-occurrence logic (time-zone generic); + - `loops` (the `--until-goal` and `--notify` flags, and the `jitter_seconds` and `allow_bypass` settings); + - `loops::allow_bypass`, which reads the setting from user or managed layers only. +- **`cyber-store`:** new migrations for `schedule` and `schedule_run`. Part A needs none: cron tasks reuse `session_loop`. +- **`cyber-server`:** + - `runtime/loops` (the cron kind, `--until-goal`, notifications and the `LoopIteration` hook); + - a new `runtime/schedules` (records, projector, sweep, run lifecycle, restore, desktop notifier port); + - `/api/v1/schedules` routes, OpenAPI and the SDK; + - the usage-wait unattended marker. +- **`cyber-tools`:** + - the `cron_create`, `cron_list` and `cron_delete` tools; + - `schedule_wakeup` offered during scheduled runs; + - the schedule deny message; + - `LoopIteration` and `ScheduleRun` as runtime lifecycle events. +- **`cyber-cli`:** `cyber loops`, and the desktop notifier wiring in `cyber-app`. +- **`cyber-tui`:** cron rows in `/loop list`, and `/loop` help. +- **Docs:** + - `docs/local-core-guide.md`; + - `docs/cli.md`; + - `README.md`; + - `ROADMAP.md` (M2.4 status). diff --git a/openspec/changes/implement-m2-4-schedules/specs/loops-scheduling/spec.md b/openspec/changes/implement-m2-4-schedules/specs/loops-scheduling/spec.md new file mode 100644 index 000000000..2eceb0251 --- /dev/null +++ b/openspec/changes/implement-m2-4-schedules/specs/loops-scheduling/spec.md @@ -0,0 +1,76 @@ +## MODIFIED Requirements + +### Requirement: In-session cron tools +(P2) The model SHALL have `cron_create` (5-field cron expression in the user's local time zone, or `at` ISO timestamp for one-shot, plus prompt), `cron_list` and `cron_delete` tools, creating Session-scoped scheduled tasks (`cron_` IDs) with at most `loops.max_per_session` (default 50) per Session. Invalid expressions SHALL be rejected with the parse error. The tools SHALL be offered only to root Sessions that are not Workflow agents. A scheduled task SHALL be a Loop of kind `cron` that shares the per-Session cap with `/loop` loops. An `at` time that is not in the future, or is more than one year ahead, SHALL be rejected. `cron_delete` SHALL stop only `cron_` tasks of its Session. `cron_create` SHALL accept `missed` (`skip` or `run-once`) and `notify` (`always`, `on_change` or `never`). The model SHALL NOT be able to create a persistent schedule. + +#### Scenario: Reminder +- **WHEN** the model calls `cron_create` with `at: "2026-10-03T09:00"` and prompt `summarize overnight CI` +- **THEN** the prompt is admitted to the Session at that time + +#### Scenario: Limit +- **WHEN** a Session already has 50 scheduled tasks +- **THEN** `cron_create` fails with `Scheduled task limit reached (50)` + +#### Scenario: Invalid expression +- **WHEN** the model calls `cron_create` with `cron: "61 * * * *"` +- **THEN** the call fails with `Invalid cron expression "61 * * * *"` and the reason + +#### Scenario: A user loop is out of reach +- **WHEN** the model calls `cron_delete` with the ID of a `/loop` the user started +- **THEN** the call fails with `Unknown scheduled task ` and the loop keeps running + +### Requirement: Restore on resume +(P2) Session-scoped Loops and cron tasks SHALL be persisted with the Session and restored on resume, server restart or handoff, unless expired. Iterations missed while the Session was not running SHALL follow the missed-run policy (default `skip`; `run-once` admits a single catch-up iteration). A self-paced Loop whose wakeup time passed while the server was not running SHALL run one iteration under either policy. An iteration that was running when the server stopped SHALL end with outcome `interrupted`. A recurring cron task that missed occurrences SHALL resume at its next occurrence under `skip`. A one-shot cron task whose time passed under `skip` SHALL end with status `expired`. + +#### Scenario: Missed runs while offline +- **WHEN** a 1-hour loop was not running for 5 hours with policy `run-once` +- **THEN** on restore exactly one catch-up iteration runs, then the normal schedule resumes + +#### Scenario: Skip after restart +- **WHEN** a 5-minute loop with policy `skip` was not running for 1 hour +- **THEN** on restore no catch-up iteration runs and the next iteration is admitted at the next 5-minute tick + +#### Scenario: Missed one-shot reminder +- **WHEN** a cron task with `at` 09:00 and policy `skip` is restored at 11:00 +- **THEN** it ends with status `expired` and its prompt is not admitted + +### Requirement: Persistent local schedules +(P2) `cyber loops add --cron "" [--dir ] [--agent ] [--mode ] [--new-session|--session ] ""` SHALL create a persistent schedule stored in the database and executed by the `cyber service` daemon even when no client is open. `cyber loops list`, `show `, `pause `, `resume `, `run ` (run now) and `rm ` SHALL manage them. Each scheduled run SHALL create or resume a Session and record its outcome. `add`, `resume` and `run` SHALL be refused inside an agent subprocess (`CYBER_SESSION_ID` set), and the schedule routes SHALL require the owner credential. + +#### Scenario: Nightly review without open terminal +- **WHEN** a schedule `0 2 * * *` exists and the user's terminal is closed but the daemon runs +- **THEN** at 02:00 a Session runs the prompt and its result is recorded + +#### Scenario: Daemon not running +- **WHEN** the user adds a persistent schedule and no Cyber service was running +- **THEN** the command warns that schedules run only while the service runs and offers `cyber service start` + +#### Scenario: Agent subprocess +- **WHEN** a model's shell command runs `cyber loops add --cron "* * * * *" "x"` +- **THEN** the command is refused and no schedule is created + +### Requirement: Unattended Mode for schedules +(P2) Persistent schedules SHALL run in the Mode set on the schedule (default `dont-ask`), and SHALL NOT run in `bypass` unless `loops.allow_bypass` is true in user or managed config. Permission asks in `dont-ask` SHALL be denied with feedback so the run can continue. A project, local, environment, profile or command-line layer SHALL NOT enable `loops.allow_bypass`. A schedule SHALL run only in an existing directory whose checkout is trusted. The directory, the trust and the Mode SHALL be checked when the schedule is added and again before every run. A run that fails a check SHALL end with outcome `refused` and its reason. Asks that no approver can answer during a scheduled run, in any Mode, SHALL be denied with the same message. + +#### Scenario: Ask denied in schedule +- **WHEN** a scheduled run attempts a command needing approval under `dont-ask` +- **THEN** the command is denied and the model receives `Denied: no approver in unattended schedule` + +#### Scenario: Project config cannot allow bypass +- **WHEN** a trusted checkout's `cyber.jsonc` sets `loops.allow_bypass: true` and the user adds a schedule with `--mode bypass` +- **THEN** the schedule is rejected because `bypass` needs `loops.allow_bypass` in user or managed config + +#### Scenario: Untrusted checkout +- **WHEN** a schedule's directory has project definitions that were changed after approval +- **THEN** the next run ends `refused`, the user is notified, and no Session runs the prompt + +### Requirement: Completion notifications +(P2) Loop iterations and scheduled runs that report `noop: false` or fail SHALL produce a notification (desktop, and remote devices when remote-control is connected) with the schedule name and a one-line result; schedule-level `notify` SHALL accept `always`, `on_change` (default) or `never`. `/loop` and `cron_create` SHALL accept the same `notify` setting. A scheduled run SHALL report `noop` through `schedule_wakeup`, which SHALL be offered during scheduled runs; its delay SHALL be ignored there. A Loop stop with status `failed` or `budget_exceeded` SHALL notify unless `notify` is `never`. Notifications recorded in a Session SHALL follow the Session's notification rate limit. + +#### Scenario: Failure notified +- **WHEN** a nightly scheduled run fails +- **THEN** the user receives a notification with the error + +#### Scenario: Quiet run +- **WHEN** a scheduled run calls `schedule_wakeup` with `noop: true` and its schedule has `notify: on_change` +- **THEN** no notification is sent and the run is recorded with `noop: true` diff --git a/openspec/changes/implement-m2-4-schedules/tasks.md b/openspec/changes/implement-m2-4-schedules/tasks.md new file mode 100644 index 000000000..64e646113 --- /dev/null +++ b/openspec/changes/implement-m2-4-schedules/tasks.md @@ -0,0 +1,39 @@ +## 1. Part A — core + +- [x] 1.1 `cyber-core::cron`: the 5-field parser (ranges, steps, lists, names, macros, day OR rule), time-zone-generic `next_after` (DST gaps and folds), the 5-year bound, and the `at` parser; unit tests for every rule and error. +- [x] 1.2 `cyber-core::loops`: `--until-goal` and `--notify` flags, `Notify`, and the shared `Scheduled task limit reached` error; grammar tests. + +## 2. Part A — runtime + +- [x] 2.1 The `cron` Loop kind: the `cron` and `at_ms` fields on `loop.created.1`, validation, fold, next due after each iteration, one-shot completion, and `create_cron`, `cron_tasks` and `delete_cron`. +- [x] 2.2 Restore: missed occurrences of cron tasks under `skip` and `run-once`; a missed one-shot under `skip` ends `expired`. +- [x] 2.3 `--until-goal`: capture the current Goal, check it before and after each iteration, and the `goal_ended` status. +- [x] 2.4 Notifications for iterations and stops under `notify`, through `record_notification`. +- [x] 2.5 The `LoopIteration` hook after `loop.iteration.ended.1`. +- [x] 2.6 Runtime tests: cron reminder at its time, cap shared with `/loop`, recurring next due, restore under skip and run-once, expired one-shot, until-goal stop, notifications by policy, and the `LoopIteration` hook payload. + +## 3. Part A — tools and surfaces + +- [x] 3.1 `cron_create`, `cron_list` and `cron_delete`, offered only to root non-workflow Sessions, with `cron_delete` limited to `cron_` tasks; tool tests. +- [x] 3.2 `GET /sessions/{id}/loops` returns the cron fields; OpenAPI and the regenerated SDK. +- [x] 3.3 TUI: `/loop list` rows show the kind (`every 5m`, `self-paced`, `cron 0 9 * * 1-5`, `at 09:00`) the next run time and the stop conditions; row tests. +- [x] 3.4 Docs: the local core guide (cron tools, `--until-goal`, `--notify`, `LoopIteration`) and the ROADMAP M2.4 status. + +## 4. Part B — persistent schedules + +- [ ] 4.1 Migrations `schedule` and `schedule_run`; the `schedule.created.1`, `schedule.updated.1` and `schedule.run.1` events, validation and projector. +- [ ] 4.2 Settings `loops.jitter_seconds` and `loops.allow_bypass` (user and managed layers only), with tests that a project layer cannot enable it. +- [ ] 4.3 Create, list, show, pause, resume, run now and remove on `Runtime`, with the gate (directory, trust, Mode) at creation. +- [ ] 4.4 The sweep: due runs with jitter; overlap skip; the gate at run time with the `refused` outcome; new or resumed Session (switching its Mode); queued admission `schedi__`. +- [ ] 4.5 Run end at the Drain's idle exit: outcome, `noop` from `schedule_wakeup`, deltas, budget stop, notifications (Session and `DesktopNotifier`), and the `ScheduleRun` hook. +- [ ] 4.6 Restore (interrupted runs, missed policy) and the background sweep, wired in `cyber-app` with the OS notifier. +- [ ] 4.7 `Denied: no approver in unattended schedule` for asks in scheduled runs; the `unattended_marker` for `schedi_` runs. +- [ ] 4.8 Routes `/api/v1/schedules…`, OpenAPI, the SDK, and HTTP tests. +- [ ] 4.9 `cyber loops add|list|show|pause|resume|run|rm`, the service warning, refusal inside agent subprocesses, CLI tests, and `docs/cli.md`. +- [ ] 4.10 Runtime tests: a nightly run with no client, overlap skip, jitter determinism and the next run, untrusted directory refused, bypass refused without the user opt-in, a dont-ask ask denied with the schedule message, budget stop with notification, interrupted run restore, missed run-once, and a usage-limit wait in a resumed Session. +- [ ] 4.11 Docs: the local core guide (schedules, unattended rules, notifications), the README, and the ROADMAP M2.4 status. + +## 5. Verification + +- [ ] 5.1 `cargo fmt`, clippy with `-D warnings`, touched-crate nextest, OpenSpec validate, `spec_lint`, `spec_inventory`, and `help-markdown` equal to `docs/cli.md`. +- [ ] 5.2 Live: a cron reminder and a nightly schedule against a real model (needs keys). diff --git a/sdk/openapi.json b/sdk/openapi.json index e42de3066..b85522b24 100644 --- a/sdk/openapi.json +++ b/sdk/openapi.json @@ -15439,12 +15439,28 @@ "format": "uint64", "minimum": 0 }, + "cron": { + "type": [ + "string", + "null" + ] + }, + "at_ms": { + "type": [ + "integer", + "null" + ], + "format": "int64" + }, "overlap": { "$ref": "#/components/schemas/Overlap" }, "missed": { "$ref": "#/components/schemas/Missed" }, + "notify": { + "$ref": "#/components/schemas/Notify" + }, "stop": { "$ref": "#/components/schemas/StopConditions" }, @@ -15562,6 +15578,7 @@ "prompt", "overlap", "missed", + "notify", "stop", "iteration_cap", "status", @@ -15578,10 +15595,19 @@ "description": "A loop as the Session state folds it." }, "LoopKind": { - "type": "string", - "enum": [ - "interval", - "self_paced" + "oneOf": [ + { + "type": "string", + "enum": [ + "interval", + "self_paced" + ] + }, + { + "type": "string", + "const": "cron", + "description": "A scheduled task the model created with `cron_create` (`cron_` ID)." + } ] }, "Overlap": { @@ -15600,6 +15626,15 @@ ], "description": "What to do with ticks missed while the Session was not running." }, + "Notify": { + "type": "string", + "enum": [ + "always", + "on_change", + "never" + ], + "description": "When a loop's iterations notify the user (`loops-scheduling` → Completion\nnotifications): `on_change` notifies iterations that report `noop: false` or fail." + }, "StopConditions": { "type": "object", "properties": { @@ -15624,6 +15659,13 @@ "string", "null" ] + }, + "until_goal": { + "type": [ + "string", + "null" + ], + "description": "`--until-goal`: the Goal whose terminal status ends the loop." } }, "description": "What stops a loop besides `/loop stop`." @@ -15803,6 +15845,10 @@ "null" ] }, + "until_goal": { + "type": "boolean", + "description": "Stop when the Session's current Goal reaches a terminal status." + }, "overlap": { "$ref": "#/components/schemas/Overlap", "default": "skip" @@ -15811,6 +15857,10 @@ "$ref": "#/components/schemas/Missed", "default": "skip" }, + "notify": { + "$ref": "#/components/schemas/Notify", + "default": "on_change" + }, "budget": { "anyOf": [ { diff --git a/sdk/typescript/src/generated/types.ts b/sdk/typescript/src/generated/types.ts index b85976bbd..95c503c3f 100644 --- a/sdk/typescript/src/generated/types.ts +++ b/sdk/typescript/src/generated/types.ts @@ -3449,7 +3449,7 @@ export type LongestSession = { duration_ms: number; }; -export type LoopKind = "interval" | "self_paced"; +export type LoopKind = "interval" | "self_paced" | "cron"; /** A loop to create. `interval_seconds: None` makes it self-paced. */ export type LoopSpec = { @@ -3458,8 +3458,11 @@ export type LoopSpec = { max_iterations?: number | null; for_seconds?: number | null; until?: string | null; + /** Stop when the Session's current Goal reaches a terminal status. */ + until_goal?: boolean; overlap?: Overlap; missed?: Missed; + notify?: Notify; budget?: Budget | null; }; @@ -3469,8 +3472,11 @@ export type LoopState = { kind: LoopKind; prompt: string; interval_seconds?: number | null; + cron?: string | null; + at_ms?: number | null; overlap: Overlap; missed: Missed; + notify: Notify; stop: StopConditions; budget?: Budget | null; iteration_cap: number; @@ -3932,6 +3938,12 @@ export type NoticePolicy = { bypass?: BypassSetting; }; +/** + * When a loop's iterations notify the user (`loops-scheduling` → Completion + * notifications): `on_change` notifies iterations that report `noop: false` or fail. + */ +export type Notify = "always" | "on_change" | "never"; + /** Lossless JSON decimal integer. Never accepts JSON numbers or noncanonical strings. */ export type Offset = string; @@ -5741,6 +5753,8 @@ export type StopConditions = { max_iterations?: number | null; for_seconds?: number | null; until?: string | null; + /** `--until-goal`: the Goal whose terminal status ends the loop. */ + until_goal?: string | null; }; export type StopReason = "user" | "budget" | "lead_deleted"; From 638885b6fc81162ef215d25ff3482e79416dec4c Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Fri, 20 Nov 2026 09:13:53 -0400 Subject: [PATCH 2/4] Add persistent cyber loops schedules run by the service Schedules are their own event streams (schedule.created/updated/run), projected into new schedule and schedule_run tables. The served App runs a sweep that starts due runs through an unattended gate, creates a new unattended Session per run (or resumes a root Session switched to the schedule's Mode) and admits the prompt queued as schedi__; the Drain's idle exit records the outcome. Transitions are decided inside the writer transaction so a run is never started or ended twice. The gate refuses missing or untrusted directories, refuses bypass unless loops.allow_bypass comes from user or managed config, and is re-checked before every run. Asks in scheduled runs are denied with 'Denied: no approver in unattended schedule'. cyber loops add/resume/run are refused inside agent subprocesses. Adds deterministic per-schedule jitter (loops.jitter_seconds), notify policies with Session and desktop notifications (osascript/notify-send, text passed as argv), budgets across runs, restore of interrupted and missed runs, schedule_wakeup noop reporting during scheduled runs, the ScheduleRun hook, and usage-limit waits for scheduled runs. Exposes /api/v1/schedules routes, regenerates the OpenAPI document, SDK and docs/cli.md, and updates the guide, features, README and roadmap. --- README.md | 2 +- ROADMAP.md | 2 +- crates/cyber-app/src/desktop_notifier.rs | 91 ++ crates/cyber-app/src/lib.rs | 28 +- crates/cyber-app/tests/schedules.rs | 202 +++ crates/cyber-cli/src/cli.rs | 5 + crates/cyber-cli/src/commands/loops.rs | 417 +++++ crates/cyber-cli/src/commands/mod.rs | 2 + crates/cyber-cli/src/commands/teams.rs | 2 +- crates/cyber-cli/tests/loops_cli.rs | 194 +++ crates/cyber-core/src/loops.rs | 57 + crates/cyber-server/src/http/error.rs | 1 + crates/cyber-server/src/http/mod.rs | 2 + crates/cyber-server/src/http/openapi.rs | 60 + crates/cyber-server/src/http/schedules.rs | 101 ++ crates/cyber-server/src/runtime/drain.rs | 2 + crates/cyber-server/src/runtime/events.rs | 2 + crates/cyber-server/src/runtime/host.rs | 11 + .../src/runtime/loops/schedule.rs | 21 +- crates/cyber-server/src/runtime/mod.rs | 11 + .../src/runtime/schedules/gate.rs | 93 ++ .../cyber-server/src/runtime/schedules/mod.rs | 378 +++++ .../src/runtime/schedules/records.rs | 577 +++++++ .../cyber-server/src/runtime/schedules/run.rs | 830 ++++++++++ crates/cyber-server/src/runtime/usage_wait.rs | 3 +- crates/cyber-server/tests/schedules.rs | 449 ++++++ crates/cyber-server/tests/support/mod.rs | 13 + crates/cyber-server/tests/usage_limit.rs | 40 + .../migrations/20261120000000_schedules.sql | 43 + crates/cyber-store/src/migrate.rs | 4 + crates/cyber-tools/src/host.rs | 52 +- crates/cyber-tools/src/lifecycle_hooks.rs | 2 + crates/cyber-tools/src/permissions/engine.rs | 8 +- crates/cyber-tools/src/permissions/mod.rs | 4 +- crates/cyber-tools/src/tools/loops.rs | 20 +- docs/cli.md | 116 ++ docs/features.md | 2 +- docs/local-core-guide.md | 28 +- .../implement-m2-4-schedules/design.md | 10 +- .../changes/implement-m2-4-schedules/tasks.md | 24 +- scripts/generate_sdk.py | 1 + sdk/openapi.json | 1428 +++++++++++++---- sdk/typescript/src/generated/operations.ts | 154 ++ sdk/typescript/src/generated/types.ts | 91 ++ 44 files changed, 5203 insertions(+), 380 deletions(-) create mode 100644 crates/cyber-app/src/desktop_notifier.rs create mode 100644 crates/cyber-app/tests/schedules.rs create mode 100644 crates/cyber-cli/src/commands/loops.rs create mode 100644 crates/cyber-cli/tests/loops_cli.rs create mode 100644 crates/cyber-server/src/http/schedules.rs create mode 100644 crates/cyber-server/src/runtime/schedules/gate.rs create mode 100644 crates/cyber-server/src/runtime/schedules/mod.rs create mode 100644 crates/cyber-server/src/runtime/schedules/records.rs create mode 100644 crates/cyber-server/src/runtime/schedules/run.rs create mode 100644 crates/cyber-server/tests/schedules.rs create mode 100644 crates/cyber-store/migrations/20261120000000_schedules.sql diff --git a/README.md b/README.md index 0b834224b..7cd4a45aa 100644 --- a/README.md +++ b/README.md @@ -180,7 +180,7 @@ Cyber Code has working features in each area below, but it is not at full featur Other limits to consider: - **Acceptance is ongoing:** the full local-model baseline, Windows enforcement and several P1 migration, memory and code-intelligence paths remain open. -- **Automation has edges:** [reserved budgets](docs/reserved-budgets.md) currently support bounded official OpenAI Responses requests; ChatGPT/Copilot subscription models use soft token/time controls. Finished-agent transcript retention and persistent scheduling are separate roadmap items; agent teams and the project hub are experimental. +- **Automation has edges:** [reserved budgets](docs/reserved-budgets.md) currently support bounded official OpenAI Responses requests; ChatGPT/Copilot subscription models use soft token/time controls. Finished-agent transcript retention is a separate roadmap item; persistent schedules (`cyber loops`) run only while the Cyber service runs, which has no launchd/systemd unit yet; agent teams and the project hub are experimental. - **The native Gemini adapter is experimental:** off until `features.gemini` is set; tested against recorded protocol shapes only. A live tool-loop run with a key, the live coding baseline, Vertex AI and stored Gemini keys (`cyber providers login google`) remain. - **Native computer use is experimental:** macOS 14+ only, off by default; controlled capture, input and Stop passed. Other layouts, live OS revocation and release signing remain unverified. - **Remote access is private:** physical-device certificate trust is an operator check. Relay, paired Devices and mobile apps remain roadmap work. diff --git a/ROADMAP.md b/ROADMAP.md index 3e6a3b9cd..cf9537ce2 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -123,7 +123,7 @@ The [current inventory](docs/implementation/spec-doc-reconciliation.md) contains 1. **M2.1 Workflow runtime:** QuickJS sandbox, `agent()/parallel()/pipeline()/phase()`, determinism guards, event-sourced resume, budgets, model tiers (`fast` / `smart` / `verify`). *Status: implemented and accepted end to end with the real binary and a scripted local provider, including the gaps (`ask()`, direct read-only tools, prompt-cache warm-up, `exec --workflow`, `/tasks`, the Workflow library over HTTP, Save); reserved budgets are implemented for bounded official OpenAI Responses requests ([limits and owner reconciliation](docs/reserved-budgets.md)); finished-transcript retention remains (Session export includes run summaries); see [P2 evidence](docs/implementation/p2-status.md).* 2. **M2.2 Verified workflow library:** *Status: the five original bundled Workflows and the `solve` candidate/check/judge protocol are implemented; solve has scripted real-binary acceptance and green platform CI in PR #23.* The bundled review, audit (find → verify), migrate (fan-out with worktrees), research (cross-checked) and plan-from-angles ship in the binary (change `implement-m2-2-bundled-workflows`) with library listing, `show`/`eject`, args validation, host preparation, `/review` and `cyber review` routed to `review`, and the `/workflows` Library tab; each runs end to end on the real binary against a scripted model (`crates/cyber-cli/tests/bundled_workflows.rs`). Open: TUI pty/PNG captures, a live-model run and the archive; see [P2 evidence](docs/implementation/p2-status.md#m22-bundled-workflows-2026-10-22). The `solve` workflow adds 2–4 independent model attempts in worktrees → host-run checks tied to exact source revisions → an independent judge → an evidence report and optional recommendation; no automatic merge. Default soft budget: 5 USD / 30 minutes. See [solve acceptance](docs/measurements/verified-solve-acceptance.md) and the [archived change](openspec/changes/archive/2026-10-23-add-verified-solve-workflow/proposal.md). 3. **M2.3 Goals:** active goal + goal queue, evaluator verdicts, `check` commands, budgets, `exec --goal` exit codes. **Status: implemented** (change `implement-m2-3-goals`): `/goal` with queue, pause/resume/skip/clear/edit and reorder, the evaluator after each Turn with continuation and completion, checks, budgets, blocking-error pauses, deferred evaluation during background work, restore after restart, `core/goal` context, notifications, hooks, HTTP routes, the TUI panel, footer and sidebar, `exec --goal`, templates, `/goal fork` into a worktree Session, goals on subagents and workflow `agent()`, the model `goal` tool and unattended-ask pauses. The live end-to-end acceptance on the real binary remains. -4. **M2.4 Loops & cron:** `/loop` fixed and self-paced, in-session cron, daemon-backed persistent loops. **Status: Session loops and in-session cron implemented** (changes `implement-m2-4-loops`, `implement-m2-4-schedules` part A): fixed-interval and self-paced `/loop` with `schedule_wakeup`, queued delivery with overlap skip/coalesce, noop collapsing, `--max`/`--for`/`--until`/`--until-goal`/budget stops, restore after restart with the missed-run policy, the model's `cron_create`/`cron_list`/`cron_delete` tasks, loop notifications (`--notify`), the `LoopIteration` hook, HTTP routes and the TUI. Persistent `cyber loops` schedules run by the service (unattended Mode, jitter, desktop notifications, `schedule.run.1`, `ScheduleRun`) remain. +4. **M2.4 Loops & cron:** `/loop` fixed and self-paced, in-session cron, daemon-backed persistent loops. **Status: implemented** (changes `implement-m2-4-loops`, `implement-m2-4-schedules`): fixed-interval and self-paced `/loop` with `schedule_wakeup`, queued delivery with overlap skip/coalesce, noop collapsing, `--max`/`--for`/`--until`/`--until-goal`/budget stops, restore after restart with the missed-run policy, the model's `cron_create`/`cron_list`/`cron_delete` tasks, loop notifications (`--notify`), the `LoopIteration` hook, HTTP routes and the TUI; persistent `cyber loops add|list|show|pause|resume|run|rm` schedules run by the service with no client open, in `dont-ask` by default (`bypass` only with `loops.allow_bypass` from user or managed config), only in trusted directories, with deterministic jitter, Session and desktop notifications, budgets across runs, `schedule.run.1` and the `ScheduleRun` hook. Live runs against a real model, a launchd/systemd unit for the service and `cyber loops promote` (P3) remain. 5. **M2.5 Agent view & teams:** `cyber agents` dashboard; experimental lead/teammates with a shared task list. **Status: agent teams implemented, behind the experimental `teams` feature** (change `implement-agent-teams`, sections 1–9): definitions, spawning with worktree isolation and the lead's Mode ceiling and deny rules, the shared task board with dependencies and atomic claims, team messaging and idle notices, file ownership, `team_merge` that leaves the lead's checkout unchanged on conflicts, team budgets, stop/resume with restart recovery, HTTP/SDK/CLI and the TUI team view; accepted by hand on 2026-10-20 with the real binary and a scripted local provider (15 scenarios, [evidence](docs/implementation/p2-status.md#agent-teams-2026-10-20)). The `cyber agents` dashboard (agent view), an automated end-to-end suite, Windows runs and the archive remain; distributed teammates are P3. **Direct peers (`cross-session-messaging`, P2, not owned by an M2.x milestone): Status: implemented** (change `add-messaging-direct-peers`; [guide](docs/peers.md)). Pairing with pinned TLS fingerprints and hashed grant tokens, `name@machine` sends held on the receiver, polled outcomes, listing and watches, revocation, `cyber attach @` and opt-in mDNS discovery have production-path tests and were accepted by hand on 2026-10-19 with two real servers on one macOS host. Open: OS keyring evidence (mocked with `--token-env`), two-way pairing with a reply, the SSH-tunnel flow, a two-host run, Linux and Windows CI on this work, and the archive; see [P2 evidence](docs/implementation/p2-status.md#cross-session-messaging-direct-peers-2026-10-19). diff --git a/crates/cyber-app/src/desktop_notifier.rs b/crates/cyber-app/src/desktop_notifier.rs new file mode 100644 index 000000000..c3995f078 --- /dev/null +++ b/crates/cyber-app/src/desktop_notifier.rs @@ -0,0 +1,91 @@ +//! The OS desktop notifier of scheduled runs (`loops-scheduling` → Completion +//! notifications): a scheduled run usually has no client attached to show its +//! notification, so the service shows it. macOS uses `osascript`, Linux `notify-send`; +//! other platforms have none. Title and body are passed as arguments, never inlined in a +//! script or a shell command line. Best effort: a missing tool or a failure is ignored, +//! and a notifier that hangs is killed after a few seconds. + +use std::process::Stdio; +use std::time::Duration; + +use cyber_server::runtime::schedules::DesktopNotifier; + +/// How long a notifier process may run. +const TIMEOUT: Duration = Duration::from_secs(5); +/// Longest title and body passed on. +const MAX_TITLE: usize = 120; +const MAX_BODY: usize = 400; + +pub struct OsNotifier; + +/// The program and arguments that show `title` and `body`, or `None` on a platform +/// without a notifier. +pub fn command(title: &str, body: &str) -> Option<(&'static str, Vec)> { + let title: String = title.chars().take(MAX_TITLE).collect(); + let body: String = body.chars().take(MAX_BODY).collect(); + if cfg!(target_os = "macos") { + // The text arrives as `argv`, so no quoting can turn it into AppleScript. + let script = [ + "-e", + "on run argv", + "-e", + "display notification (item 2 of argv) with title (item 1 of argv)", + "-e", + "end run", + ]; + let mut args: Vec = script.iter().map(|s| (*s).to_owned()).collect(); + args.extend([title, body]); + return Some(("osascript", args)); + } + if cfg!(target_os = "linux") { + return Some(("notify-send", vec!["--".into(), title, body])); + } + None +} + +impl DesktopNotifier for OsNotifier { + fn notify(&self, title: &str, body: &str) { + let Some((program, args)) = command(title, body) else { + return; + }; + let Ok(handle) = tokio::runtime::Handle::try_current() else { + return; + }; + handle.spawn(async move { + let child = tokio::process::Command::new(program) + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .spawn(); + if let Ok(mut child) = child { + let _ = tokio::time::timeout(TIMEOUT, child.wait()).await; + } + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn text_is_passed_as_arguments_only() { + let hostile = "\" & do shell script \"touch /tmp/x\" & \""; + let Some((program, args)) = command("Schedule nightly", hostile) else { + return; + }; + assert!(matches!(program, "osascript" | "notify-send")); + assert_eq!(args.last().map(String::as_str), Some(hostile)); + assert!( + args.iter() + .filter(|a| a.as_str() != hostile) + .all(|a| !a.contains("touch")), + "{args:?}" + ); + let long = "x".repeat(1000); + let (_, args) = command(&long, &long).unwrap(); + assert!(args.iter().all(|a| a.chars().count() <= MAX_BODY)); + } +} diff --git a/crates/cyber-app/src/lib.rs b/crates/cyber-app/src/lib.rs index c95518ad5..d59a18ffb 100644 --- a/crates/cyber-app/src/lib.rs +++ b/crates/cyber-app/src/lib.rs @@ -5,6 +5,7 @@ pub mod account; pub mod backup; pub mod collaboration; +pub mod desktop_notifier; pub mod git_text; mod host; pub mod peer_discovery; @@ -208,6 +209,28 @@ fn peer_names(global: Arc) -> Arc { Arc::new(move || peer_tokens::enabled_names(&global()?)) } +/// Session loops: end iterations a stopped server cut off, apply the missed-run policy, +/// then admit due iterations every 5 s (`loops-scheduling`). Persistent schedules run only +/// in the service (`loops-scheduling` → Persistent local schedules): end runs a stopped +/// service cut off, apply the missed-run policy, then start due runs every 5 s, notifying +/// on the desktop. +async fn recover_loops_and_schedules( + runtime: &cyber_server::runtime::Runtime, + served: bool, +) -> Result<(), String> { + runtime.recover_loops().await.map_err(|e| e.to_string())?; + runtime.spawn_loop_sweep(); + if served { + runtime.set_desktop_notifier(Arc::new(desktop_notifier::OsNotifier)); + runtime + .recover_schedules() + .await + .map_err(|e| e.to_string())?; + runtime.spawn_schedule_sweep(); + } + Ok(()) +} + pub fn config_loader(paths: Paths, home: PathBuf) -> Arc { let resolved = hook_config_loader(paths, home); Arc::new(move |location| resolved(location).map(|resolved| (resolved.value, resolved.sources))) @@ -450,10 +473,7 @@ impl App { // teams a restart left stopping finish stopping (`agent-teams` → Idle // notifications, Shutdown and resume). runtime.recover_teams().await.map_err(|e| e.to_string())?; - // Session loops: end iterations a stopped server cut off, apply the missed-run - // policy, then admit due iterations every 5 s (`loops-scheduling`). - runtime.recover_loops().await.map_err(|e| e.to_string())?; - runtime.spawn_loop_sweep(); + recover_loops_and_schedules(&runtime, served).await?; // Outcomes of messages held on peers, polled from the times the store keeps, so // polling resumes after a restart (`cross-session-messaging` → Peer outcome // tracking). diff --git a/crates/cyber-app/tests/schedules.rs b/crates/cyber-app/tests/schedules.rs new file mode 100644 index 000000000..16ddfff5b --- /dev/null +++ b/crates/cyber-app/tests/schedules.rs @@ -0,0 +1,202 @@ +//! Persistent schedules on the production App (`loops-scheduling` → Persistent local +//! schedules, Unattended Mode for schedules, Completion notifications, Loop events and +//! hooks): the `/schedules` routes, the real tool host's gate and denials, and the real +//! `schedule_wakeup` tool, with the scripted OpenAI-compatible provider. + +#[path = "support/scripted_model.rs"] +mod scripted_model; +#[path = "support/mode_app.rs"] +mod support; + +use std::time::Duration; + +use serde_json::{Value, json}; +use support::{ModeApp, Setup}; + +async fn add(app: &ModeApp, body: Value) -> Value { + let (status, created) = app.send("POST", "/schedules", Some(body)).await; + assert_eq!(status, 201, "{created}"); + created["data"].clone() +} + +/// Start a run now and return the schedule once that run ended. +async fn run_now(app: &ModeApp, id: &str) -> Value { + let (status, body) = app + .send("POST", &format!("/schedules/{id}/run"), None) + .await; + assert_eq!(status, 200, "{body}"); + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + loop { + let (_, shown) = app.send("GET", &format!("/schedules/{id}"), None).await; + let run = &shown["data"]["recent"][0]; + if run["outcome"].is_string() && run["outcome"] != "running" { + return shown["data"].clone(); + } + assert!(tokio::time::Instant::now() < deadline, "{shown}"); + tokio::time::sleep(Duration::from_millis(50)).await; + } +} + +/// `loops-scheduling` → Unattended Mode for schedules: under `dont-ask` an ask is denied +/// with the schedule's message and the run continues to its end. +#[tokio::test] +async fn an_ask_in_a_scheduled_run_is_denied_with_feedback() { + let app = ModeApp::start(Setup::default()).await; + let schedule = add( + &app, + json!({"cron": "0 2 * * *", "name": "nightly", + "prompt": "RUN<>"}), + ) + .await; + assert_eq!(schedule["mode"], "dont-ask"); + let id = schedule["id"].as_str().unwrap(); + let shown = run_now(&app, id).await; + let run = &shown["recent"][0]; + assert_eq!(run["outcome"], "completed", "{shown}"); + let session = run["session_id"].as_str().unwrap(); + let outputs = app.outputs(session).await; + assert!( + outputs + .iter() + .any(|o| o.contains("Denied: no approver in unattended schedule")), + "{outputs:?}" + ); +} + +/// `loops-scheduling` → Completion notifications, Loop events and hooks: a run that calls +/// `schedule_wakeup` with `noop: true` is quiet under `on_change`, and `ScheduleRun` gets +/// the schedule and the run on stdin. +#[tokio::test] +async fn a_quiet_run_records_noop_and_fires_the_schedule_run_hook() { + let app = ModeApp::start(Setup { + config: json!({"hooks": {"ScheduleRun": [{"hooks": [ + {"type": "command", "command": "cat > run.json"}]}]}}), + ..Setup::default() + }) + .await; + let schedule = add( + &app, + json!({"cron": "0 2 * * *", "name": "quiet", + "prompt": r#"TOOL<>{"delay_seconds": 60, "reason": "nothing new", "noop": true}"#}), + ) + .await; + let id = schedule["id"].as_str().unwrap(); + let shown = run_now(&app, id).await; + let run = &shown["recent"][0]; + assert_eq!( + (run["outcome"].as_str(), run["noop"].as_bool()), + (Some("completed"), Some(true)), + "{shown}" + ); + assert_eq!(run["reason"], "nothing new"); + let session = run["session_id"].as_str().unwrap(); + let notified = app + .events(session) + .into_iter() + .filter(|e| e.kind == "session.notification.sent.1") + .count(); + assert_eq!(notified, 0, "on_change stays quiet for a noop run"); + + let path = app.repo.join("run.json"); + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + let written = loop { + if let Ok(text) = std::fs::read_to_string(&path) + && let Ok(value) = serde_json::from_str::(&text) + { + break value; + } + assert!(tokio::time::Instant::now() < deadline, "the hook never ran"); + tokio::time::sleep(Duration::from_millis(50)).await; + }; + assert_eq!(written["schedule"]["id"], id, "{written}"); + assert_eq!(written["run"]["noop"], true); + assert_eq!(written["run"]["outcome"], "completed"); +} + +#[tokio::test] +async fn schedules_are_managed_over_http() { + let app = ModeApp::start(Setup::default()).await; + let (status, body) = app + .send( + "POST", + "/schedules", + Some(json!({"cron": "61 * * * *", "prompt": "x"})), + ) + .await; + assert_eq!( + (status, body["_tag"].as_str()), + (400, Some("InvalidRequestError")), + "{body}" + ); + assert!( + body["message"] + .as_str() + .unwrap() + .contains("Invalid cron expression") + ); + let (status, body) = app + .send( + "POST", + "/schedules", + Some(json!({"cron": "0 2 * * *", "prompt": "x", "mode": "bypass"})), + ) + .await; + assert_eq!(status, 400, "{body}"); + assert!( + body["message"] + .as_str() + .unwrap() + .contains("loops.allow_bypass"), + "{body}" + ); + + let schedule = add(&app, json!({"cron": "0 2 * * *", "prompt": "review"})).await; + let id = schedule["id"].as_str().unwrap(); + assert_eq!(schedule["directory"], app.repo.display().to_string()); + assert!(schedule["next_due_ms"].is_i64()); + let (_, listed) = app.send("GET", "/schedules", None).await; + assert_eq!(listed["data"][0]["id"], id); + let (_, paused) = app + .send("POST", &format!("/schedules/{id}/pause"), None) + .await; + assert_eq!(paused["data"]["status"], "paused"); + assert!(paused["data"]["next_due_ms"].is_null()); + let (_, resumed) = app + .send("POST", &format!("/schedules/{id}/resume"), None) + .await; + assert_eq!(resumed["data"]["status"], "active"); + let (status, _) = app.send("DELETE", &format!("/schedules/{id}"), None).await; + assert_eq!(status, 200); + let (status, body) = app.send("GET", &format!("/schedules/{id}"), None).await; + assert_eq!( + (status, body["_tag"].as_str()), + (404, Some("ScheduleNotFoundError")) + ); +} + +/// A user config that allows `bypass` admits a `bypass` schedule only through the user +/// layer: the same key in the trusted checkout's project config does not. +#[tokio::test] +async fn only_user_config_allows_bypass_schedules() { + let app = ModeApp::start(Setup::default()).await; + std::fs::write( + app.repo.join("cyber.jsonc"), + r#"{"loops": {"allow_bypass": true}}"#, + ) + .unwrap(); + let (status, body) = app + .send( + "POST", + "/schedules", + Some(json!({"cron": "0 2 * * *", "prompt": "x", "mode": "bypass"})), + ) + .await; + assert_eq!(status, 400, "{body}"); + assert!( + body["message"] + .as_str() + .unwrap() + .contains("loops.allow_bypass"), + "{body}" + ); +} diff --git a/crates/cyber-cli/src/cli.rs b/crates/cyber-cli/src/cli.rs index 09cd19465..1be3497ac 100644 --- a/crates/cyber-cli/src/cli.rs +++ b/crates/cyber-cli/src/cli.rs @@ -233,6 +233,11 @@ pub enum Command { #[command(subcommand)] cmd: WorkflowsCmd, }, + /// Persistent schedules the Cyber service runs even when no client is open. + Loops { + #[command(subcommand)] + cmd: crate::commands::loops::LoopsCmd, + }, /// List, remove and prune managed Git worktrees of the current repository. Worktree { #[command(subcommand)] diff --git a/crates/cyber-cli/src/commands/loops.rs b/crates/cyber-cli/src/commands/loops.rs new file mode 100644 index 000000000..3581281b8 --- /dev/null +++ b/crates/cyber-cli/src/commands/loops.rs @@ -0,0 +1,417 @@ +//! `cyber loops` (`loops-scheduling` → Persistent local schedules): prompts the Cyber +//! service runs on a cron schedule even when no client is open, managed through the +//! service's schedule routes. +//! +//! Creating or waking a schedule is the human owner's act: `add`, `resume` and `run` are +//! refused inside an agent subprocess, so the model cannot schedule unattended work. + +use std::path::PathBuf; + +use clap::{Args, Subcommand}; +use cyber_client::Client; +use cyber_core::budget::Budget; +use serde_json::{Value, json}; + +use crate::cli::GlobalArgs; +use crate::context::Context; +use crate::error::CliError; +use crate::output; + +#[derive(Debug, Subcommand)] +pub enum LoopsCmd { + /// Add a schedule the Cyber service runs even when no client is open. + Add(Box), + /// Schedules with their next run (jitter included). + #[command(alias = "ls")] + List, + /// A schedule and its recent runs. + Show(IdArg), + /// Stop running a schedule until it is resumed; a run in flight finishes. + Pause(IdArg), + /// Resume a paused schedule at its next occurrence. + Resume(IdArg), + /// Run a schedule now, outside its cron schedule. + Run(IdArg), + /// Remove a schedule; its run history stays in the database. + #[command(alias = "remove")] + Rm(IdArg), +} + +#[derive(Debug, Args)] +pub struct IdArg { + /// The schedule's `cron_` ID. + pub id: String, +} + +#[derive(Debug, Args)] +pub struct AddArgs { + /// A 5-field cron expression in local time: minute hour day-of-month month day-of-week. + #[arg(long)] + pub cron: String, + /// A name shown in listings and notifications (default: the ID). + #[arg(long)] + pub name: Option, + /// The directory runs work in (default: the current Location). Its checkout must be + /// trusted. + #[arg(long)] + pub dir: Option, + /// The agent of run Sessions. + #[arg(long)] + pub agent: Option, + /// The Mode runs use (default dont-ask). `bypass` needs `loops.allow_bypass` in user or + /// managed config. + #[arg(long)] + pub mode: Option, + /// The model of new run Sessions (default: the Location's default model). + #[arg(long)] + pub model: Option, + /// Create a new Session for every run (the default). + #[arg(long, conflicts_with = "session")] + pub new_session: bool, + /// Resume this root Session for every run instead. + #[arg(long)] + pub session: Option, + /// When to notify: always, on_change (default) or never. + #[arg(long, value_parser = ["always", "on_change", "never"])] + pub notify: Option, + /// Runs missed while the service was not running: skip (default) or run-once. + #[arg(long, value_parser = ["skip", "run-once"])] + pub missed: Option, + /// Stop the schedule once its runs cost this many USD in total. + #[arg(long)] + pub max_cost: Option, + /// Stop once its runs used this many tokens in total. + #[arg(long)] + pub max_tokens: Option, + /// Stop once its runs made this many model calls in total. + #[arg(long)] + pub max_turns: Option, + /// Stop this long after the schedule was added (e.g. 30d). + #[arg(long)] + pub timeout: Option, + /// The prompt (or `/command`) each run sends. + pub prompt: String, +} + +/// The refusal inside an agent subprocess. +const AGENT_REFUSAL: &str = + "persistent schedules are managed by the human owner, outside an agent subprocess"; + +pub fn run(cmd: LoopsCmd, ctx: &Context, global: &GlobalArgs) -> Result<(), CliError> { + let wakes = matches!( + cmd, + LoopsCmd::Add(_) | LoopsCmd::Resume(_) | LoopsCmd::Run(_) + ); + if wakes && std::env::var_os("CYBER_SESSION_ID").is_some() { + return Err(CliError::usage(AGENT_REFUSAL)); + } + let body = match &cmd { + LoopsCmd::Add(args) => Some(add_body(args, ctx)?), + _ => None, + }; + let rt = super::serve::runtime()?; + rt.block_on(async { + let was_running = service_running(ctx).await; + let info = super::serve::start(ctx).await?; + let client = Client::http(&info.registration.url, Some(info.password)) + .at(&ctx.location.display().to_string()); + let json = output::is_json(global.format); + match cmd { + LoopsCmd::Add(_) => add(&client, body.unwrap_or_default(), json, was_running).await, + LoopsCmd::List => list(&client, json).await, + LoopsCmd::Show(arg) => show(&client, &arg.id, json).await, + LoopsCmd::Pause(arg) => act(&client, "POST", &arg.id, "/pause", json).await, + LoopsCmd::Resume(arg) => act(&client, "POST", &arg.id, "/resume", json).await, + LoopsCmd::Run(arg) => act(&client, "POST", &arg.id, "/run", json).await, + LoopsCmd::Rm(arg) => act(&client, "DELETE", &arg.id, "", json).await, + } + }) +} + +/// Whether a healthy service was registered before this command (which starts one). +async fn service_running(ctx: &Context) -> bool { + match cyber_app::read_registration(&ctx.paths) { + Some(registration) => cyber_app::probe_registration(®istration) + .await + .is_some_and(|probe| probe.serves(®istration)), + None => false, + } +} + +fn add_body(args: &AddArgs, ctx: &Context) -> Result { + let directory = match &args.dir { + Some(dir) => std::fs::canonicalize(dir) + .map_err(|e| CliError::usage(format!("--dir {}: {e}", dir.display())))?, + None => ctx.location.clone(), + }; + let budget = budget(args)?; + let mut body = json!({ + "cron": args.cron, + "prompt": args.prompt, + "directory": directory.display().to_string(), + }); + let optional = [ + ("name", args.name.clone()), + ("agent", args.agent.clone()), + ("mode", args.mode.clone()), + ("model", args.model.clone()), + ("session_id", args.session.clone()), + ("notify", args.notify.clone()), + ("missed", args.missed.clone()), + ]; + for (key, value) in optional { + if let Some(value) = value { + body[key] = json!(value); + } + } + if let Some(budget) = budget { + body["budget"] = + serde_json::to_value(budget).map_err(|e| CliError::runtime(e.to_string()))?; + } + Ok(body) +} + +fn budget(args: &AddArgs) -> Result, CliError> { + let wall = match &args.timeout { + Some(text) => Some( + cyber_core::loops::duration(text) + .ok_or_else(|| CliError::usage("--timeout needs a duration such as 12h or 30d"))? + as f64, + ), + None => None, + }; + let budget = Budget { + max_cost_usd: args.max_cost, + max_tokens: args.max_tokens, + max_turns: args.max_turns, + max_wall_seconds: wall, + ..Budget::default() + }; + let any = budget.max_cost_usd.is_some() + || budget.max_tokens.is_some() + || budget.max_turns.is_some() + || budget.max_wall_seconds.is_some(); + if any { + budget.validate().map_err(CliError::usage)?; + } + Ok(any.then_some(budget)) +} + +/// One schedule route request; a declared failure becomes a usage error (exit 2). +async fn call( + client: &Client, + method: &str, + path: &str, + body: Option, +) -> Result { + let (status, value) = client + .raw(method, path, body, &[]) + .await + .map_err(|e| CliError::runtime(e.to_string()))?; + if (200..300).contains(&status) { + return Ok(value); + } + let tag = value["_tag"].as_str().unwrap_or_default(); + let message = value["message"] + .as_str() + .unwrap_or("the server refused the request"); + Err(match tag { + "InvalidRequestError" | "ScheduleNotFoundError" => CliError::usage(message), + _ => CliError::runtime(super::tagged(tag, message)), + }) +} + +fn schedule_path(id: &str) -> Result { + if !cyber_core::loops::is_cron_id(id) { + return Err( + CliError::usage(format!("{id} is not a schedule ID (cron_…)")) + .with_hint("run \"cyber loops list\""), + ); + } + Ok(format!("/schedules/{id}")) +} + +async fn add(client: &Client, body: Value, json: bool, was_running: bool) -> Result<(), CliError> { + let schedule = call(client, "POST", "/schedules", Some(body)).await?["data"].take(); + if json { + output::json(&schedule)?; + } else { + println!( + "{} added · {} · next run {}", + field(&schedule, "id"), + field(&schedule, "cron"), + when(&schedule["next_due_ms"]) + ); + } + if !was_running { + eprintln!( + "warning: schedules run only while the Cyber service runs. It was not running, so it \ + was started now; after a reboot or logout start it again with `cyber service start`." + ); + } + Ok(()) +} + +async fn list(client: &Client, json: bool) -> Result<(), CliError> { + let schedules = call(client, "GET", "/schedules", None).await?["data"].take(); + if json { + return output::json(&schedules); + } + let schedules = schedules.as_array().cloned().unwrap_or_default(); + if schedules.is_empty() { + println!("No schedules. Add one with: cyber loops add --cron \"0 2 * * *\" \"\""); + return Ok(()); + } + let rows = schedules + .iter() + .map(|s| { + vec![ + field(s, "id"), + field(s, "name"), + field(s, "cron"), + when(&s["next_due_ms"]), + field(s, "status"), + s["runs"].as_u64().unwrap_or_default().to_string(), + field(s, "mode"), + field(s, "directory"), + ] + }) + .collect(); + let columns = [ + ("ID", false), + ("NAME", false), + ("CRON", false), + ("NEXT RUN", false), + ("STATUS", false), + ("RUNS", true), + ("MODE", false), + ("DIRECTORY", false), + ]; + super::teams::print_table(&columns, rows); + Ok(()) +} + +async fn show(client: &Client, id: &str, json: bool) -> Result<(), CliError> { + let schedule = call(client, "GET", &schedule_path(id)?, None).await?["data"].take(); + if json { + return output::json(&schedule); + } + let session = schedule["session_id"] + .as_str() + .map_or_else(|| "new Session per run".to_owned(), str::to_owned); + output::rows(&[ + ("id", field(&schedule, "id")), + ("name", field(&schedule, "name")), + ("cron", field(&schedule, "cron")), + ("next run", when(&schedule["next_due_ms"])), + ("status", field(&schedule, "status")), + ("directory", field(&schedule, "directory")), + ("mode", field(&schedule, "mode")), + ("session", session), + ("notify", field(&schedule, "notify")), + ( + "runs", + schedule["runs"].as_u64().unwrap_or_default().to_string(), + ), + ( + "cost", + format!("${:.2}", schedule["cost_usd"].as_f64().unwrap_or_default()), + ), + ("prompt", field(&schedule, "prompt")), + ]); + if let Some(reason) = schedule["reason"].as_str() { + println!("reason: {reason}"); + } + for run in schedule["recent"].as_array().into_iter().flatten() { + let reason = run["reason"] + .as_str() + .map(|r| format!(" · {r}")) + .unwrap_or_default(); + println!( + " #{} {} {}{reason}", + run["n"].as_u64().unwrap_or_default(), + when(&run["due_ms"]), + field(run, "outcome"), + ); + } + Ok(()) +} + +async fn act( + client: &Client, + method: &str, + id: &str, + verb: &str, + json: bool, +) -> Result<(), CliError> { + let path = format!("{}{verb}", schedule_path(id)?); + let value = call(client, method, &path, None).await?["data"].take(); + if json { + return output::json(&value); + } + match verb { + "" => println!("{id} removed"), + "/run" => println!( + "{id} run started ({})", + value["run_id"].as_str().unwrap_or("-") + ), + _ => println!( + "{id} {} · next run {}", + field(&value, "status"), + when(&value["next_due_ms"]) + ), + } + Ok(()) +} + +fn field(value: &Value, key: &str) -> String { + value[key].as_str().unwrap_or("-").to_owned() +} + +/// A time in ms as a local timestamp, or `-`. +fn when(value: &Value) -> String { + value + .as_i64() + .map_or_else(|| "-".into(), cyber_core::cron::local_time_text) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args(extra: &[&str]) -> AddArgs { + use clap::Parser; + #[derive(Parser)] + struct Wrap { + #[command(flatten)] + add: AddArgs, + } + let mut all = vec!["x", "--cron", "0 2 * * *"]; + all.extend_from_slice(extra); + all.push("review the night's commits"); + Wrap::parse_from(all).add + } + + #[test] + fn budgets_come_from_the_flags() { + assert_eq!(budget(&args(&[])).unwrap(), None); + let b = budget(&args(&["--max-cost", "2", "--timeout", "30d"])) + .unwrap() + .unwrap(); + assert_eq!( + (b.max_cost_usd, b.max_wall_seconds), + (Some(2.0), Some(2_592_000.0)) + ); + assert!(budget(&args(&["--timeout", "soon"])).is_err()); + } + + #[test] + fn schedule_ids_are_checked_before_any_request() { + assert_eq!( + schedule_path("cron_01ABC").unwrap(), + "/schedules/cron_01ABC" + ); + assert!(schedule_path("lop_01ABC").is_err()); + assert!(schedule_path("../x").is_err()); + } +} diff --git a/crates/cyber-cli/src/commands/mod.rs b/crates/cyber-cli/src/commands/mod.rs index 2e465f11d..cd3786ca8 100644 --- a/crates/cyber-cli/src/commands/mod.rs +++ b/crates/cyber-cli/src/commands/mod.rs @@ -19,6 +19,7 @@ pub mod hooks; pub mod ide; pub mod import; pub mod intelligence; +pub mod loops; pub mod mcp; pub mod mcp_browser; pub mod mcp_config; @@ -126,6 +127,7 @@ pub fn run(mut cli: Cli) -> Result<(), CliError> { Command::Worktree { cmd } => worktrees::run(cmd, &ctx, &cli.global), Command::Workflows { cmd } => workflows::run(cmd, &ctx, &cli.global), Command::Teams { cmd } => teams::run(cmd, &ctx, &cli.global), + Command::Loops { cmd } => loops::run(cmd, &ctx, &cli.global), Command::Computer { cmd } => computer::run(cmd, &ctx, &cli.global), Command::Features { cmd } => features::run(cmd, &ctx, &cli.global), Command::Debug { cmd } => debug::run(cmd, &ctx, &cli.global), diff --git a/crates/cyber-cli/src/commands/teams.rs b/crates/cyber-cli/src/commands/teams.rs index deba14359..e6bd431f6 100644 --- a/crates/cyber-cli/src/commands/teams.rs +++ b/crates/cyber-cli/src/commands/teams.rs @@ -367,7 +367,7 @@ fn status_of(team: &Value) -> String { /// Columns `(header, right-aligned)` as wide as their widest cell, two spaces apart; the /// last column is not padded. -fn print_table(columns: &[(&str, bool)], rows: Vec>) { +pub(crate) fn print_table(columns: &[(&str, bool)], rows: Vec>) { let widths: Vec = columns .iter() .enumerate() diff --git a/crates/cyber-cli/tests/loops_cli.rs b/crates/cyber-cli/tests/loops_cli.rs new file mode 100644 index 000000000..03f791c47 --- /dev/null +++ b/crates/cyber-cli/tests/loops_cli.rs @@ -0,0 +1,194 @@ +//! `cyber loops` through the real binary (`loops-scheduling` → Persistent local +//! schedules): schedules added, listed, run, paused, resumed and removed against the +//! background service the command starts, with a loopback scripted model; and the +//! refusal inside an agent subprocess. + +use std::path::PathBuf; +use std::process::{Command, Output}; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +#[path = "../../cyber-app/tests/support/scripted_model.rs"] +mod scripted_model; + +/// A checkout whose default model is the scripted one; the background service it starts +/// is stopped on drop. +struct Served { + _dir: tempfile::TempDir, + root: PathBuf, + repo: PathBuf, + _model: scripted_model::ScriptedModel, +} + +impl Served { + fn new() -> Self { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().canonicalize().unwrap(); + let repo = root.join("repo"); + std::fs::create_dir_all(repo.join(".git")).unwrap(); + let model = scripted_model::ScriptedModel::start(|_| json!({"content": "reviewed"})); + let config_dir = root.join("cyber-home").join("config"); + std::fs::create_dir_all(&config_dir).unwrap(); + std::fs::write(config_dir.join("cyber.jsonc"), model.config().to_string()).unwrap(); + std::fs::write(root.join("models.json"), "{}").unwrap(); + Self { + _dir: dir, + root, + repo, + _model: model, + } + } + + fn cyber_with(&self, args: &[&str], env: &[(&str, &str)]) -> Output { + let models = self.root.join("models.json"); + let mut command = Command::new(env!("CARGO_BIN_EXE_cyber")); + command + .args(args) + .env_clear() + .env("HOME", self.root.join("home")) + .env("CYBER_HOME", self.root.join("cyber-home")) + .env("CYBER_MANAGED_POLICY_DIR", self.root.join("managed")) + .env("CYBER_MODELS_PATH", models) + .env("PATH", std::env::var("PATH").unwrap_or_default()) + .envs(env.iter().copied()) + .current_dir(&self.repo); + #[cfg(windows)] + if let Some(system) = std::env::var_os("SystemRoot") { + command.env("SystemRoot", system); + } + command.output().unwrap() + } + + fn cyber(&self, args: &[&str]) -> Output { + self.cyber_with(args, &[]) + } + + fn json(&self, args: &[&str]) -> Value { + let mut all = args.to_vec(); + all.extend(["--format", "json"]); + let out = self.cyber(&all); + succeeded(&out); + serde_json::from_slice(&out.stdout).unwrap_or_else(|e| panic!("{e}: {}", stdout(&out))) + } +} + +impl Drop for Served { + fn drop(&mut self) { + let _ = self.cyber(&["service", "stop"]); + } +} + +fn stdout(o: &Output) -> String { + String::from_utf8_lossy(&o.stdout).into_owned() +} + +fn stderr(o: &Output) -> String { + String::from_utf8_lossy(&o.stderr).into_owned() +} + +fn succeeded(out: &Output) { + assert!( + out.status.success(), + "stdout: {}\nstderr: {}", + stdout(out), + stderr(out) + ); +} + +#[test] +fn schedules_are_added_run_and_managed_through_the_service() { + let env = Served::new(); + // February 29th only, so the service's own sweep never starts a run during the test. + let added = env.cyber(&[ + "loops", + "add", + "--cron", + "0 2 29 2 *", + "--name", + "nightly", + "--notify", + "never", + "review last night's commits", + ]); + succeeded(&added); + let line = stdout(&added); + assert!(line.starts_with("cron_"), "{line}"); + assert!(line.contains("added · 0 2 29 2 * · next run "), "{line}"); + assert!( + stderr(&added).contains("schedules run only while the Cyber service runs") + && stderr(&added).contains("cyber service start"), + "{}", + stderr(&added) + ); + let id = line.split_whitespace().next().unwrap().to_owned(); + + let listed = env.cyber(&["loops", "list"]); + succeeded(&listed); + let text = stdout(&listed); + assert!(text.starts_with("ID"), "{text}"); + assert!( + text.contains(&id) && text.contains("nightly") && text.contains("dont-ask"), + "{text}" + ); + + // A second add finds the service running: no warning. + let again = env.cyber(&[ + "loops", + "add", + "--cron", + "0 3 29 2 *", + "--notify", + "never", + "leap day", + ]); + succeeded(&again); + assert!(!stderr(&again).contains("warning"), "{}", stderr(&again)); + + let started = env.cyber(&["loops", "run", &id]); + succeeded(&started); + let deadline = Instant::now() + Duration::from_secs(60); + let shown = loop { + let shown = env.json(&["loops", "show", &id]); + if shown["recent"][0]["outcome"] == "completed" { + break shown; + } + assert!(Instant::now() < deadline, "{shown:#}"); + std::thread::sleep(Duration::from_millis(100)); + }; + assert_eq!(shown["runs"], 1); + assert!(shown["recent"][0]["session_id"].is_string(), "{shown:#}"); + + succeeded(&env.cyber(&["loops", "pause", &id])); + assert_eq!(env.json(&["loops", "show", &id])["status"], "paused"); + succeeded(&env.cyber(&["loops", "resume", &id])); + assert_eq!(env.json(&["loops", "show", &id])["status"], "active"); + succeeded(&env.cyber(&["loops", "rm", &id])); + let gone = env.cyber(&["loops", "show", &id]); + assert_eq!(gone.status.code(), Some(2), "{}", stderr(&gone)); + let bad = env.cyber(&["loops", "show", "lop_01ABC"]); + assert_eq!(bad.status.code(), Some(2)); + assert!( + stderr(&bad).contains("not a schedule ID"), + "{}", + stderr(&bad) + ); +} + +#[test] +fn an_agent_subprocess_cannot_add_or_wake_schedules() { + let env = Served::new(); + for args in [ + vec!["loops", "add", "--cron", "* * * * *", "exfiltrate"], + vec!["loops", "run", "cron_01ABC"], + vec!["loops", "resume", "cron_01ABC"], + ] { + let out = env.cyber_with(&args, &[("CYBER_SESSION_ID", "ses_01MODEL")]); + assert_eq!(out.status.code(), Some(2), "{args:?}: {}", stderr(&out)); + assert!( + stderr(&out).contains("managed by the human owner, outside an agent subprocess"), + "{}", + stderr(&out) + ); + } +} diff --git a/crates/cyber-core/src/loops.rs b/crates/cyber-core/src/loops.rs index cf93ea33f..489d2b362 100644 --- a/crates/cyber-core/src/loops.rs +++ b/crates/cyber-core/src/loops.rs @@ -348,6 +348,8 @@ pub struct LoopSettings { pub max_iterations: u64, pub max_per_session: u64, pub until_timeout_seconds: u64, + /// The largest deterministic offset of a persistent schedule's runs; 0 turns it off. + pub jitter_seconds: u64, } impl Default for LoopSettings { @@ -356,10 +358,26 @@ impl Default for LoopSettings { max_iterations: 500, max_per_session: 50, until_timeout_seconds: 60, + jitter_seconds: 60, } } } +/// The longest jitter accepted, so a schedule's runs stay within its period. +pub const MAX_JITTER_SECONDS: u64 = 3600; + +/// `loops.allow_bypass` (`loops-scheduling` → Unattended Mode for schedules): true only +/// when the merged value is `true` and the layer that set it is user (`global:`) or +/// managed (`managed:`) configuration. A project, local, environment, profile or +/// command-line layer cannot enable it, and anything unexpected reads as false. +pub fn allow_bypass(config: &Value, sources: &std::collections::BTreeMap) -> bool { + const POINTER: &str = "/loops/allow_bypass"; + config.pointer(POINTER) == Some(&Value::Bool(true)) + && sources + .get(POINTER) + .is_some_and(|label| label.starts_with("global:") || label.starts_with("managed:")) +} + impl LoopSettings { pub fn from_config(config: &Value) -> Self { let defaults = Self::default(); @@ -375,6 +393,10 @@ impl LoopSettings { max_iterations: number("max_iterations", defaults.max_iterations), max_per_session: number("max_per_session", defaults.max_per_session), until_timeout_seconds: number("until_timeout_seconds", defaults.until_timeout_seconds), + jitter_seconds: loops + .and_then(|l| l.get("jitter_seconds")) + .and_then(Value::as_u64) + .map_or(defaults.jitter_seconds, |s| s.min(MAX_JITTER_SECONDS)), } } } @@ -514,5 +536,40 @@ mod tests { let s = LoopSettings::from_config(&serde_json::json!({"loops": {"max_iterations": 7}})); assert_eq!(s.max_iterations, 7); assert_eq!(s.max_per_session, 50); + assert_eq!(s.jitter_seconds, 60); + let off = LoopSettings::from_config(&serde_json::json!({"loops": {"jitter_seconds": 0}})); + assert_eq!(off.jitter_seconds, 0); + let capped = + LoopSettings::from_config(&serde_json::json!({"loops": {"jitter_seconds": 99999}})); + assert_eq!(capped.jitter_seconds, MAX_JITTER_SECONDS); + } + + #[test] + fn only_user_or_managed_config_allows_bypass() { + let on = serde_json::json!({"loops": {"allow_bypass": true}}); + let from = |label: &str| { + std::iter::once(("/loops/allow_bypass".to_owned(), label.to_owned())).collect() + }; + assert!(allow_bypass( + &on, + &from("global:/home/u/.config/cyber/cyber.jsonc") + )); + assert!(allow_bypass(&on, &from("managed:/etc/cyber/managed.json"))); + for label in [ + "project:/repo/cyber.jsonc", + "project:/repo/.cyber/cyber.local.jsonc", + "env:CYBER_CONFIG_CONTENT", + "profile:fast", + "cli:--config", + "default", + ] { + assert!(!allow_bypass(&on, &from(label)), "{label}"); + } + let off = serde_json::json!({"loops": {"allow_bypass": "true"}}); + assert!( + !allow_bypass(&off, &from("global:/x")), + "only the boolean true" + ); + assert!(!allow_bypass(&on, &Default::default()), "an unknown source"); } } diff --git a/crates/cyber-server/src/http/error.rs b/crates/cyber-server/src/http/error.rs index faca710b2..c98d1c488 100644 --- a/crates/cyber-server/src/http/error.rs +++ b/crates/cyber-server/src/http/error.rs @@ -234,6 +234,7 @@ impl From for ApiError { } RuntimeError::MessageNotFound(_) => Self::not_found("MessageNotFoundError", message), RuntimeError::LoopNotFound(_) => Self::not_found("LoopNotFoundError", message), + RuntimeError::ScheduleNotFound(_) => Self::not_found("ScheduleNotFoundError", message), RuntimeError::LoopLimit(_) => { Self::new(StatusCode::CONFLICT, "LoopLimitError", message) } diff --git a/crates/cyber-server/src/http/mod.rs b/crates/cyber-server/src/http/mod.rs index d67a6f53c..90bebdb72 100644 --- a/crates/cyber-server/src/http/mod.rs +++ b/crates/cyber-server/src/http/mod.rs @@ -44,6 +44,7 @@ mod pty; pub mod remote_tools; mod reservations; pub mod rpc; +mod schedules; mod serve; mod service; mod sessions; @@ -783,6 +784,7 @@ pub fn router_with(state: AppState, mcp_serve: Arc) -> Router .merge(memory::routes()) .merge(messaging::routes()) .merge(loops::routes()) + .merge(schedules::routes()) .merge(peers::routes()) .merge(goals::routes()) .merge(providers::routes()) diff --git a/crates/cyber-server/src/http/openapi.rs b/crates/cyber-server/src/http/openapi.rs index 9488ac606..c4b39d7e4 100644 --- a/crates/cyber-server/src/http/openapi.rs +++ b/crates/cyber-server/src/http/openapi.rs @@ -1424,6 +1424,66 @@ pub fn operations(g: &mut SchemaGenerator) -> Vec { ) .ok::>>(g) .error::(g, 404, "SessionNotFoundError or LoopNotFoundError"), + op( + "get", + "/schedules", + "v1.schedule.list", + "Persistent schedules (not removed), oldest first, with their next run including jitter", + ) + .ok::>>(g), + op( + "post", + "/schedules", + "v1.schedule.create", + "Add a persistent schedule the service runs with no client open; the directory must be trusted and `bypass` needs `loops.allow_bypass` in user or managed config", + ) + .body::(g) + .status(201) + .ok::>(g) + .error::(g, 400, "InvalidRequestError, such as an invalid cron expression or a refused directory or Mode"), + op( + "get", + "/schedules/{scheduleID}", + "v1.schedule.get", + "A schedule with its 20 most recent runs, newest first", + ) + .ok::>(g) + .error::(g, 404, "ScheduleNotFoundError"), + op( + "delete", + "/schedules/{scheduleID}", + "v1.schedule.remove", + "Remove a schedule; its run history stays and a run in flight finishes", + ) + .ok::>>(g) + .error::(g, 404, "ScheduleNotFoundError"), + op( + "post", + "/schedules/{scheduleID}/pause", + "v1.schedule.pause", + "Pause a schedule; a run in flight finishes", + ) + .ok::>(g) + .error::(g, 400, "InvalidRequestError") + .error::(g, 404, "ScheduleNotFoundError"), + op( + "post", + "/schedules/{scheduleID}/resume", + "v1.schedule.resume", + "Resume a paused schedule at its next occurrence", + ) + .ok::>(g) + .error::(g, 400, "InvalidRequestError, such as a schedule that exceeded its budget") + .error::(g, 404, "ScheduleNotFoundError"), + op( + "post", + "/schedules/{scheduleID}/run", + "v1.schedule.run", + "Run a schedule now, outside its cron schedule, through the same unattended gate", + ) + .ok::>(g) + .error::(g, 400, "InvalidRequestError, such as a run already in flight") + .error::(g, 404, "ScheduleNotFoundError"), op("get","/account","v1.account.get","Current Cyber Account display claims; never returns raw tokens") .ok::>(g) .error::(g,401,"SessionExpiredError") diff --git a/crates/cyber-server/src/http/schedules.rs b/crates/cyber-server/src/http/schedules.rs new file mode 100644 index 000000000..28d9d860d --- /dev/null +++ b/crates/cyber-server/src/http/schedules.rs @@ -0,0 +1,101 @@ +//! Schedule routes (`loops-scheduling` → Persistent local schedules): `/api/v1/schedules`. +//! Owner credential only; IDE tokens do not reach them (their scope excludes them), and +//! model subprocesses never hold the owner credential. + +use axum::{ + Json, Router, + extract::{Path, State}, + http::{StatusCode, request::Parts}, + routing::{get, post}, +}; +use schemars::JsonSchema; +use serde::Serialize; + +use super::{AppState, envelope::Data, error::ApiError}; +use crate::runtime::schedules::{Schedule, ScheduleRequest}; + +type Result = std::result::Result; + +/// `POST /api/v1/schedules/{id}/run`. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ScheduleRunStarted { + pub run_id: String, +} + +pub(super) fn routes() -> Router { + Router::new() + .route("/schedules", get(list).post(create)) + .route("/schedules/{schedule_id}", get(show).delete(remove)) + .route("/schedules/{schedule_id}/pause", post(pause)) + .route("/schedules/{schedule_id}/resume", post(resume)) + .route("/schedules/{schedule_id}/run", post(run_now)) +} + +async fn list(State(state): State) -> Result>>> { + Ok(Json(Data { + data: state.runtime.schedules()?, + })) +} + +async fn create( + State(state): State, + parts: Parts, + Json(mut body): Json, +) -> Result<(StatusCode, Json>)> { + let directory = match body.directory.take() { + Some(directory) => std::fs::canonicalize(&directory) + .map_err(|_| ApiError::invalid(format!("no such directory: {directory}")))?, + None => super::envelope::location(&parts, &state.options.default_directory)?, + }; + if body.model.is_none() { + body.model = state.services.default_model(&directory); + } + body.directory = Some(directory.display().to_string()); + let created = state.runtime.create_schedule(body).await?; + Ok((StatusCode::CREATED, Json(Data { data: created }))) +} + +async fn show( + State(state): State, + Path(id): Path, +) -> Result>> { + Ok(Json(Data { + data: state.runtime.schedule(&id, true)?, + })) +} + +async fn remove( + State(state): State, + Path(id): Path, +) -> Result>>> { + state.runtime.remove_schedule(&id)?; + Ok(Json(Data { data: vec![id] })) +} + +async fn pause( + State(state): State, + Path(id): Path, +) -> Result>> { + Ok(Json(Data { + data: state.runtime.pause_schedule(&id)?, + })) +} + +async fn resume( + State(state): State, + Path(id): Path, +) -> Result>> { + Ok(Json(Data { + data: state.runtime.resume_schedule(&id)?, + })) +} + +async fn run_now( + State(state): State, + Path(id): Path, +) -> Result>> { + let run_id = state.runtime.run_schedule_now(&id).await?; + Ok(Json(Data { + data: ScheduleRunStarted { run_id }, + })) +} diff --git a/crates/cyber-server/src/runtime/drain.rs b/crates/cyber-server/src/runtime/drain.rs index 1c09d0c5e..9f4d484d7 100644 --- a/crates/cyber-server/src/runtime/drain.rs +++ b/crates/cyber-server/src/runtime/drain.rs @@ -138,6 +138,8 @@ async fn went_idle(runtime: super::Runtime, id: &str, (hops, status): (u32, Opti runtime.inner.release_attachment_cache(id).await; // `loops-scheduling`: the iterations this Drain ran end now. runtime.loops_drain_ended(id, status.as_deref()).await; + // `loops-scheduling` → Persistent local schedules: the scheduled runs it ran end now. + runtime.schedules_drain_ended(id, status.as_deref()).await; // `cross-session-messaging` → Idle notifications: the Session went idle. runtime.drain_ended(id, hops, status).await; // `agent-teams` → Idle notifications: a teammate's lead hears that it went idle. diff --git a/crates/cyber-server/src/runtime/events.rs b/crates/cyber-server/src/runtime/events.rs index 0328e89f0..4622b4c2e 100644 --- a/crates/cyber-server/src/runtime/events.rs +++ b/crates/cyber-server/src/runtime/events.rs @@ -657,6 +657,7 @@ pub fn registry() -> EventRegistry { super::memory::register(&mut registry); super::messaging::records::register(&mut registry); super::loops::records::register(&mut registry); + super::schedules::records::register(&mut registry); super::teams::records::register(&mut registry); super::goals::records::register(&mut registry); super::usage_wait::register(&mut registry); @@ -665,6 +666,7 @@ pub fn registry() -> EventRegistry { registry.projector(project); registry.projector(super::messaging::records::project); registry.projector(super::loops::records::project); + registry.projector(super::schedules::records::project); registry.projector(super::teams::records::project); registry.projector(super::goals::records::project); registry.projector(super::usage_wait::project); diff --git a/crates/cyber-server/src/runtime/host.rs b/crates/cyber-server/src/runtime/host.rs index 4c03980d6..2f0133b59 100644 --- a/crates/cyber-server/src/runtime/host.rs +++ b/crates/cyber-server/src/runtime/host.rs @@ -1352,6 +1352,17 @@ pub trait ToolHost: Send + Sync { Ok((cyber_core::loops::LoopSettings::default(), None)) } + /// What the unattended gate of a persistent schedule needs about `directory` + /// (`loops-scheduling` → Unattended Mode for schedules): checkout trust, whether user + /// or managed config allows `bypass`, the jitter and the `budgets.loop` default. A host + /// that cannot tell refuses, so schedules never run on assumptions. + fn schedule_policy( + &self, + _directory: &str, + ) -> Result { + Err("Refused: this host cannot check a directory for unattended schedules".into()) + } + /// `usage_limit` at the Location (`configuration` → Usage limit settings). fn usage_limit_settings( &self, diff --git a/crates/cyber-server/src/runtime/loops/schedule.rs b/crates/cyber-server/src/runtime/loops/schedule.rs index 06da42f22..a3dc9db0b 100644 --- a/crates/cyber-server/src/runtime/loops/schedule.rs +++ b/crates/cyber-server/src/runtime/loops/schedule.rs @@ -317,15 +317,28 @@ impl Runtime { session_id: &str, iteration: &Iteration, ) -> Result { - let message_id = Some(iteration.started.message_id.clone()); + let message_id = iteration.started.message_id.clone(); + self.prompt_admission(session_id, &iteration.prompt, message_id) + .await + } + + /// A queued `source: "loop"` admission of a loop or scheduled run's prompt under + /// `message_id`; a `/command` prompt is planned as the command route plans it. + pub(crate) async fn prompt_admission( + &self, + session_id: &str, + prompt: &str, + message_id: String, + ) -> Result { + let message_id = Some(message_id); let plain = || Admission { message_id: message_id.clone(), source: "loop".into(), resume: true, output_schema: None, - ..Admission::text(iteration.prompt.clone(), Delivery::Queue) + ..Admission::text(prompt.to_owned(), Delivery::Queue) }; - let Some(command) = iteration.prompt.strip_prefix('/') else { + let Some(command) = prompt.strip_prefix('/') else { return Ok(plain()); }; let (name, arguments) = command @@ -556,7 +569,7 @@ impl Runtime { /// Admit an iteration like a typed prompt (templates, `@` mentions, UserPromptSubmit /// with `source: "loop"`) with its `loop.iteration.started` record in the same commit. - async fn admit_loop_iteration( + pub(crate) async fn admit_loop_iteration( &self, session_id: &str, admission: Admission, diff --git a/crates/cyber-server/src/runtime/mod.rs b/crates/cyber-server/src/runtime/mod.rs index 891960b7b..a0ec93bfb 100644 --- a/crates/cyber-server/src/runtime/mod.rs +++ b/crates/cyber-server/src/runtime/mod.rs @@ -92,6 +92,7 @@ mod jobs; pub mod loops; mod names; mod output_style; +pub mod schedules; pub mod teams; pub use handoff::Handoff; mod process_jobs; @@ -402,6 +403,8 @@ pub enum RuntimeError { /// The Session already has `loops.max_per_session` active loops. #[error("LoopLimitError: Scheduled task limit reached ({0})")] LoopLimit(u64), + #[error("ScheduleNotFoundError: no schedule {0}")] + ScheduleNotFound(String), /// A feature the Location's configuration leaves off (`agent-teams` → Feature flag); /// nothing was written. #[error("FeatureDisabledError: {0}")] @@ -983,6 +986,12 @@ pub(crate) struct Inner { workflow_relaunch: std::sync::OnceLock>, /// Set once the `workflow.run.progress` publisher runs. workflow_progress: std::sync::OnceLock<()>, + /// Shows a scheduled run's notification on the desktop (`loops-scheduling` → + /// Completion notifications); the served App sets the OS one. + desktop_notifier: std::sync::OnceLock>, + /// Set once this runtime runs persistent schedules (`spawn_schedule_sweep`): only the + /// service does, so an in-process App never runs them a second time. + schedules_on: std::sync::atomic::AtomicBool, pub(crate) waiters: StdMutex>, /// The last background update check (`installation-upgrade`). update_status: StdMutex>, @@ -1090,6 +1099,8 @@ impl Runtime { attachments: std::sync::OnceLock::new(), workflow_relaunch: std::sync::OnceLock::new(), workflow_progress: std::sync::OnceLock::new(), + desktop_notifier: std::sync::OnceLock::new(), + schedules_on: std::sync::atomic::AtomicBool::new(false), waiters: StdMutex::default(), wait_clock: std::sync::OnceLock::new(), settlement_probe: std::sync::OnceLock::new(), diff --git a/crates/cyber-server/src/runtime/schedules/gate.rs b/crates/cyber-server/src/runtime/schedules/gate.rs new file mode 100644 index 000000000..369e9c522 --- /dev/null +++ b/crates/cyber-server/src/runtime/schedules/gate.rs @@ -0,0 +1,93 @@ +//! The unattended gate (`loops-scheduling` → Unattended Mode for schedules): checked when +//! a schedule is added and again before every run, because configuration, trust and +//! checkouts change between runs. Every failure refuses; nothing is assumed. + +use std::path::Path; + +use super::SchedulePolicy; +use crate::runtime::{Runtime, RuntimeError}; + +/// What a schedule would run: where, as which agent, in which Mode, in which Session. +pub(super) struct Draft<'a> { + pub directory: &'a str, + pub agent: &'a str, + pub mode: &'a str, + pub session_id: Option<&'a str>, +} + +impl Runtime { + /// Admit `draft` or say why not; the directory's policy when admitted. + pub(super) async fn schedule_gate(&self, draft: &Draft<'_>) -> Result { + let path = Path::new(draft.directory); + if !path.is_absolute() || !path.is_dir() { + return Err(format!( + "Refused: {} is not an existing directory", + draft.directory + )); + } + let policy = self.inner.tools.schedule_policy(draft.directory)?; + if !policy.trusted { + return Err(format!( + "Refused: {} is not trusted; run `cyber trust inspect` there", + draft.directory + )); + } + if draft.mode == "bypass" && !policy.allow_bypass { + return Err( + "Refused: a schedule runs in bypass only when loops.allow_bypass is true in \ + user or managed config" + .into(), + ); + } + self.admit_mode(draft.directory, draft.agent, draft.mode) + .map_err(|error| format!("Refused: {}", plain(&error)))?; + if let Some(session_id) = draft.session_id { + self.schedule_session_usable(session_id, draft.directory) + .await?; + } + Ok(policy) + } + + /// A Session a schedule resumes: a root Session of the schedule's directory that is + /// not archived. + async fn schedule_session_usable( + &self, + session_id: &str, + directory: &str, + ) -> Result<(), String> { + let state = self + .state(session_id) + .await + .map_err(|_| format!("Refused: Session {session_id} does not exist"))?; + let info = &state.info; + if info.parent_id.is_some() || info.workflow_run_id.is_some() { + return Err(format!( + "Refused: Session {session_id} is not a root Session" + )); + } + if info.archived { + return Err(format!("Refused: Session {session_id} is archived")); + } + if !same_directory(&info.directory, directory) { + return Err(format!( + "Refused: Session {session_id} belongs to {}, not {directory}", + info.directory + )); + } + Ok(()) + } +} + +fn same_directory(a: &str, b: &str) -> bool { + let canonical = |p: &str| std::fs::canonicalize(p).unwrap_or_else(|_| p.into()); + canonical(a) == canonical(b) +} + +/// A runtime error's message without its error-type prefix. +pub(super) fn plain(error: &RuntimeError) -> String { + let text = error.to_string(); + match text.split_once(": ") { + Some((tag, rest)) if tag.ends_with("Error") => rest.to_owned(), + _ => text, + } +} diff --git a/crates/cyber-server/src/runtime/schedules/mod.rs b/crates/cyber-server/src/runtime/schedules/mod.rs new file mode 100644 index 000000000..47d4ed6c4 --- /dev/null +++ b/crates/cyber-server/src/runtime/schedules/mod.rs @@ -0,0 +1,378 @@ +//! Persistent local schedules (`loops-scheduling` → Persistent local schedules, Unattended +//! Mode for schedules, Jitter, Completion notifications, Budgets for loops): prompts the +//! service runs on a cron schedule even when no client is open. +//! +//! A schedule is its own event stream (`schedule.*`, keyed by its `cron_` ID) projected +//! into `schedule` and `schedule_run`. Every transition is decided inside the writer +//! transaction that records it, so the sweep, `run now` and the Drain's idle exit never +//! record the same run twice. [`run`] runs them: each due run passes the unattended gate, +//! then is admitted as queued input `schedi__` into a new or resumed Session. + +mod gate; +pub mod records; +mod run; + +use std::sync::Arc; + +use cyber_core::budget::Budget; +use cyber_core::cron::Cron; +use cyber_core::loops::{MAX_TEXT, Missed, Notify}; +use cyber_store::{Expected, NewEvent}; +use serde::Deserialize; +use sha2::{Digest, Sha256}; + +pub use records::{RunOutcome, RunRecord, Schedule, ScheduleStatus}; +pub(crate) use run::scheduled_run_current; + +use super::events::event; +use super::{Runtime, RuntimeError}; + +/// The model asks no approver here: the run continues without the action. +pub const NO_SCHEDULE_APPROVER: &str = "Denied: no approver in unattended schedule"; +/// The Mode a schedule runs in unless it names one. +pub const DEFAULT_MODE: &str = "dont-ask"; +/// The longest schedule name. +const MAX_NAME: usize = 80; + +/// A desktop notification outside any client (`loops-scheduling` → Completion +/// notifications): scheduled runs usually happen with no client attached. +pub trait DesktopNotifier: Send + Sync { + /// Show `title` and `body`; best effort, never blocking for long. + fn notify(&self, title: &str, body: &str); +} + +/// `POST /api/v1/schedules`, `cyber loops add`. +#[derive(Debug, Clone, Default, PartialEq, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ScheduleRequest { + /// A 5-field cron expression in the service's local time zone. + pub cron: String, + pub prompt: String, + /// An absolute directory; the request's Location when absent. + #[serde(default)] + pub directory: Option, + #[serde(default)] + pub name: Option, + #[serde(default)] + pub agent: Option, + /// `dont-ask` when absent; `bypass` needs `loops.allow_bypass` in user or managed + /// config. + #[serde(default)] + pub mode: Option, + /// The model of new run Sessions; the Location's default when absent. + #[serde(default)] + pub model: Option, + /// Resume this root Session for every run instead of creating one per run. + #[serde(default)] + pub session_id: Option, + #[serde(default)] + pub notify: Notify, + #[serde(default)] + pub missed: Missed, + #[serde(default)] + pub budget: Option, +} + +/// What the unattended gate needs to know about a directory (`ToolHost::schedule_policy`). +#[derive(Debug, Clone, Default, PartialEq)] +pub struct SchedulePolicy { + /// The checkout's configuration is trusted (`workspace-trust`). + pub trusted: bool, + /// `loops.allow_bypass` is true in user or managed config. + pub allow_bypass: bool, + /// `loops.jitter_seconds` (default 60; 0 turns jitter off). + pub jitter_seconds: u64, + /// `budgets.loop`, the default budget across runs. + pub budget: Option, +} + +pub(crate) fn now_ms() -> i64 { + chrono::Utc::now().timestamp_millis() +} + +/// The fixed offset of a schedule: SHA-256 of its ID modulo the jitter window. +pub fn jitter_ms(schedule_id: &str, jitter_seconds: u64) -> i64 { + let window = jitter_seconds.saturating_mul(1000); + if window == 0 { + return 0; + } + let digest = Sha256::digest(schedule_id.as_bytes()); + let mut bytes = [0u8; 8]; + bytes.copy_from_slice(&digest[..8]); + i64::try_from(u64::from_be_bytes(bytes) % window).unwrap_or(0) +} + +/// The next run after `now_ms`: the next occurrence after `now - jitter`, plus jitter, +/// which is always in the future. +pub fn next_run(cron: &str, jitter_ms: i64, now_ms: i64) -> Option { + let cron = Cron::parse(cron).ok()?; + let after = chrono::DateTime::from_timestamp_millis(now_ms.saturating_sub(jitter_ms))?; + let base = cron.next_after(after, &chrono::Local)?; + Some(base.timestamp_millis() + jitter_ms) +} + +fn not_found(id: &str) -> RuntimeError { + RuntimeError::ScheduleNotFound(id.to_owned()) +} + +fn validate(request: &ScheduleRequest) -> Result<(), String> { + Cron::parse(&request.cron)?; + let prompt = request.prompt.trim(); + if prompt.is_empty() || prompt.chars().count() > MAX_TEXT { + return Err(format!( + "A schedule's prompt has 1 to {MAX_TEXT} characters" + )); + } + if request + .name + .as_ref() + .is_some_and(|n| n.trim().is_empty() || n.chars().count() > MAX_NAME) + { + return Err(format!("A schedule's name has 1 to {MAX_NAME} characters")); + } + if let Some(budget) = &request.budget { + budget.validate()?; + } + Ok(()) +} + +impl Runtime { + /// Create a persistent schedule after the unattended gate admitted its directory, + /// Mode and Session; its first run is the next occurrence. + pub async fn create_schedule( + &self, + request: ScheduleRequest, + ) -> Result { + validate(&request).map_err(RuntimeError::Invalid)?; + let directory = request + .directory + .clone() + .ok_or_else(|| RuntimeError::Invalid("A schedule needs a directory".into()))?; + let mode = request.mode.clone().unwrap_or_else(|| DEFAULT_MODE.into()); + super::selection::validate_mode(&mode)?; + let model = request + .model + .clone() + .filter(|m| !m.trim().is_empty()) + .ok_or_else(|| RuntimeError::Invalid("A schedule needs a model".into()))?; + let schedule_id = cyber_core::ids::new_id("cron"); + let draft = gate::Draft { + directory: &directory, + agent: request.agent.as_deref().unwrap_or("build"), + mode: &mode, + session_id: request.session_id.as_deref(), + }; + let policy = self + .schedule_gate(&draft) + .await + .map_err(RuntimeError::Invalid)?; + let jitter = jitter_ms(&schedule_id, policy.jitter_seconds); + let now = now_ms(); + let next_due_ms = next_run(&request.cron, jitter, now) + .ok_or_else(|| RuntimeError::Invalid("The expression never matches".into()))?; + let created = records::Created { + name: request + .name + .map(|n| n.trim().to_owned()) + .unwrap_or_else(|| schedule_id.clone()), + schedule_id: schedule_id.clone(), + cron: request.cron.trim().to_owned(), + directory, + prompt: request.prompt.trim().to_owned(), + agent: request.agent, + mode, + model, + session_id: request.session_id, + notify: request.notify, + missed: request.missed, + budget: request.budget.or(policy.budget), + jitter_ms: jitter, + created_ms: now, + next_due_ms, + }; + self.inner.store.append( + &schedule_id, + Expected::Seq(-1), + vec![event(records::CREATED, &created)], + )?; + self.nudge_schedules(); + self.schedule(&schedule_id, false) + } + + /// Every schedule not removed, oldest first. + pub fn schedules(&self) -> Result, RuntimeError> { + Ok(self.inner.store.read(|db| Ok(records::list(db)?))?) + } + + /// One schedule; `with_runs` adds its most recent runs. + pub fn schedule(&self, id: &str, with_runs: bool) -> Result { + let key = id.to_owned(); + let found = self.inner.store.read(move |db| { + let Some(mut schedule) = records::load(db, &key)? else { + return Ok(None); + }; + if with_runs { + schedule.recent = records::runs(db, &key, records::RECENT_RUNS)?; + } + Ok(Some(schedule)) + })?; + found + .filter(|s| s.status != ScheduleStatus::Deleted) + .ok_or_else(|| not_found(id)) + } + + /// Pause an active schedule; a run in flight finishes. + pub fn pause_schedule(&self, id: &str) -> Result { + self.update_schedule(id, |schedule, _| match schedule.status { + ScheduleStatus::Active | ScheduleStatus::Paused => Ok(records::Updated { + schedule_id: schedule.id.clone(), + status: ScheduleStatus::Paused, + reason: Some("paused by the user".into()), + next_due_ms: None, + }), + _ => Err(RuntimeError::Invalid(format!( + "Schedule {} is {} and cannot be paused", + schedule.id, + schedule.status.as_str() + ))), + })?; + self.schedule(id, false) + } + + /// Resume a paused schedule at its next occurrence. One that exhausted its budget + /// stays stopped: its budget is fixed, so it is removed and added again. + pub fn resume_schedule(&self, id: &str) -> Result { + self.update_schedule(id, |schedule, now| match schedule.status { + ScheduleStatus::Active | ScheduleStatus::Paused => Ok(records::Updated { + schedule_id: schedule.id.clone(), + status: ScheduleStatus::Active, + reason: None, + next_due_ms: next_run(&schedule.cron, schedule.jitter_ms, now), + }), + _ => Err(RuntimeError::Invalid(format!( + "Schedule {} stopped ({}); remove it and add a new one", + schedule.id, + schedule.reason.as_deref().unwrap_or("budget exceeded") + ))), + })?; + self.nudge_schedules(); + self.schedule(id, false) + } + + /// Remove a schedule; its history stays in the store and a run in flight finishes. + pub fn remove_schedule(&self, id: &str) -> Result<(), RuntimeError> { + self.update_schedule(id, |schedule, _| { + Ok(records::Updated { + schedule_id: schedule.id.clone(), + status: ScheduleStatus::Deleted, + reason: Some("removed by the user".into()), + next_due_ms: None, + }) + }) + } + + /// Decide and record one `schedule.updated` in the writer transaction. + fn update_schedule( + &self, + id: &str, + decide: impl FnOnce(&Schedule, i64) -> Result + Send + 'static, + ) -> Result<(), RuntimeError> { + let key = id.to_owned(); + let missing = not_found(id); + let (_, outcome) = self + .inner + .store + .append_checked(id, Expected::Any, move |tx| { + let schedule = + records::load(tx, &key)?.filter(|s| s.status != ScheduleStatus::Deleted); + let decided = match schedule { + Some(schedule) => decide(&schedule, now_ms()), + None => Err(missing), + }; + Ok(match decided { + Ok(updated) => (vec![event(records::UPDATED, &updated)], Ok(())), + Err(error) => (Vec::new(), Err(error)), + }) + })?; + outcome + } + + /// Set the desktop notifier scheduled runs use (the App wires the OS one). + pub fn set_desktop_notifier(&self, notifier: Arc) { + let _ = self.inner.desktop_notifier.set(notifier); + } + + /// Rebuild `schedule` and `schedule_run` from the `schedule.*` events. + pub fn rebuild_schedules(&self) -> Result { + Ok(self.inner.store.reproject( + &records::TABLES, + records::PREFIX, + std::sync::Arc::new(records::project), + )?) + } +} + +/// Append prepared schedule events to one schedule's stream. +pub(crate) fn append( + runtime: &Runtime, + schedule_id: &str, + events: Vec, +) -> Result<(), RuntimeError> { + if events.is_empty() { + return Ok(()); + } + runtime + .inner + .store + .append(schedule_id, Expected::Any, events) + .map(drop) + .map_err(RuntimeError::from) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn jitter_is_deterministic_and_bounded() { + let a = jitter_ms("cron_01ABC", 60); + assert_eq!(a, jitter_ms("cron_01ABC", 60)); + assert!((0..60_000).contains(&a)); + assert_ne!(a, jitter_ms("cron_01ABD", 60), "IDs spread"); + assert_eq!(jitter_ms("cron_01ABC", 0), 0); + } + + #[test] + fn the_next_run_includes_jitter_and_lies_ahead() { + let jitter = 30_000; + let now = chrono::Utc::now().timestamp_millis(); + let next = next_run("* * * * *", jitter, now).unwrap(); + assert!(next > now, "{next} > {now}"); + assert_eq!((next - jitter) % 60_000, 0, "a whole minute plus jitter"); + assert!(next - now <= 60_000 + jitter); + } + + #[test] + fn requests_are_validated() { + let ok = ScheduleRequest { + cron: "0 2 * * *".into(), + prompt: "review".into(), + ..ScheduleRequest::default() + }; + assert!(validate(&ok).is_ok()); + let bad_cron = ScheduleRequest { + cron: "0 25 * * *".into(), + ..ok.clone() + }; + assert!( + validate(&bad_cron) + .unwrap_err() + .contains("Invalid cron expression") + ); + let empty = ScheduleRequest { + prompt: " ".into(), + ..ok + }; + assert!(validate(&empty).is_err()); + } +} diff --git a/crates/cyber-server/src/runtime/schedules/records.rs b/crates/cyber-server/src/runtime/schedules/records.rs new file mode 100644 index 000000000..4e562460b --- /dev/null +++ b/crates/cyber-server/src/runtime/schedules/records.rs @@ -0,0 +1,577 @@ +//! Durable schedule records (`loops-scheduling` → Persistent local schedules, Loop events +//! and hooks): the `schedule.*` events of each schedule's own stream, validated on +//! append, and their projector into `schedule` and `schedule_run`, which the sweep, the +//! run lifecycle and the routes read. + +use cyber_core::budget::Budget; +use cyber_core::loops::{Missed, Notify}; +use rusqlite::{Connection, OptionalExtension, Transaction, params}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use cyber_store::{EventRegistry, StoredEvent}; + +pub const CREATED: &str = "schedule.created.1"; +pub const UPDATED: &str = "schedule.updated.1"; +pub const RUN: &str = "schedule.run.1"; + +/// The projection tables, children first, in the order a rebuild clears them. +pub const TABLES: [&str; 2] = ["schedule_run", "schedule"]; +/// The event type prefix every schedule record shares. +pub const PREFIX: &str = "schedule."; +/// Runs `show` lists, newest first. +pub const RECENT_RUNS: usize = 20; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ScheduleStatus { + Active, + Paused, + BudgetExceeded, + Deleted, +} + +impl ScheduleStatus { + pub fn as_str(self) -> &'static str { + match self { + Self::Active => "active", + Self::Paused => "paused", + Self::BudgetExceeded => "budget_exceeded", + Self::Deleted => "deleted", + } + } + + fn parse(text: &str) -> Self { + match text { + "active" => Self::Active, + "paused" => Self::Paused, + "budget_exceeded" => Self::BudgetExceeded, + _ => Self::Deleted, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Phase { + /// Admitted to its Session; it runs when the Session is free. + Started, + /// The run's `schedule_wakeup` (`noop` and `reason`). + Reported, + Ended, +} + +/// How a run ended. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum RunOutcome { + Completed, + Failed, + Interrupted, + /// The gate refused it: untrusted or missing directory, `bypass` not allowed, a + /// Session it cannot use. + Refused, + /// Its time came while the previous run (or the target Session) was still busy. + SkippedOverlap, + /// Its time passed while the service was not running (missed-run policy `skip`). + SkippedMissed, +} + +impl RunOutcome { + pub fn as_str(self) -> &'static str { + match self { + Self::Completed => "completed", + Self::Failed => "failed", + Self::Interrupted => "interrupted", + Self::Refused => "refused", + Self::SkippedOverlap => "skipped_overlap", + Self::SkippedMissed => "skipped_missed", + } + } +} + +/// `schedule.created.1`: everything a run needs, fixed for the schedule's life. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Created { + pub schedule_id: String, + pub name: String, + pub cron: String, + pub directory: String, + pub prompt: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub agent: Option, + pub mode: String, + pub model: String, + /// Each run resumes this Session; `None` creates a new Session per run. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub session_id: Option, + pub notify: Notify, + pub missed: Missed, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub budget: Option, + /// The fixed offset added to every occurrence (`loops.jitter_seconds`). + pub jitter_ms: i64, + pub created_ms: i64, + pub next_due_ms: i64, +} + +/// `schedule.updated.1`: pause, resume, budget stop or removal. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Updated { + pub schedule_id: String, + pub status: ScheduleStatus, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reason: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next_due_ms: Option, +} + +/// `schedule.run.1`: a run's start, its reported `noop`, or its end. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Run { + pub schedule_id: String, + pub run_id: String, + pub n: u64, + pub phase: Phase, + pub due_ms: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub session_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub message_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub outcome: Option, + #[serde(default)] + pub noop: bool, + #[serde(default)] + pub duration_ms: i64, + #[serde(default)] + pub cost: f64, + #[serde(default)] + pub tokens: u64, + #[serde(default)] + pub turns: u64, + /// Session totals at admission, so the end reports a delta. + #[serde(default)] + pub cost_before: f64, + #[serde(default)] + pub tokens_before: u64, + #[serde(default)] + pub turns_before: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reason: Option, + /// When the next run is due; `None` keeps it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next_due_ms: Option, +} + +impl Run { + /// A run record of `phase` with nothing measured yet. + pub fn new(schedule_id: &str, run_id: &str, n: u64, phase: Phase, due_ms: i64) -> Self { + Self { + schedule_id: schedule_id.to_owned(), + run_id: run_id.to_owned(), + n, + phase, + due_ms, + session_id: None, + message_id: None, + outcome: None, + noop: false, + duration_ms: 0, + cost: 0.0, + tokens: 0, + turns: 0, + cost_before: 0.0, + tokens_before: 0, + turns_before: 0, + reason: None, + next_due_ms: None, + } + } +} + +/// A schedule as the routes and the CLI show it. +#[derive(Debug, Clone, PartialEq, Serialize, schemars::JsonSchema)] +pub struct Schedule { + pub id: String, + pub name: String, + pub cron: String, + pub directory: String, + pub prompt: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub agent: Option, + pub mode: String, + pub model: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub session_id: Option, + pub notify: Notify, + pub missed: Missed, + #[serde(skip_serializing_if = "Option::is_none")] + pub budget: Option, + pub jitter_ms: i64, + pub status: ScheduleStatus, + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + /// The next run, jitter included; `None` while paused or ended. + pub next_due_ms: Option, + /// The run in flight. + #[serde(skip_serializing_if = "Option::is_none")] + pub inflight: Option, + pub runs: u64, + pub cost_usd: f64, + pub tokens: u64, + pub turns: u64, + pub created_ms: i64, + pub updated_ms: i64, + /// The most recent runs, newest first (`show` only). + #[serde(skip_serializing_if = "Vec::is_empty")] + pub recent: Vec, +} + +/// One run as `show` lists it. +#[derive(Debug, Clone, PartialEq, Serialize, schemars::JsonSchema)] +pub struct RunRecord { + pub run_id: String, + pub n: u64, + pub due_ms: i64, + #[serde(skip_serializing_if = "Option::is_none")] + pub started_ms: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub ended_ms: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub session_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub message_id: Option, + /// A [`RunOutcome`], or `running`. + pub outcome: String, + pub noop: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + pub cost: f64, + pub tokens: u64, + pub turns: u64, + #[serde(skip)] + pub cost_before: f64, + #[serde(skip)] + pub tokens_before: u64, + #[serde(skip)] + pub turns_before: u64, +} + +pub(crate) fn register(registry: &mut EventRegistry) { + registry + .register_with(CREATED, validate_created) + .and_then(|r| r.register_with(UPDATED, |v| decode::(v).map(drop))) + .and_then(|r| r.register_with(RUN, validate_run)) + .expect("valid schedule events"); +} + +fn validate_created(data: &Value) -> Result<(), String> { + let c: Created = decode(data)?; + if !cyber_core::loops::is_cron_id(&c.schedule_id) { + return Err(format!("schedule ID {:?} is not a cron_ ID", c.schedule_id)); + } + cyber_core::cron::Cron::parse(&c.cron)?; + if c.prompt.trim().is_empty() || c.directory.is_empty() || c.mode.is_empty() { + return Err("a schedule has a prompt, a directory and a Mode".into()); + } + if c.jitter_ms < 0 { + return Err("a schedule's jitter is not negative".into()); + } + Ok(()) +} + +fn validate_run(data: &Value) -> Result<(), String> { + let run: Run = decode(data)?; + match (run.phase, run.outcome) { + (Phase::Ended, None) => Err("an ended run has an outcome".into()), + (Phase::Started | Phase::Reported, Some(_)) => { + Err("only an ended run has an outcome".into()) + } + (Phase::Started, None) if run.session_id.is_none() || run.message_id.is_none() => { + Err("a started run names its Session and message".into()) + } + _ => Ok(()), + } +} + +fn decode(data: &Value) -> Result { + serde_json::from_value(data.clone()).map_err(|error| error.to_string()) +} + +/// Write `schedule` and `schedule_run` in the event transaction. +pub(crate) fn project(tx: &Transaction<'_>, e: &StoredEvent) -> Result<(), String> { + if !e.kind.starts_with(PREFIX) { + return Ok(()); + } + let result = match e.kind.as_str() { + CREATED => project_created(tx, &decode(&e.data)?, e.time_ms), + UPDATED => { + let u: Updated = decode(&e.data)?; + tx.execute( + "UPDATE schedule SET status = ?2, reason = ?3, + next_due_ms = COALESCE(?4, next_due_ms), updated_ms = ?5 + WHERE id = ?1", + params![ + u.schedule_id, + u.status.as_str(), + u.reason, + u.next_due_ms, + e.time_ms + ], + ) + .map(drop) + } + RUN => project_run(tx, &decode(&e.data)?, e.time_ms), + _ => return Ok(()), + }; + result.map_err(|error| error.to_string()) +} + +fn project_created(tx: &Transaction<'_>, c: &Created, time_ms: i64) -> rusqlite::Result<()> { + let spec = serde_json::to_string(c).expect("a schedule serializes"); + tx.execute( + "INSERT INTO schedule (id, name, cron, directory, spec, status, next_due_ms, + created_ms, updated_ms) + VALUES (?1, ?2, ?3, ?4, ?5, 'active', ?6, ?7, ?8)", + params![ + c.schedule_id, + c.name, + c.cron, + c.directory, + spec, + c.next_due_ms, + c.created_ms, + time_ms + ], + ) + .map(drop) +} + +fn project_run(tx: &Transaction<'_>, r: &Run, time_ms: i64) -> rusqlite::Result<()> { + match r.phase { + Phase::Started => { + tx.execute( + "INSERT INTO schedule_run (id, schedule_id, n, due_ms, started_ms, session_id, + message_id, outcome, cost_before, tokens_before, turns_before) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, 'running', ?8, ?9, ?10)", + params![ + r.run_id, + r.schedule_id, + int(r.n), + r.due_ms, + time_ms, + r.session_id, + r.message_id, + r.cost_before, + int(r.tokens_before), + int(r.turns_before) + ], + )?; + tx.execute( + "UPDATE schedule SET inflight = ?2, runs = ?3, + next_due_ms = COALESCE(?4, next_due_ms), updated_ms = ?5 + WHERE id = ?1", + params![r.schedule_id, r.run_id, int(r.n), r.next_due_ms, time_ms], + ) + .map(drop) + } + Phase::Reported => tx + .execute( + "UPDATE schedule_run SET noop = ?2, reason = ?3 WHERE id = ?1", + params![r.run_id, r.noop, r.reason], + ) + .map(drop), + Phase::Ended => project_ended(tx, r, time_ms), + } +} + +fn project_ended(tx: &Transaction<'_>, r: &Run, time_ms: i64) -> rusqlite::Result<()> { + let outcome = r.outcome.map_or("failed", RunOutcome::as_str); + let updated = tx.execute( + "UPDATE schedule_run SET outcome = ?2, ended_ms = ?3, noop = ?4, reason = ?5, + cost_usd = ?6, tokens = ?7, turns = ?8 + WHERE id = ?1", + params![ + r.run_id, + outcome, + time_ms, + r.noop, + r.reason, + r.cost, + int(r.tokens), + int(r.turns) + ], + )?; + if updated == 0 { + // A run that never started: skipped or refused. + tx.execute( + "INSERT INTO schedule_run (id, schedule_id, n, due_ms, ended_ms, session_id, + outcome, reason) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + params![ + r.run_id, + r.schedule_id, + int(r.n), + r.due_ms, + time_ms, + r.session_id, + outcome, + r.reason + ], + )?; + } + tx.execute( + "UPDATE schedule SET + inflight = CASE WHEN inflight = ?2 THEN NULL ELSE inflight END, + next_due_ms = COALESCE(?3, next_due_ms), + cost_usd = cost_usd + ?4, tokens = tokens + ?5, turns = turns + ?6, updated_ms = ?7 + WHERE id = ?1", + params![ + r.schedule_id, + r.run_id, + r.next_due_ms, + r.cost, + int(r.tokens), + int(r.turns), + time_ms + ], + ) + .map(drop) +} + +/// A count as SQLite stores it. +fn int(value: u64) -> i64 { + i64::try_from(value).unwrap_or(i64::MAX) +} + +fn count(row: &rusqlite::Row<'_>, column: &str) -> rusqlite::Result { + Ok(u64::try_from(row.get::<_, i64>(column)?).unwrap_or(0)) +} + +fn schedule_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { + let spec: String = row.get("spec")?; + let c: Created = serde_json::from_str(&spec).map_err(|error| { + rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(error)) + })?; + let status: String = row.get("status")?; + let status = ScheduleStatus::parse(&status); + Ok(Schedule { + id: c.schedule_id, + name: c.name, + cron: c.cron, + directory: c.directory, + prompt: c.prompt, + agent: c.agent, + mode: c.mode, + model: c.model, + session_id: c.session_id, + notify: c.notify, + missed: c.missed, + budget: c.budget, + jitter_ms: c.jitter_ms, + status, + reason: row.get("reason")?, + next_due_ms: if status == ScheduleStatus::Active { + row.get("next_due_ms")? + } else { + None + }, + inflight: row.get("inflight")?, + runs: count(row, "runs")?, + cost_usd: row.get("cost_usd")?, + tokens: count(row, "tokens")?, + turns: count(row, "turns")?, + created_ms: row.get("created_ms")?, + updated_ms: row.get("updated_ms")?, + recent: Vec::new(), + }) +} + +fn run_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { + Ok(RunRecord { + run_id: row.get("id")?, + n: count(row, "n")?, + due_ms: row.get("due_ms")?, + started_ms: row.get("started_ms")?, + ended_ms: row.get("ended_ms")?, + session_id: row.get("session_id")?, + message_id: row.get("message_id")?, + outcome: row.get("outcome")?, + noop: row.get("noop")?, + reason: row.get("reason")?, + cost: row.get("cost_usd")?, + tokens: count(row, "tokens")?, + turns: count(row, "turns")?, + cost_before: row.get("cost_before")?, + tokens_before: count(row, "tokens_before")?, + turns_before: count(row, "turns_before")?, + }) +} + +/// One schedule, deleted ones included. +pub(crate) fn load(db: &Connection, id: &str) -> rusqlite::Result> { + db.query_row("SELECT * FROM schedule WHERE id = ?1", [id], schedule_row) + .optional() +} + +/// Every schedule not removed, oldest first. +pub(crate) fn list(db: &Connection) -> rusqlite::Result> { + let mut stmt = + db.prepare("SELECT * FROM schedule WHERE status != 'deleted' ORDER BY created_ms, id")?; + stmt.query_map([], schedule_row)?.collect() +} + +/// A schedule's runs, newest first. +pub(crate) fn runs(db: &Connection, id: &str, limit: usize) -> rusqlite::Result> { + let mut stmt = db.prepare( + "SELECT * FROM schedule_run WHERE schedule_id = ?1 ORDER BY n DESC, rowid DESC LIMIT ?2", + )?; + stmt.query_map(params![id, limit as i64], run_row)? + .collect() +} + +/// One run. +pub(crate) fn run(db: &Connection, run_id: &str) -> rusqlite::Result> { + db.query_row( + "SELECT * FROM schedule_run WHERE id = ?1", + [run_id], + run_row, + ) + .optional() +} + +/// Active schedules due at `now_ms`, oldest due first. +pub(crate) fn due(db: &Connection, now_ms: i64) -> rusqlite::Result> { + let mut stmt = db.prepare( + "SELECT id FROM schedule + WHERE status = 'active' AND next_due_ms IS NOT NULL AND next_due_ms <= ?1 + ORDER BY next_due_ms, id", + )?; + stmt.query_map([now_ms], |r| r.get(0))?.collect() +} + +/// Runs in flight in `session_id`: `(schedule, run)`. +pub(crate) fn running_in( + db: &Connection, + session_id: &str, +) -> rusqlite::Result> { + let mut stmt = db.prepare( + "SELECT schedule_id, id FROM schedule_run + WHERE session_id = ?1 AND outcome = 'running' ORDER BY n", + )?; + stmt.query_map([session_id], |r| Ok((r.get(0)?, r.get(1)?)))? + .collect() +} + +/// Schedules the restore visits: active ones and any with a run in flight. +pub(crate) fn restorable(db: &Connection) -> rusqlite::Result> { + let mut stmt = db.prepare( + "SELECT id FROM schedule WHERE status = 'active' OR inflight IS NOT NULL ORDER BY id", + )?; + stmt.query_map([], |r| r.get(0))?.collect() +} diff --git a/crates/cyber-server/src/runtime/schedules/run.rs b/crates/cyber-server/src/runtime/schedules/run.rs new file mode 100644 index 000000000..c8fb274c6 --- /dev/null +++ b/crates/cyber-server/src/runtime/schedules/run.rs @@ -0,0 +1,830 @@ +//! Running schedules: the sweep starts due runs through the unattended gate, the Drain's +//! idle exit ends them, and startup restores what a stopped service left behind. +//! +//! A run's start and end are each recorded by a decision made inside the writer +//! transaction (the run must still be in flight to end, the schedule free to start), so +//! a sweep, `run now`, a nudge and the idle hook cannot record a transition twice. Work +//! that must not hold the writer (the gate, Session creation, admission) happens between. + +use std::sync::PoisonError; +use std::time::Duration; + +use cyber_core::loops::{Missed, Notify}; +use cyber_store::Expected; +use serde_json::json; + +use super::gate::{Draft, plain}; +use super::records::{self, Phase, Run, RunOutcome, RunRecord, Schedule, ScheduleStatus}; +use super::{append, next_run, now_ms}; +use crate::runtime::events::event; +use crate::runtime::{ + CreateSession, InputStatus, Notification, Runtime, RuntimeError, SessionState, +}; + +/// How often the background sweep looks for due runs. +const SWEEP_EVERY: Duration = Duration::from_secs(5); +/// The longest result a notification shows. +const RESULT_EXCERPT: usize = 160; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Trigger { + /// Its time came. + Due, + /// `cyber loops run`: now, outside the schedule. + Manual, +} + +fn warn(what: &str, error: &RuntimeError) { + cyber_core::log::warn( + "schedules", + what, + serde_json::json!({ "error": error.to_string() }), + ); +} + +/// The deterministic inbox ID of run `n`. +pub(crate) fn message_id(schedule_id: &str, n: u64) -> String { + format!("schedi_{}_{n}", schedule_id.trim_start_matches("cron_")) +} + +/// Whether `id` is a scheduled run's inbox ID. +pub(crate) fn is_run_message(id: &str) -> bool { + id.starts_with("schedi_") +} + +/// Why `schedule` must not run again: an exhausted budget, as ` /`. +fn budget_exceeded(schedule: &Schedule, now: i64) -> Option { + let budget = schedule.budget.as_ref()?; + if let Some(max) = budget.max_cost_usd + && schedule.cost_usd >= max + { + return Some(format!("max_cost_usd {:.2}/{max:.2}", schedule.cost_usd)); + } + if let Some(max) = budget.max_tokens + && schedule.tokens >= max + { + return Some(format!("max_tokens {}/{max}", schedule.tokens)); + } + if let Some(max) = budget.max_turns + && schedule.turns >= max + { + return Some(format!("max_turns {}/{max}", schedule.turns)); + } + let wall = budget.max_wall_seconds?; + let elapsed = (now - schedule.created_ms) as f64 / 1000.0; + (elapsed >= wall).then(|| format!("max_wall_seconds {elapsed:.0}/{wall:.0}")) +} + +/// Session totals a run's end is measured against: cost, tokens, model steps. +fn totals(state: &SessionState) -> (f64, u64, u64) { + let usage = &state.totals.usage; + let tokens = usage.input + usage.output + usage.reasoning; + (state.totals.cost, tokens, u64::from(state.totals.steps)) +} + +fn promoted(state: &SessionState, message_id: &str) -> bool { + state + .inbox + .iter() + .any(|row| row.message_id == message_id && row.status == InputStatus::Promoted) +} + +/// The Session's current run is a scheduled one: its last promoted input is `schedi_`. +pub(crate) fn scheduled_run_current(state: &SessionState) -> bool { + state + .inbox + .iter() + .filter_map(|row| row.promoted_seq.map(|seq| (seq, row))) + .max_by_key(|(seq, _)| *seq) + .is_some_and(|(_, row)| is_run_message(&row.message_id)) +} + +fn outcome_of(status: Option<&str>) -> RunOutcome { + match status { + Some(s) if s.starts_with("failed") => RunOutcome::Failed, + Some(_) => RunOutcome::Interrupted, + None => RunOutcome::Completed, + } +} + +fn clip(text: &str, max: usize) -> String { + let line = text.split_whitespace().collect::>().join(" "); + if line.chars().count() <= max { + return line; + } + let cut: String = line.chars().take(max - 1).collect(); + format!("{}…", cut.trim_end()) +} + +/// Whether an ended run notifies under `notify`; a refused run counts as a failure. +fn run_notifies(notify: Notify, run: &Run) -> bool { + match run.outcome { + Some(RunOutcome::Completed) => notify.notifies(false, run.noop), + Some(RunOutcome::Failed | RunOutcome::Refused) => notify.notifies(true, false), + _ => notify == Notify::Always, + } +} + +/// The one-line result of an ended run. +fn run_result(run: &Run) -> String { + let outcome = run.outcome.map_or("ended", RunOutcome::as_str); + match run.reason.as_deref().map(|r| clip(r, RESULT_EXCERPT)) { + Some(reason) => format!("run {} {outcome}: {reason}", run.n), + None => format!("run {} {outcome}", run.n), + } +} + +/// A run record that ends a run which never started (skipped or refused). +fn unstarted( + schedule: &Schedule, + n: u64, + due_ms: i64, + outcome: RunOutcome, + reason: String, + next_due_ms: Option, +) -> Run { + let mut run = Run::new( + &schedule.id, + &cyber_core::ids::new_id("srun"), + n, + Phase::Ended, + due_ms, + ); + run.outcome = Some(outcome); + run.reason = Some(reason); + run.next_due_ms = next_due_ms; + run +} + +impl Runtime { + /// Start every due run (and record skipped ones) at `now_ms`; the number of schedules + /// visited. Tests drive it with a chosen time. + pub async fn sweep_schedules(&self, now_ms: i64) -> Result { + let due = self + .inner + .store + .read(move |db| Ok(records::due(db, now_ms)?))?; + for id in &due { + if self.is_shutting_down() { + break; + } + if let Err(error) = self.run_due_schedule(id, now_ms).await { + warn("a scheduled run failed to start", &error); + } + } + Ok(due.len()) + } + + /// `cyber loops run`: start a run now, outside the schedule (also when paused); the + /// run's ID. + pub async fn run_schedule_now(&self, id: &str) -> Result { + let schedule = self.schedule(id, false)?; + if schedule.inflight.is_some() { + return Err(RuntimeError::Invalid(format!( + "Schedule {id} has a run in flight" + ))); + } + if !matches!( + schedule.status, + ScheduleStatus::Active | ScheduleStatus::Paused + ) { + return Err(RuntimeError::Invalid(format!( + "Schedule {id} is {}", + schedule.status.as_str() + ))); + } + self.start_run(schedule, now_ms(), Trigger::Manual).await + } + + async fn run_due_schedule(&self, id: &str, now: i64) -> Result<(), RuntimeError> { + let key = id.to_owned(); + let Some(schedule) = self + .inner + .store + .read(move |db| Ok(records::load(db, &key)?))? + else { + return Ok(()); + }; + if schedule.status != ScheduleStatus::Active + || schedule.next_due_ms.is_none_or(|due| due > now) + { + return Ok(()); + } + if schedule.inflight.is_some() { + let next = next_run(&schedule.cron, schedule.jitter_ms, now); + let due = schedule.next_due_ms.unwrap_or(now); + let skip = unstarted( + &schedule, + schedule.runs + 1, + due, + RunOutcome::SkippedOverlap, + "the previous run was still running".into(), + next, + ); + return self.end_unstarted(&schedule, skip).await; + } + self.start_run(schedule, now, Trigger::Due).await.map(drop) + } + + /// Gate, prepare the Session, record the start and admit the prompt; the run ID. + async fn start_run( + &self, + schedule: Schedule, + now: i64, + trigger: Trigger, + ) -> Result { + let (due, next) = match trigger { + Trigger::Due => ( + schedule.next_due_ms.unwrap_or(now), + next_run(&schedule.cron, schedule.jitter_ms, now), + ), + Trigger::Manual => (now, None), + }; + let n = schedule.runs + 1; + if let Some(reason) = budget_exceeded(&schedule, now) { + self.stop_for_budget(&schedule, &reason).await; + return Err(RuntimeError::Invalid(format!( + "Schedule {} exceeded its budget: {reason}", + schedule.id + ))); + } + let draft = Draft { + directory: &schedule.directory, + agent: schedule.agent.as_deref().unwrap_or("build"), + mode: &schedule.mode, + session_id: schedule.session_id.as_deref(), + }; + if let Err(reason) = self.schedule_gate(&draft).await { + let refused = unstarted(&schedule, n, due, RunOutcome::Refused, reason, next); + let run_id = refused.run_id.clone(); + self.end_unstarted(&schedule, refused).await?; + return Ok(run_id); + } + let session_id = match self.run_session(&schedule, now).await { + Ok(id) => id, + Err((outcome, reason)) => { + let failed = unstarted(&schedule, n, due, outcome, reason, next); + let run_id = failed.run_id.clone(); + self.end_unstarted(&schedule, failed).await?; + return Ok(run_id); + } + }; + self.admit_run(&schedule, session_id, n, due, next).await + } + + /// The Session a run uses: a new unattended one, or the schedule's own Session switched + /// to the schedule's Mode (a busy one is skipped). + async fn run_session( + &self, + schedule: &Schedule, + now: i64, + ) -> Result { + let failed = |error: RuntimeError| (RunOutcome::Failed, plain(&error)); + if let Some(id) = &schedule.session_id { + if self.is_running(id) { + return Err((RunOutcome::SkippedOverlap, format!("Session {id} was busy"))); + } + self.switch_mode(id, &schedule.mode).await.map_err(failed)?; + return Ok(id.clone()); + } + let title = format!( + "{} · {}", + schedule.name, + cyber_core::cron::local_time_text(now) + ); + let info = self + .create_session(CreateSession { + directory: schedule.directory.clone(), + model: schedule.model.clone(), + model_is_default: true, + agent: schedule.agent.clone(), + mode: Some(schedule.mode.clone()), + title: Some(title), + unattended: true, + ..CreateSession::default() + }) + .await + .map_err(failed)?; + Ok(info.id) + } + + /// Record the start, then admit the prompt queued; a refused admission ends the run. + async fn admit_run( + &self, + schedule: &Schedule, + session_id: String, + n: u64, + due: i64, + next: Option, + ) -> Result { + let message = message_id(&schedule.id, n); + let (cost_before, tokens_before, turns_before) = totals(&self.state(&session_id).await?); + let mut started = Run::new( + &schedule.id, + &cyber_core::ids::new_id("srun"), + n, + Phase::Started, + due, + ); + started.session_id = Some(session_id.clone()); + started.message_id = Some(message.clone()); + started.cost_before = cost_before; + started.tokens_before = tokens_before; + started.turns_before = turns_before; + started.next_due_ms = next; + let run_id = started.run_id.clone(); + if !self.record_schedule_start(started)? { + return Ok(run_id); + } + let admitted = match self + .prompt_admission(&session_id, &schedule.prompt, message) + .await + { + Ok(admission) => self + .admit_loop_iteration(&session_id, admission, Vec::new()) + .await + .map(drop), + Err(error) => Err(error), + }; + if let Err(error) = admitted { + self.end_run( + &schedule.id, + &run_id, + RunOutcome::Failed, + Some(plain(&error)), + ) + .await; + } + Ok(run_id) + } + + /// Record a run's start if the schedule is still free and at `n - 1` runs. + fn record_schedule_start(&self, started: Run) -> Result { + let id = started.schedule_id.clone(); + let (_, recorded) = self + .inner + .store + .append_checked(&id, Expected::Any, move |tx| { + let free = records::load(tx, &started.schedule_id)?.is_some_and(|s| { + s.inflight.is_none() + && s.runs + 1 == started.n + && s.status != ScheduleStatus::Deleted + }); + Ok(if free { + (vec![event(records::RUN, &started)], true) + } else { + (Vec::new(), false) + }) + })?; + Ok(recorded) + } + + /// Record a run that never started, then notify. + async fn end_unstarted(&self, schedule: &Schedule, run: Run) -> Result<(), RuntimeError> { + append(self, &schedule.id, vec![event(records::RUN, &run)])?; + self.run_followups(schedule, &run).await; + Ok(()) + } + + /// End a started run with `outcome` unless it already ended; measured against its + /// Session's totals. Then the budget check, notifications and the hook. + async fn end_run( + &self, + schedule_id: &str, + run_id: &str, + outcome: RunOutcome, + reason: Option, + ) { + if let Err(error) = self.try_end_run(schedule_id, run_id, outcome, reason).await { + warn("ending a scheduled run failed", &error); + } + } + + async fn try_end_run( + &self, + schedule_id: &str, + run_id: &str, + outcome: RunOutcome, + reason: Option, + ) -> Result<(), RuntimeError> { + let key = run_id.to_owned(); + let Some(record) = self + .inner + .store + .read(move |db| Ok(records::run(db, &key)?))? + else { + return Ok(()); + }; + let totals = match &record.session_id { + Some(id) => self.state(id).await.map(|s| totals(&s)).ok(), + None => None, + }; + let ended = ended_run(schedule_id, &record, outcome, reason, totals); + let recorded = ended.clone(); + let (_, done) = self + .inner + .store + .append_checked(schedule_id, Expected::Any, move |tx| { + let running = + records::run(tx, &recorded.run_id)?.is_some_and(|r| r.outcome == "running"); + Ok(if running { + (vec![event(records::RUN, &recorded)], true) + } else { + (Vec::new(), false) + }) + })?; + if !done { + return Ok(()); + } + let schedule = self.schedule(schedule_id, false).ok(); + if let Some(schedule) = schedule { + self.run_followups(&schedule, &ended).await; + if let Some(reason) = budget_exceeded(&schedule, now_ms()) { + self.stop_for_budget(&schedule, &reason).await; + } + } + self.nudge_schedules(); + Ok(()) + } + + /// Stop `schedule` with `budget_exceeded`, and notify unless `never`. + async fn stop_for_budget(&self, schedule: &Schedule, reason: &str) { + let updated = records::Updated { + schedule_id: schedule.id.clone(), + status: ScheduleStatus::BudgetExceeded, + reason: Some(reason.to_owned()), + next_due_ms: None, + }; + if let Err(error) = append(self, &schedule.id, vec![event(records::UPDATED, &updated)]) { + return warn("stopping a schedule failed", &error); + } + if schedule.notify != Notify::Never { + let body = format!("stopped (budget_exceeded): {reason}"); + self.schedule_notify(schedule, None, &body).await; + } + } + + /// Notifications and the `ScheduleRun` hook of an ended run. + async fn run_followups(&self, schedule: &Schedule, run: &Run) { + if run_notifies(schedule.notify, run) { + self.schedule_notify(schedule, run.session_id.as_deref(), &run_result(run)) + .await; + } + let Some(session_id) = run.session_id.as_deref() else { + return; + }; + let Ok(handle) = self.inner.handle(session_id).await else { + return; + }; + let fields = json!({ + "schedule": { + "id": schedule.id, + "name": schedule.name, + "cron": schedule.cron, + "directory": schedule.directory, + }, + "run": { + "run_id": run.run_id, + "n": run.n, + "outcome": run.outcome, + "noop": run.noop, + "duration_ms": run.duration_ms, + "cost": run.cost, + "tokens": run.tokens, + "turns": run.turns, + "reason": run.reason, + }, + }); + let hook = self + .inner + .lifecycle_hook(&handle, "ScheduleRun", schedule.id.clone(), fields) + .await; + self.inner.observe_lifecycle(hook).await; + } + + /// A notification in the run's Session (clients and remote devices) and on the desktop. + async fn schedule_notify(&self, schedule: &Schedule, session_id: Option<&str>, body: &str) { + let title = format!("Schedule {}", clip(&schedule.name, 60)); + if let Some(session_id) = session_id { + let notification = Notification { + call_id: schedule.id.clone(), + title: title.clone(), + body: body.to_owned(), + }; + // Past the per-Session rate limit it is dropped; the run record keeps it. + let _ = self.record_notification(session_id, notification).await; + } + if let Some(notifier) = self.inner.desktop_notifier.get() { + notifier.notify(&title, body); + } + } + + /// The Session's Drain ended (`drain::run`): end every scheduled run it ran. + pub(crate) async fn schedules_drain_ended(&self, session_id: &str, status: Option<&str>) { + if self.is_shutting_down() { + return; + } + let id = session_id.to_owned(); + let running = match self + .inner + .store + .read(move |db| Ok(records::running_in(db, &id)?)) + { + Ok(running) if !running.is_empty() => running, + Ok(_) => return, + Err(error) => { + return warn("reading scheduled runs failed", &RuntimeError::Store(error)); + } + }; + let Ok(state) = self.state(session_id).await else { + return; + }; + let status = status.map(str::to_owned).or_else(|| { + let (last, _) = crate::runtime::messaging::watch::last_run(&state); + (last.starts_with("failed") || last == crate::runtime::INTERRUPTED).then_some(last) + }); + for (schedule_id, run_id) in running { + let key = run_id.clone(); + let message = self + .inner + .store + .read(move |db| Ok(records::run(db, &key)?)) + .ok() + .flatten() + .and_then(|r| r.message_id); + if message.is_some_and(|m| promoted(&state, &m)) { + self.end_run( + &schedule_id, + &run_id, + outcome_of(status.as_deref()), + status.clone(), + ) + .await; + } + } + } + + /// `schedule_wakeup` during a scheduled run: record its `noop` and reason. `false` + /// when the Session's current run is not a scheduled one. + pub async fn report_schedule_run( + &self, + session_id: &str, + reason: &str, + noop: bool, + ) -> Result { + let state = self.state(session_id).await?; + if !scheduled_run_current(&state) { + return Ok(false); + } + let id = session_id.to_owned(); + let running = self + .inner + .store + .read(move |db| Ok(records::running_in(db, &id)?))?; + for (schedule_id, run_id) in running { + let key = run_id.clone(); + let Some(record) = self + .inner + .store + .read(move |db| Ok(records::run(db, &key)?))? + else { + continue; + }; + if !record + .message_id + .as_deref() + .is_some_and(|m| promoted(&state, m)) + { + continue; + } + let mut reported = Run::new( + &schedule_id, + &run_id, + record.n, + Phase::Reported, + record.due_ms, + ); + reported.noop = noop; + reported.reason = Some(reason.trim().chars().take(200).collect()); + append(self, &schedule_id, vec![event(records::RUN, &reported)])?; + return Ok(true); + } + Ok(false) + } + + /// Whether a scheduled run is in flight in `session_id` (offers `schedule_wakeup`). + /// Reads only the index. + pub fn schedule_run_running(&self, session_id: &str) -> bool { + let id = session_id.to_owned(); + self.inner + .store + .read(move |db| Ok(!records::running_in(db, &id)?.is_empty())) + .unwrap_or(false) + } + + /// Whether the Session's current run is a scheduled one (its asks get + /// [`super::NO_SCHEDULE_APPROVER`]). + pub async fn scheduled_run_active(&self, session_id: &str) -> bool { + self.schedule_run_running(session_id) + && self + .state(session_id) + .await + .is_ok_and(|state| scheduled_run_current(&state)) + } + + /// Run the sweep soon, without waiting for its next period. + pub(crate) fn nudge_schedules(&self) { + if !self + .inner + .schedules_on + .load(std::sync::atomic::Ordering::SeqCst) + { + return; + } + let weak = self.downgrade(); + tokio::spawn(async move { + let Some(runtime) = weak.upgrade() else { + return; + }; + if let Err(error) = runtime.sweep_schedules(now_ms()).await { + warn("schedule sweep failed", &error); + } + }); + } + + /// Restore schedules after a restart: end runs a stopped service cut off and apply the + /// missed-run policy. Must run before [`Self::spawn_schedule_sweep`]; the number of + /// records written. + pub async fn recover_schedules(&self) -> Result { + self.recover_schedules_at(now_ms()).await + } + + /// [`Self::recover_schedules`] at a chosen time. + pub async fn recover_schedules_at(&self, now: i64) -> Result { + let ids = self.inner.store.read(|db| Ok(records::restorable(db)?))?; + let mut changed = 0; + for id in ids { + changed += self.restore_schedule(&id, now).await?; + } + Ok(changed) + } + + async fn restore_schedule(&self, id: &str, now: i64) -> Result { + let key = id.to_owned(); + let Some(schedule) = self + .inner + .store + .read(move |db| Ok(records::load(db, &key)?))? + else { + return Ok(0); + }; + if let Some(run_id) = &schedule.inflight { + return self.restore_inflight(&schedule, run_id).await; + } + let missed = schedule.status == ScheduleStatus::Active + && schedule.missed == Missed::Skip + && schedule.next_due_ms.is_some_and(|due| due < now); + if !missed { + return Ok(0); + } + let mut skip = unstarted( + &schedule, + schedule.runs + 1, + schedule.next_due_ms.unwrap_or(now), + RunOutcome::SkippedMissed, + "the service was not running".into(), + next_run(&schedule.cron, schedule.jitter_ms, now), + ); + skip.reason = Some("the service was not running".into()); + append(self, id, vec![event(records::RUN, &skip)])?; + Ok(1) + } + + /// A run in flight when the service stopped: one whose prompt was promoted in a Session + /// that no longer runs ends `interrupted`; one still queued runs on its next Drain. + async fn restore_inflight( + &self, + schedule: &Schedule, + run_id: &str, + ) -> Result { + let key = run_id.to_owned(); + let Some(record) = self + .inner + .store + .read(move |db| Ok(records::run(db, &key)?))? + else { + return Ok(0); + }; + let (Some(session_id), Some(message)) = (&record.session_id, &record.message_id) else { + return Ok(0); + }; + if self.is_running(session_id) { + return Ok(0); + } + let cut_off = match self.state(session_id).await { + Ok(state) => promoted(&state, message), + // Its Session is gone: nothing will ever end it. + Err(_) => true, + }; + if !cut_off { + return Ok(0); + } + self.end_run( + &schedule.id, + run_id, + RunOutcome::Interrupted, + Some("interrupted by a service restart".into()), + ) + .await; + Ok(1) + } + + /// Run the schedule sweep every [`SWEEP_EVERY`] until shutdown. Only the served App + /// (the `cyber service` process) runs schedules. + pub fn spawn_schedule_sweep(&self) { + self.inner + .schedules_on + .store(true, std::sync::atomic::Ordering::SeqCst); + let weak = self.downgrade(); + let closed = self.inner.closed.clone(); + let task = tokio::spawn(async move { + loop { + tokio::select! { + () = closed.cancelled() => return, + () = tokio::time::sleep(SWEEP_EVERY) => {} + } + let Some(runtime) = weak.upgrade() else { + return; + }; + if let Err(error) = runtime.sweep_schedules(now_ms()).await { + warn("schedule sweep failed", &error); + } + } + }); + let mut owners = self + .inner + .background + .lock() + .unwrap_or_else(PoisonError::into_inner); + owners.retain(|owner| !owner.is_finished()); + owners.push(task); + } +} + +/// The `ended` record of a started run, measured against its Session's current totals. +fn ended_run( + schedule_id: &str, + record: &RunRecord, + outcome: RunOutcome, + reason: Option, + totals: Option<(f64, u64, u64)>, +) -> Run { + let mut ended = Run::new( + schedule_id, + &record.run_id, + record.n, + Phase::Ended, + record.due_ms, + ); + ended.session_id = record.session_id.clone(); + ended.message_id = record.message_id.clone(); + ended.outcome = Some(outcome); + ended.noop = record.noop && outcome == RunOutcome::Completed; + ended.reason = reason.or_else(|| record.reason.clone()); + ended.duration_ms = record + .started_ms + .map_or(0, |started| (now_ms() - started).max(0)); + if let Some((cost, tokens, turns)) = totals { + ended.cost = (cost - record.cost_before).max(0.0); + ended.tokens = tokens.saturating_sub(record.tokens_before); + ended.turns = turns.saturating_sub(record.turns_before); + } + ended +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn run_ids_and_notify_policy() { + assert_eq!(message_id("cron_01ABC", 3), "schedi_01ABC_3"); + assert!(is_run_message("schedi_01ABC_3")); + let mut run = Run::new("cron_01ABC", "srun_1", 1, Phase::Ended, 0); + run.outcome = Some(RunOutcome::Completed); + assert!(run_notifies(Notify::OnChange, &run)); + run.noop = true; + assert!(!run_notifies(Notify::OnChange, &run)); + assert!(run_notifies(Notify::Always, &run)); + run.outcome = Some(RunOutcome::Refused); + assert!(run_notifies(Notify::OnChange, &run)); + assert!(!run_notifies(Notify::Never, &run)); + run.outcome = Some(RunOutcome::SkippedOverlap); + assert!(!run_notifies(Notify::OnChange, &run)); + run.reason = Some("the previous run was still running".into()); + assert_eq!( + run_result(&run), + "run 1 skipped_overlap: the previous run was still running" + ); + } +} diff --git a/crates/cyber-server/src/runtime/usage_wait.rs b/crates/cyber-server/src/runtime/usage_wait.rs index 923cdfad8..8237fe5e6 100644 --- a/crates/cyber-server/src/runtime/usage_wait.rs +++ b/crates/cyber-server/src/runtime/usage_wait.rs @@ -524,10 +524,11 @@ impl Inner { } /// A Session that runs with nobody attached: created by `cyber exec`, a Workflow agent, -/// an active Goal, a loop iteration in flight, or a teammate. +/// an active Goal, a loop iteration in flight, a scheduled run, or a teammate. fn unattended_marker(state: &SessionState) -> bool { let info = &state.info; info.unattended + || super::schedules::scheduled_run_current(state) || info.workflow_run_id.is_some() || state.goals.active().is_some() || state diff --git a/crates/cyber-server/tests/schedules.rs b/crates/cyber-server/tests/schedules.rs new file mode 100644 index 000000000..ef6a21dec --- /dev/null +++ b/crates/cyber-server/tests/schedules.rs @@ -0,0 +1,449 @@ +//! `loops-scheduling` (persistent local schedules), end to end with a scripted model. +//! Time is passed to the sweep explicitly; `run_schedule_now` starts a run at once. + +mod support; + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use cyber_core::budget::Budget; +use cyber_core::loops::{Missed, Notify}; +use cyber_server::runtime::RuntimeError; +use cyber_server::runtime::schedules::{ + DesktopNotifier, RunRecord, Schedule, SchedulePolicy, ScheduleRequest, ScheduleStatus, + jitter_ms, next_run, +}; +use support::*; + +/// Desktop notifications, as `title: body`. +#[derive(Default)] +struct Recorder(Mutex>); + +impl DesktopNotifier for Recorder { + fn notify(&self, title: &str, body: &str) { + self.0.lock().unwrap().push(format!("{title}: {body}")); + } +} + +impl Recorder { + fn sent(&self) -> Vec { + self.0.lock().unwrap().clone() + } +} + +fn harness(replies: Vec>) -> (Harness, Arc) { + let h = Harness::new(Setup { + scripts: vec![("test/main", replies)], + ..Setup::default() + }); + let recorder = Arc::new(Recorder::default()); + h.runtime.set_desktop_notifier(recorder.clone()); + (h, recorder) +} + +fn request(h: &Harness, cron: &str, prompt: &str) -> ScheduleRequest { + ScheduleRequest { + cron: cron.into(), + prompt: prompt.into(), + name: Some("nightly".into()), + directory: Some(h.repo.display().to_string()), + model: Some("test/main".into()), + ..ScheduleRequest::default() + } +} + +fn now_ms() -> i64 { + chrono::Utc::now().timestamp_millis() +} + +/// The schedule once its newest run ended, after its Session settled. +async fn ended_run(h: &Harness, id: &str) -> (Schedule, RunRecord) { + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + loop { + let shown = h.runtime.schedule(id, true).unwrap(); + if let Some(run) = shown.recent.first() { + if let Some(session) = &run.session_id { + h.settle(session).await; + } + if run.outcome != "running" { + let run = run.clone(); + return (h.runtime.schedule(id, true).unwrap(), run); + } + } + assert!(tokio::time::Instant::now() < deadline, "{shown:?}"); + tokio::time::sleep(Duration::from_millis(20)).await; + } +} + +fn notices(h: &Harness, session: &str) -> Vec { + h.store + .read_events(session, -1, 500) + .unwrap() + .events + .into_iter() + .filter(|e| e.kind == "session.notification.sent.1") + .map(|e| format!("{}: {}", e.data["title"], e.data["body"])) + .collect() +} + +#[tokio::test] +async fn a_nightly_schedule_runs_in_a_new_unattended_session() { + let (h, desktop) = harness(vec![text("3 commits reviewed, all fine")]); + let before = now_ms(); + let schedule = h + .runtime + .create_schedule(request(&h, "0 2 * * *", "review last night's commits")) + .await + .unwrap(); + assert!(schedule.id.starts_with("cron_"), "{}", schedule.id); + assert_eq!( + (schedule.mode.as_str(), schedule.status), + ("dont-ask", ScheduleStatus::Active) + ); + let due = schedule.next_due_ms.unwrap(); + assert!(due > before && due <= before + 86_400_000, "{due}"); + assert_eq!(Some(due), next_run("0 2 * * *", 0, due - 60_000)); + + assert_eq!( + h.runtime.sweep_schedules(due - 1).await.unwrap(), + 0, + "not due yet" + ); + assert_eq!(h.runtime.sweep_schedules(due).await.unwrap(), 1); + let (after, run) = ended_run(&h, &schedule.id).await; + assert_eq!(run.outcome, "completed", "{run:?}"); + assert_eq!(after.runs, 1); + assert!(after.next_due_ms.unwrap() > due, "the next night"); + assert!(after.inflight.is_none()); + + let session = run.session_id.clone().unwrap(); + let state = h.state(&session).await; + assert!(state.info.unattended, "no client attends a scheduled run"); + assert_eq!(state.info.mode, "dont-ask"); + assert!( + state.info.title.starts_with("nightly · "), + "{}", + state.info.title + ); + let row = &state.inbox[0]; + assert!(row.message_id.starts_with("schedi_"), "{}", row.message_id); + assert_eq!(row.source, "loop"); + + let kinds: Vec = h + .store + .read_events(&schedule.id, -1, 100) + .unwrap() + .events + .into_iter() + .map(|e| e.kind) + .collect(); + assert_eq!( + kinds, + ["schedule.created.1", "schedule.run.1", "schedule.run.1"] + ); + // A run that reported no `noop` changed something: `on_change` notifies. + assert_eq!(desktop.sent().len(), 1, "{:?}", desktop.sent()); + assert!(desktop.sent()[0].starts_with("Schedule nightly: run 1 completed")); + assert_eq!(notices(&h, &session).len(), 1); +} + +#[tokio::test] +async fn a_due_run_while_one_is_in_flight_is_skipped() { + let (h, _) = harness(vec![tools(&[("c1", "write", "{}")]), text("done")]); + h.tools.set("write", Behavior::Gated); + let schedule = h + .runtime + .create_schedule(request(&h, "*/5 * * * *", "poll")) + .await + .unwrap(); + h.runtime.run_schedule_now(&schedule.id).await.unwrap(); + h.tools.started.notified().await; + let busy = h.runtime.schedule(&schedule.id, false).unwrap(); + assert!(busy.inflight.is_some()); + let error = h.runtime.run_schedule_now(&schedule.id).await.unwrap_err(); + assert!(error.to_string().contains("run in flight"), "{error}"); + + let due = busy.next_due_ms.unwrap(); + h.runtime.sweep_schedules(due).await.unwrap(); + let shown = h.runtime.schedule(&schedule.id, true).unwrap(); + assert_eq!(shown.recent[0].outcome, "skipped_overlap", "{shown:?}"); + assert!(shown.next_due_ms.unwrap() > due); + h.tools.release.notify_one(); + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + loop { + let shown = h.runtime.schedule(&schedule.id, true).unwrap(); + if shown.inflight.is_none() { + assert!( + shown.recent.iter().any(|r| r.outcome == "completed"), + "{shown:?}" + ); + break; + } + assert!(tokio::time::Instant::now() < deadline); + tokio::time::sleep(Duration::from_millis(20)).await; + } +} + +#[tokio::test] +async fn jitter_is_fixed_per_schedule_and_included_in_the_next_run() { + let (h, _) = harness(Vec::new()); + h.tools.schedule_policy.lock().unwrap().jitter_seconds = 60; + let schedule = h + .runtime + .create_schedule(request(&h, "* * * * *", "tick")) + .await + .unwrap(); + assert_eq!(schedule.jitter_ms, jitter_ms(&schedule.id, 60)); + let next = schedule.next_due_ms.unwrap(); + assert_eq!((next - schedule.jitter_ms).rem_euclid(60_000), 0); + let listed = h.runtime.schedules().unwrap(); + assert_eq!(listed[0].next_due_ms, Some(next)); +} + +#[tokio::test] +async fn the_gate_refuses_untrusted_directories_and_unallowed_bypass() { + let (h, desktop) = harness(Vec::new()); + let policy = |p: SchedulePolicy| *h.tools.schedule_policy.lock().unwrap() = p; + policy(SchedulePolicy::default()); + let error = h + .runtime + .create_schedule(request(&h, "0 2 * * *", "x")) + .await + .unwrap_err(); + assert!(error.to_string().contains("is not trusted"), "{error}"); + + policy(SchedulePolicy { + trusted: true, + ..SchedulePolicy::default() + }); + let bypass = ScheduleRequest { + mode: Some("bypass".into()), + ..request(&h, "0 2 * * *", "x") + }; + let error = h.runtime.create_schedule(bypass.clone()).await.unwrap_err(); + assert!(error.to_string().contains("loops.allow_bypass"), "{error}"); + let missing = ScheduleRequest { + directory: Some(h.repo.join("gone").display().to_string()), + ..request(&h, "0 2 * * *", "x") + }; + let error = h.runtime.create_schedule(missing).await.unwrap_err(); + assert!( + error.to_string().contains("not an existing directory"), + "{error}" + ); + assert!(h.runtime.schedules().unwrap().is_empty()); + + policy(SchedulePolicy { + trusted: true, + allow_bypass: true, + ..SchedulePolicy::default() + }); + let allowed = h.runtime.create_schedule(bypass).await.unwrap(); + assert_eq!(allowed.mode, "bypass"); + + // The checkout changed after approval: the next run is refused, notified, and no + // Session runs the prompt. + policy(SchedulePolicy::default()); + h.runtime.run_schedule_now(&allowed.id).await.unwrap(); + let shown = h.runtime.schedule(&allowed.id, true).unwrap(); + let run = &shown.recent[0]; + assert_eq!(run.outcome, "refused"); + assert!( + run.reason.as_deref().unwrap().contains("is not trusted"), + "{run:?}" + ); + assert!(run.session_id.is_none()); + assert_eq!( + shown.status, + ScheduleStatus::Active, + "a refusal does not pause it" + ); + assert!( + desktop.sent()[0].contains("refused"), + "{:?}", + desktop.sent() + ); +} + +#[tokio::test] +async fn a_spent_budget_stops_the_schedule_and_notifies() { + let (h, desktop) = harness(vec![text("1")]); + let schedule = h + .runtime + .create_schedule(ScheduleRequest { + budget: Some(Budget { + max_turns: Some(1), + ..Budget::default() + }), + notify: Notify::Never, + ..request(&h, "0 2 * * *", "spend") + }) + .await + .unwrap(); + h.runtime.run_schedule_now(&schedule.id).await.unwrap(); + ended_run(&h, &schedule.id).await; + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + let stopped = loop { + let shown = h.runtime.schedule(&schedule.id, false).unwrap(); + if shown.status != ScheduleStatus::Active { + break shown; + } + assert!(tokio::time::Instant::now() < deadline); + tokio::time::sleep(Duration::from_millis(20)).await; + }; + assert_eq!(stopped.status, ScheduleStatus::BudgetExceeded); + assert_eq!(stopped.reason.as_deref(), Some("max_turns 1/1")); + assert_eq!(stopped.next_due_ms, None); + assert!( + desktop.sent().is_empty(), + "notify never: {:?}", + desktop.sent() + ); + let error = h.runtime.resume_schedule(&schedule.id).unwrap_err(); + assert!( + error.to_string().contains("remove it and add a new one"), + "{error}" + ); + assert_eq!(h.runtime.sweep_schedules(i64::MAX / 2).await.unwrap(), 0); +} + +#[tokio::test] +async fn pause_resume_and_remove() { + let (h, _) = harness(Vec::new()); + let schedule = h + .runtime + .create_schedule(request(&h, "0 2 * * *", "x")) + .await + .unwrap(); + let paused = h.runtime.pause_schedule(&schedule.id).unwrap(); + assert_eq!( + (paused.status, paused.next_due_ms), + (ScheduleStatus::Paused, None) + ); + assert_eq!(h.runtime.sweep_schedules(i64::MAX / 2).await.unwrap(), 0); + let resumed = h.runtime.resume_schedule(&schedule.id).unwrap(); + assert_eq!(resumed.status, ScheduleStatus::Active); + assert!(resumed.next_due_ms.unwrap() > now_ms()); + h.runtime.remove_schedule(&schedule.id).unwrap(); + assert!(h.runtime.schedules().unwrap().is_empty()); + assert!(matches!( + h.runtime.schedule(&schedule.id, false), + Err(RuntimeError::ScheduleNotFound(_)) + )); + assert!(matches!( + h.runtime.pause_schedule(&schedule.id), + Err(RuntimeError::ScheduleNotFound(_)) + )); + let error = h + .runtime + .create_schedule(request(&h, "0 2 31 2 *", "x")) + .await + .unwrap_err(); + assert!( + error.to_string().contains("Invalid cron expression"), + "{error}" + ); +} + +#[tokio::test] +async fn a_run_resumes_its_own_session_in_the_schedules_mode() { + let (h, _) = harness(vec![text("first"), text("again")]); + let session = h.session().await; + assert_eq!(h.state(&session).await.info.mode, "default"); + let schedule = h + .runtime + .create_schedule(ScheduleRequest { + session_id: Some(session.clone()), + ..request(&h, "0 2 * * *", "check the queue") + }) + .await + .unwrap(); + h.runtime.run_schedule_now(&schedule.id).await.unwrap(); + let (_, run) = ended_run(&h, &schedule.id).await; + assert_eq!(run.session_id.as_deref(), Some(session.as_str())); + assert_eq!(run.outcome, "completed"); + let state = h.state(&session).await; + assert_eq!(state.info.mode, "dont-ask"); + let child = h + .runtime + .create_session(cyber_server::runtime::CreateSession { + directory: h.repo.display().to_string(), + model: "test/main".into(), + parent_id: Some(session), + ..Default::default() + }) + .await + .unwrap() + .id; + let error = h + .runtime + .create_schedule(ScheduleRequest { + session_id: Some(child), + ..request(&h, "0 2 * * *", "x") + }) + .await + .unwrap_err(); + assert!(error.to_string().contains("not a root Session"), "{error}"); +} + +#[tokio::test] +async fn a_run_cut_off_by_a_restart_ends_interrupted() { + let (h, _) = harness(vec![tools(&[("c1", "write", "{}")]), text("never")]); + h.tools.set("write", Behavior::Gated); + let schedule = h + .runtime + .create_schedule(request(&h, "0 2 * * *", "work")) + .await + .unwrap(); + h.runtime.run_schedule_now(&schedule.id).await.unwrap(); + h.tools.started.notified().await; + + let restarted = h.restart(); + restarted.recover_schedules_at(now_ms()).await.unwrap(); + let shown = restarted.schedule(&schedule.id, true).unwrap(); + assert!(shown.inflight.is_none(), "{shown:?}"); + assert_eq!(shown.recent[0].outcome, "interrupted"); + h.tools.release.notify_one(); +} + +#[tokio::test] +async fn missed_runs_follow_the_policy_after_a_restart() { + for missed in [Missed::Skip, Missed::RunOnce] { + let (h, _) = harness(vec![text("caught up")]); + let schedule = h + .runtime + .create_schedule(ScheduleRequest { + missed, + ..request(&h, "0 2 * * *", "nightly") + }) + .await + .unwrap(); + // The service was down for two days. + let now = schedule.next_due_ms.unwrap() + 2 * 86_400_000; + let restarted = h.restart(); + restarted.recover_schedules_at(now).await.unwrap(); + let shown = restarted.schedule(&schedule.id, true).unwrap(); + match missed { + Missed::Skip => { + assert_eq!(shown.recent[0].outcome, "skipped_missed"); + assert!(shown.next_due_ms.unwrap() > now); + assert_eq!( + restarted.sweep_schedules(now).await.unwrap(), + 0, + "no catch-up" + ); + } + Missed::RunOnce => { + assert!(shown.recent.is_empty()); + assert_eq!( + restarted.sweep_schedules(now).await.unwrap(), + 1, + "one catch-up" + ); + let started = restarted.schedule(&schedule.id, false).unwrap(); + assert_eq!(started.runs, 1); + assert!(started.next_due_ms.unwrap() > now); + } + } + } +} diff --git a/crates/cyber-server/tests/support/mod.rs b/crates/cyber-server/tests/support/mod.rs index 13313a19b..72b336639 100644 --- a/crates/cyber-server/tests/support/mod.rs +++ b/crates/cyber-server/tests/support/mod.rs @@ -232,6 +232,9 @@ pub struct Tools { pub pinned: Mutex>, /// How many times the pinned source was observed. pub pinned_observed: std::sync::atomic::AtomicUsize, + /// What every directory's schedule gate reads (`loops-scheduling`): trusted, no + /// `bypass`, no jitter, unless a test changes it. + pub schedule_policy: Mutex, } pub fn def(name: &str, safety: RetrySafety, parallel: bool) -> ToolDef { @@ -289,6 +292,10 @@ impl Tools { rule_approvals: Mutex::default(), pinned: Mutex::default(), pinned_observed: Default::default(), + schedule_policy: Mutex::new(cyber_server::runtime::schedules::SchedulePolicy { + trusted: true, + ..Default::default() + }), }) } @@ -375,6 +382,12 @@ impl ToolHost for Tools { Ok(self.usage_limit.lock().unwrap().clone()) } + fn schedule_policy( + &self, + _directory: &str, + ) -> Result { + Ok(self.schedule_policy.lock().unwrap().clone()) + } fn goal_settings( &self, _directory: &str, diff --git a/crates/cyber-server/tests/usage_limit.rs b/crates/cyber-server/tests/usage_limit.rs index 00a6022c2..9209d4ca0 100644 --- a/crates/cyber-server/tests/usage_limit.rs +++ b/crates/cyber-server/tests/usage_limit.rs @@ -760,3 +760,43 @@ async fn a_loop_iteration_waits_the_whole_advised_delay() { ); assert_eq!(*clock.sleeps.lock().unwrap(), [Duration::from_secs(600)]); } + +/// `loops-scheduling` → Usage limit waits in loop iterations: a scheduled run that resumes +/// an attended Session makes it unattended while it runs, so it waits for the reset. +#[tokio::test] +async fn a_scheduled_run_waits_for_the_reset_and_completes() { + let clock = TestClock::skipping(); + let h = harness(vec![limit(10), text("nightly review done")], &clock); + let id = h.session().await; + let schedule = h + .runtime + .create_schedule(cyber_server::runtime::schedules::ScheduleRequest { + cron: "0 2 * * *".into(), + prompt: "review last night's commits".into(), + directory: Some(h.repo.display().to_string()), + model: Some("test/main".into()), + session_id: Some(id.clone()), + ..Default::default() + }) + .await + .unwrap(); + h.runtime.run_schedule_now(&schedule.id).await.unwrap(); + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + let run = loop { + h.settle(&id).await; + let shown = h.runtime.schedule(&schedule.id, true).unwrap(); + if shown.recent.first().is_some_and(|r| r.outcome != "running") { + break shown.recent[0].clone(); + } + assert!(tokio::time::Instant::now() < deadline, "{shown:?}"); + tokio::time::sleep(Duration::from_millis(20)).await; + }; + assert_eq!(run.outcome, "completed", "{run:?}"); + assert_eq!( + kinds(&waits(&h, &id)), + [ + "session.usage_limit.waiting.1", + "session.usage_limit.resumed.1" + ] + ); +} diff --git a/crates/cyber-store/migrations/20261120000000_schedules.sql b/crates/cyber-store/migrations/20261120000000_schedules.sql new file mode 100644 index 000000000..22f2a492a --- /dev/null +++ b/crates/cyber-store/migrations/20261120000000_schedules.sql @@ -0,0 +1,43 @@ +-- Persistent local schedules (`loops-scheduling` → Persistent local schedules): the +-- projection of the `schedule.*` events of each schedule's own stream, read by the +-- service's sweep and the `cyber loops` routes. Rebuildable from events. +CREATE TABLE schedule ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + cron TEXT NOT NULL, + directory TEXT NOT NULL, + spec TEXT NOT NULL, + status TEXT NOT NULL, + reason TEXT, + next_due_ms INTEGER, + inflight TEXT, + runs INTEGER NOT NULL DEFAULT 0, + cost_usd REAL NOT NULL DEFAULT 0, + tokens INTEGER NOT NULL DEFAULT 0, + turns INTEGER NOT NULL DEFAULT 0, + created_ms INTEGER NOT NULL, + updated_ms INTEGER NOT NULL +) STRICT; +CREATE INDEX schedule_due ON schedule (status, next_due_ms); + +CREATE TABLE schedule_run ( + id TEXT PRIMARY KEY, + schedule_id TEXT NOT NULL REFERENCES schedule (id) ON DELETE CASCADE, + n INTEGER NOT NULL, + due_ms INTEGER NOT NULL, + started_ms INTEGER, + ended_ms INTEGER, + session_id TEXT, + message_id TEXT, + outcome TEXT NOT NULL, + noop INTEGER NOT NULL DEFAULT 0, + reason TEXT, + cost_usd REAL NOT NULL DEFAULT 0, + tokens INTEGER NOT NULL DEFAULT 0, + turns INTEGER NOT NULL DEFAULT 0, + cost_before REAL NOT NULL DEFAULT 0, + tokens_before INTEGER NOT NULL DEFAULT 0, + turns_before INTEGER NOT NULL DEFAULT 0 +) STRICT; +CREATE INDEX schedule_run_schedule ON schedule_run (schedule_id, n); +CREATE INDEX schedule_run_session ON schedule_run (session_id, outcome); diff --git a/crates/cyber-store/src/migrate.rs b/crates/cyber-store/src/migrate.rs index e0eb6daa6..c0dfa55b0 100644 --- a/crates/cyber-store/src/migrate.rs +++ b/crates/cyber-store/src/migrate.rs @@ -221,6 +221,10 @@ pub(crate) const MIGRATIONS: &[Migration] = &[ id: "20261118020000_auto_reviewer_tools", sql: include_str!("../migrations/20261118020000_auto_reviewer_tools.sql"), }, + Migration { + id: "20261120000000_schedules", + sql: include_str!("../migrations/20261120000000_schedules.sql"), + }, ]; pub(crate) enum Outcome { diff --git a/crates/cyber-tools/src/host.rs b/crates/cyber-tools/src/host.rs index 13900c230..3a087d449 100644 --- a/crates/cyber-tools/src/host.rs +++ b/crates/cyber-tools/src/host.rs @@ -1291,6 +1291,26 @@ impl ToolHost for BuiltinHost { )) } + fn schedule_policy( + &self, + directory: &str, + ) -> Result { + // Fail closed: without the checkout resolver there is no trust to check. + let config = self + .hook_config + .get() + .ok_or("Refused: checkout trust is unavailable on this host")?; + let resolved = (config.resolve)(Path::new(directory)) + .map_err(|error| format!("Refused: the configuration of {directory}: {error}"))?; + let settings = cyber_core::loops::LoopSettings::from_config(&resolved.value); + Ok(cyber_server::runtime::schedules::SchedulePolicy { + trusted: resolved.trust.trusted, + allow_bypass: cyber_core::loops::allow_bypass(&resolved.value, &resolved.sources), + jitter_seconds: settings.jitter_seconds, + budget: cyber_core::budget::Budget::from_config(&resolved.value, "loop")?, + }) + } + fn check( &self, directory: &str, @@ -1692,11 +1712,13 @@ impl ToolHost for BuiltinHost { .get_or_init(|| tools::messaging::enabled(self, Path::new(&turn.directory))) }) .filter(|d| { - // `loops-scheduling`: only while an iteration of an active loop runs. + // `loops-scheduling`: only while an iteration of an active loop, or a + // scheduled run, runs. d.spec.name != tools::loops::NAME - || self - .runtime() - .is_some_and(|runtime| runtime.loop_iteration_running(&turn.session_id)) + || self.runtime().is_some_and(|runtime| { + runtime.loop_iteration_running(&turn.session_id) + || runtime.schedule_run_running(&turn.session_id) + }) }) .filter(|d| { // `loops-scheduling`: scheduled tasks belong to root, non-workflow Sessions. @@ -2562,7 +2584,8 @@ impl Ctx<'_> { permissions::DecisionSource::Taint => "taint", permissions::DecisionSource::Rules => "rule", }; - return Err(self.denied(&req, source, deny_message(&reason)).await); + let message = self.schedule_denial(&reason).await; + return Err(self.denied(&req, source, message).await); } // A tainted run's risky action: no allow approves it alone, a hook's included. let held = self.policy.taint_holds(&req); @@ -2673,6 +2696,22 @@ impl Ctx<'_> { /// The denial error, after PermissionDenied hooks on an armed attempt; a merged /// `retry` is kept for the caller, never applied here. + /// The model-visible text of a policy denial: an ask `dont-ask` turned into a denial + /// during a scheduled run says no approver exists there (`loops-scheduling` → + /// Unattended Mode for schedules). + async fn schedule_denial(&self, reason: &str) -> String { + let unapproved = + self.policy.mode == Mode::DontAsk && reason == permissions::DONT_ASK_DENIAL; + match self.host.runtime() { + Some(runtime) + if unapproved && runtime.scheduled_run_active(&self.inv.session_id).await => + { + cyber_server::runtime::schedules::NO_SCHEDULE_APPROVER.to_owned() + } + _ => deny_message(reason), + } + } + async fn denied(&self, req: &Request, source: &str, message: String) -> ToolError { if !self .denial @@ -2799,6 +2838,9 @@ impl Ctx<'_> { { cyber_server::runtime::NO_WORKFLOW_APPROVER.to_owned() } + Some(runtime) if runtime.scheduled_run_active(&self.inv.session_id).await => { + cyber_server::runtime::schedules::NO_SCHEDULE_APPROVER.to_owned() + } _ => unattended(self.policy.mode), }; Err(self.denied(&req, "unattended", message).await) diff --git a/crates/cyber-tools/src/lifecycle_hooks.rs b/crates/cyber-tools/src/lifecycle_hooks.rs index 41d4622dd..bed7f8c2a 100644 --- a/crates/cyber-tools/src/lifecycle_hooks.rs +++ b/crates/cyber-tools/src/lifecycle_hooks.rs @@ -49,6 +49,7 @@ const DISTINCT_UNAVAILABLE: &[&str] = &[ "GoalEvaluated", "GoalCompleted", "LoopIteration", + "ScheduleRun", ]; /// Lifecycle events the runtime dispatches through its narrow host port. @@ -56,6 +57,7 @@ const RUNTIME_EVENTS: &[&str] = &[ "GoalEvaluated", "GoalCompleted", "LoopIteration", + "ScheduleRun", "Stop", "StopFailure", "UserPromptSubmit", diff --git a/crates/cyber-tools/src/permissions/engine.rs b/crates/cyber-tools/src/permissions/engine.rs index 7accde226..53f757236 100644 --- a/crates/cyber-tools/src/permissions/engine.rs +++ b/crates/cyber-tools/src/permissions/engine.rs @@ -471,6 +471,8 @@ pub struct Policy { } const PLAN_DENY: &str = "Plan mode is read-only. Present the plan with plan_exit."; +/// What `dont-ask` turns an ask into (`permissions-modes` → dont-ask mode). +pub const DONT_ASK_DENIAL: &str = "Not pre-approved (dont-ask mode)"; impl Policy { pub(crate) fn skill_tool_denial(&self, tool: &str) -> Option { @@ -628,7 +630,7 @@ impl Policy { .mode_ceiling(req, mode) .unwrap_or_else(|| self.apply_mode(req, effect, mode)); if mode == Mode::DontAsk && decision == Decision::Ask { - Decision::Deny("Not pre-approved (dont-ask mode)".into()) + Decision::Deny(DONT_ASK_DENIAL.into()) } else { decision } @@ -678,9 +680,7 @@ impl Policy { (Mode::AcceptEdits, Effect::Ask) if req.file_edit && self.inside_location(req) => { Decision::Allow } - (Mode::DontAsk, Effect::Ask) => { - Decision::Deny("Not pre-approved (dont-ask mode)".into()) - } + (Mode::DontAsk, Effect::Ask) => Decision::Deny(DONT_ASK_DENIAL.into()), (_, Effect::Ask) => Decision::Ask, } } diff --git a/crates/cyber-tools/src/permissions/mod.rs b/crates/cyber-tools/src/permissions/mod.rs index 540a3cb20..67c696a41 100644 --- a/crates/cyber-tools/src/permissions/mod.rs +++ b/crates/cyber-tools/src/permissions/mod.rs @@ -19,8 +19,8 @@ pub(crate) use taint::{ }; pub use engine::{ - COLLAB_MESSAGE_SEND, COLLAB_TASK_WRITE, Decision, DecisionSource, Effect, GOAL_SET, - MESSAGE_SEND, Mode, Policy, Request, Rule, TEAM_MANAGE, TEAM_TASK, WORKFLOW_RUN, + COLLAB_MESSAGE_SEND, COLLAB_TASK_WRITE, DONT_ASK_DENIAL, Decision, DecisionSource, Effect, + GOAL_SET, MESSAGE_SEND, Mode, Policy, Request, Rule, TEAM_MANAGE, TEAM_TASK, WORKFLOW_RUN, boundary_evaluate, defaults, evaluate, evaluate_all, evaluate_scoped, is_protected, parse_rules, slash, workflow_resource, }; diff --git a/crates/cyber-tools/src/tools/loops.rs b/crates/cyber-tools/src/tools/loops.rs index 56a9fbee8..468b032f6 100644 --- a/crates/cyber-tools/src/tools/loops.rs +++ b/crates/cyber-tools/src/tools/loops.rs @@ -20,12 +20,12 @@ pub(crate) const CRON_TOOLS: [&str; 3] = ["cron_create", "cron_list", "cron_dele /// Guidance shown to the model while an iteration runs (Context Source `core/loop`). pub(crate) const GUIDANCE_KEY: &str = "core/loop"; -pub(crate) const GUIDANCE: &str = "This prompt is an iteration of a /loop the user started. \ -Before you finish, call schedule_wakeup once: set noop to true when nothing changed since \ -the last check, and give a one-sentence reason. In a self-paced loop, delay_seconds \ -(60–3600) is the wait before the next iteration, and finishing without calling \ -schedule_wakeup ends the loop. In an interval loop the interval keeps the pace and \ -delay_seconds is ignored."; +pub(crate) const GUIDANCE: &str = "This prompt is an iteration of a /loop or a scheduled \ +run the user set up. Before you finish, call schedule_wakeup once: set noop to true when \ +nothing changed since the last check, and give a one-sentence reason. In a self-paced loop, \ +delay_seconds (60–3600) is the wait before the next iteration, and finishing without calling \ +schedule_wakeup ends the loop. In an interval loop, a scheduled task or a scheduled run the \ +schedule keeps the pace and delay_seconds is ignored."; pub(crate) struct ScheduleWakeup; @@ -56,6 +56,14 @@ impl Tool for ScheduleWakeup { .host .runtime() .ok_or_else(|| failed("schedule_wakeup requires the runtime"))?; + // A scheduled run reports its `noop` and reason; its cron sets the pace. + if runtime + .report_schedule_run(&ctx.inv.session_id, text(input, "reason"), noop) + .await + .map_err(|error| failed(error.to_string()))? + { + return Ok("Recorded for this scheduled run".into()); + } let ack = runtime .loop_wakeup(&ctx.inv.session_id, delay, text(input, "reason"), noop) .await diff --git a/docs/cli.md b/docs/cli.md index b8641d367..36204cf51 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -55,6 +55,7 @@ cyber [OPTIONS] [COMMAND] - [`computer`](#cyber-computer): Inspect, set up, arm and stop experimental native computer control - [`features`](#cyber-features): List the feature registry; enable or disable a feature in config - [`workflows`](#cyber-workflows): List saved Workflows; run, inspect and control Workflow Runs +- [`loops`](#cyber-loops): Persistent schedules the Cyber service runs even when no client is open - [`worktree`](#cyber-worktree): List, remove and prune managed Git worktrees of the current repository - [`debug`](#cyber-debug): Inspect resolved paths, configuration and build information - [`models`](#cyber-models): List models from the catalog, available first @@ -1366,6 +1367,121 @@ cyber workflows logs [OPTIONS] - `` +## `cyber loops` + +Persistent schedules the Cyber service runs even when no client is open + +```text +cyber loops [OPTIONS] +``` + +**Subcommands:** + +- [`add`](#cyber-loops-add): Add a schedule the Cyber service runs even when no client is open +- [`list`](#cyber-loops-list): Schedules with their next run (jitter included) +- [`show`](#cyber-loops-show): A schedule and its recent runs +- [`pause`](#cyber-loops-pause): Stop running a schedule until it is resumed; a run in flight finishes +- [`resume`](#cyber-loops-resume): Resume a paused schedule at its next occurrence +- [`run`](#cyber-loops-run): Run a schedule now, outside its cron schedule +- [`rm`](#cyber-loops-rm): Remove a schedule; its run history stays in the database + +## `cyber loops add` + +Add a schedule the Cyber service runs even when no client is open + +```text +cyber loops add [OPTIONS] --cron +``` + +**Arguments:** + +- ``: The prompt (or `/command`) each run sends. + +**Options:** + +- `--cron `: A 5-field cron expression in local time: minute hour day-of-month month day-of-week. +- `--name `: A name shown in listings and notifications (default: the ID) +- `--dir `: The directory runs work in (default: the current Location). Its checkout must be trusted. +- `--agent `: The agent of run Sessions. +- `--mode `: The Mode runs use (default dont-ask). `bypass` needs `loops.allow_bypass` in user or managed config. +- `--model `: The model of new run Sessions (default: the Location's default model) +- `--new-session`: Create a new Session for every run (the default) +- `--session `: Resume this root Session for every run instead. +- `--notify `: When to notify: always, on_change (default) or never. Values: `always`, `on_change`, `never`. +- `--missed `: Runs missed while the service was not running: skip (default) or run-once. Values: `skip`, `run-once`. +- `--max-cost `: Stop the schedule once its runs cost this many USD in total. +- `--max-tokens `: Stop once its runs used this many tokens in total. +- `--max-turns `: Stop once its runs made this many model calls in total. +- `--timeout `: Stop this long after the schedule was added (e.g. 30d) + +## `cyber loops list` + +Schedules with their next run (jitter included) + +```text +cyber loops list [OPTIONS] +``` + +## `cyber loops show` + +A schedule and its recent runs + +```text +cyber loops show [OPTIONS] +``` + +**Arguments:** + +- ``: The schedule's `cron_` ID. + +## `cyber loops pause` + +Stop running a schedule until it is resumed; a run in flight finishes + +```text +cyber loops pause [OPTIONS] +``` + +**Arguments:** + +- ``: The schedule's `cron_` ID. + +## `cyber loops resume` + +Resume a paused schedule at its next occurrence + +```text +cyber loops resume [OPTIONS] +``` + +**Arguments:** + +- ``: The schedule's `cron_` ID. + +## `cyber loops run` + +Run a schedule now, outside its cron schedule + +```text +cyber loops run [OPTIONS] +``` + +**Arguments:** + +- ``: The schedule's `cron_` ID. + +## `cyber loops rm` + +Remove a schedule; its run history stays in the database + +```text +cyber loops rm [OPTIONS] +``` + +**Arguments:** + +- ``: The schedule's `cron_` ID. + ## `cyber worktree` List, remove and prune managed Git worktrees of the current repository diff --git a/docs/features.md b/docs/features.md index 8f02d045f..abce8bb33 100644 --- a/docs/features.md +++ b/docs/features.md @@ -52,7 +52,7 @@ Implemented behavior and remaining scope, reviewed on **2026-10-16** (Cross-sess | Operations | Database-plus-artifact backup, verify/restore, retention, logs and diagnostics; OpenTelemetry export of traces, counters and logs over OTLP (`http/protobuf`, `http/json`, `grpc`) from the server, off until `telemetry.otel.enabled` is set in global configuration (an `OTEL_*` endpoint alone never enables it), with no content unless `telemetry.log_prompts` (then redacted), masked headers, non-blocking delivery and `cyber telemetry show` ([guide](local-core-guide.md#opentelemetry-export)) | Available; Windows CI and the 8 CI build targets with the gRPC transport are not yet verified, broader observability remains | | Feature flags | The feature registry (`teams`, `collaboration` and `computer_use`, experimental and off by default; computer use accepts trusted global enablement only): `cyber features list [--json]`, `cyber features enable\|disable [--scope user\|project]`, `--features a,-b` (for the process it is given to: commands served by the background server, such as `cyber teams list` and the TUI, follow the server's configuration), `CYBER_FEATURES`, `features.` (the deprecated `experimental.` still works and warns), org `policy.features.lock` (a malformed policy locks every feature to its default) and `GET /api/v1/features`; an unknown name in any source fails with `ConfigInvalidError: unknown feature ""` | Available | | Goals | `/goal` conditions and queue, evaluator/checks, budgets, pause/resume/skip/edit/reorder, templates, worktree forks, goals on subagents and workflow agents, the model `goal` tool, unattended-ask pausing, restart recovery, HTTP/hooks, TUI panel/footer/sidebar and `cyber exec --goal` with CI exits ([guide](local-core-guide.md#goals-p2-m23)) | Implemented (P2 M2.3, slices 1–2); live end-to-end acceptance on the real binary and archiving remain | -| Loops | Fixed-interval and self-paced `/loop`, `schedule_wakeup`, queued delivery, overlap skip/coalesce, quiet-check collapsing, command/time/iteration/budget stops, restart recovery, HTTP routes and TUI indicators ([guide](local-core-guide.md#loops-p2-m24)) | Session loops implemented (P2 M2.4); in-session cron, persistent service schedules, notifications, loop hooks, `--until-goal` and exec slash invocation remain | +| Loops | Fixed-interval and self-paced `/loop`, `schedule_wakeup`, queued delivery, overlap skip/coalesce, quiet-check collapsing, command/time/iteration/budget/`--until-goal` stops, restart recovery with the missed-run policy, the model's `cron_create`/`cron_list`/`cron_delete` tasks, `--notify` notifications, the `LoopIteration` hook, HTTP routes and TUI indicators; persistent `cyber loops` schedules run by the service with no client open (`dont-ask` by default, `bypass` only with `loops.allow_bypass` in user or managed config, trusted directories only, jitter, desktop notifications, budgets across runs, `schedule.run.1`, `ScheduleRun`) ([guide](local-core-guide.md#loops-p2-m24)) | Implemented (P2 M2.4); live runs against a real model, a launchd/systemd unit for the service, `/loop` in `cyber exec` and `cyber loops promote` (P3) remain | | Web dashboard | `cyber web`, Session/Location navigation, transcripts/diffs, prompts, permission/question inbox, Workflow/Job/Goal controls and solve evidence; owner password in page memory, explicit expiring presence, TLS off loopback and user-managed SSH forwarding | First P1 browser slice implemented; [setup and acceptance evidence](web-dashboard.md); attachments, full Settings, terminal emulation, Relay and paired Devices remain outside this slice | | VS Code extension | `clients/vscode/`: a chat panel bound to a Session of the workspace folder (history, durable event resume, prompt, interrupt, Mode and model), the active file and selection sent as a ranged `file` part read through the `read` checks, Alt+K `@path#L12-30` mentions, pending edits reviewed in the native diff editor with Accept / Accept always / Reject / Reject with feedback, permission and question cards plus a notification when hidden, presence leases, terminal handoff to `cyber --resume`, Restricted Mode gating; authenticates only with a local IDE token (`cyber ide token create\|list\|revoke`: SHA-256 at rest, 30-day default expiry, rotation, loopback or Unix socket only, an allowlist of routes, `403 ide_token_scope` elsewhere, revocation closing streams within 1 s); strict nonce CSP webview with no credentials or network; `.vsix` and `.sha256` on each release ([guide](vscode-extension.md)) | First slice (P1, `add-vscode-extension`); unsigned `.vsix` only, no Marketplace or Open VSX, no per-hunk review, ACP or other IDEs; macOS and Linux | | Verified integrations | Durable dependency manifests, isolated complementary commits, combined host checks/source fingerprints, independent Plan review, owner CLI/API/SDK/dashboard queue and explicit branch/PR publication ([guide](verified-integrations.md)) | Implemented; macOS real CLI/SDK/browser and crash acceptance, signed local Auth fixtures and mocked remote-publication transport. Live CyberdyneAuth, actual GitHub publication and Linux/Windows feature acceptance remain unverified | diff --git a/docs/local-core-guide.md b/docs/local-core-guide.md index 3dd347774..5d32cb0cb 100644 --- a/docs/local-core-guide.md +++ b/docs/local-core-guide.md @@ -2229,7 +2229,33 @@ In the `/goal` panel, `e` edits, `p` pauses, `r` resumes and `c` clears the sele - a one-shot scheduled task whose time passed ends `expired` under `skip`, and runs once under `run-once`. - **Hooks.** `LoopIteration` hooks receive `{loop, iteration: {n, outcome, noop, duration_ms, cost, tokens, turns, reason}}` on stdin after each iteration ends (skipped ticks excluded). They are observational. - **API:** `GET|POST /api/v1/sessions/{id}/loops` (`POST` takes `{"command": "5m check"}` or the parsed fields), `DELETE /api/v1/sessions/{id}/loops[/{loop_id}]`. -- **Not yet:** persistent `cyber loops add` schedules run by the service, and `/loop` in `cyber exec`. +- **Not yet:** `/loop` in `cyber exec`, and `cyber loops promote` (P3). + +### Persistent schedules (`cyber loops`) + +`cyber loops` schedules a prompt that the Cyber service runs on a cron schedule, even when no terminal or client is open: + +```text +cyber loops add --cron "0 2 * * *" --name nightly "review last night's commits" +cyber loops add --cron "*/30 9-18 * * 1-5" --dir ~/src/api --session ses_… --notify always "check CI" +cyber loops add --cron @weekly --max-cost 5 --timeout 90d "summarize open issues" +cyber loops list # ID, name, cron, next run (jitter included), status, runs, Mode +cyber loops show cron_… # settings and the 20 most recent runs +cyber loops pause|resume|run|rm cron_… +``` + +- **The service runs them.** Schedules live in the database (`schedule.*` events, `schedule` and `schedule_run` tables) and the `cyber serve` process that `cyber service start` registers runs them, checking every 5 s. `add` starts the service like every resource command, and warns when it was not running: schedules run only while it runs, so start it again with `cyber service start` after a reboot or logout. +- **Each run** creates a new Session (unattended, titled ` ·