diff --git a/docs/ai/design/2026-11-25-feature-scheduled-sends.md b/docs/ai/design/2026-11-25-feature-scheduled-sends.md new file mode 100644 index 00000000..1392a413 --- /dev/null +++ b/docs/ai/design/2026-11-25-feature-scheduled-sends.md @@ -0,0 +1,91 @@ +--- +phase: design +title: System Design & Architecture +description: Implementation architecture for scheduled agent sends (#482) +--- + +# System Design & Architecture + +## Architecture Overview + +```mermaid +flowchart LR + CLI["CLI: agent send --in/--at & agent schedule list/cancel"] -->|JSON-RPC over Unix socket| RPC["devkitd rpc/schedule.rs"] + RPC --> Store["devkit-core Store (daemon.db: scheduled_sends)"] + Loop["devkitd Dedicated 2s Scheduler Task (server.rs)"] -->|tick_schedules(now_ms)| Store + Loop -->|fire-time lookup| Lookup["Registry + enriched cache"] + Lookup --> Deliver["ScheduleDeliverer"] + Deliver -->|runtime=herdr| Herdr["HerdrRuntime::send_prompt"] + Deliver -->|TTY matches tmux| Tmux["TmuxRuntime::pane_for_pid + send_to_pane"] + Deliver -->|unmanaged terminal| Fallback["Subprocess: ai-devkit agent send --id --stdin"] +``` + +### Key Components +1. **Storage (`rust/crates/devkit-core/src/store/schedules.rs`):** Owns `scheduled_sends` DDL, partial index, canonical RFC3339/ISO-8601 UTC parsing/normalization (no `chrono`), short `sch_<8-hex>` ID generation, CRUD, state transitions, and amortized terminal-row pruning (keep newest 1,000 terminal rows / 30 days). +2. **Wire Protocol (`rust/crates/devkit-core/src/proto.rs` + `packages/daemon-client`):** `ScheduledSend`, `ScheduleCreateParams`, `ScheduleListParams`, `ScheduleCancelParams` exported via `ts-rs`, plus `DaemonClient::{createSchedule, listSchedules, cancelSchedule}`. +3. **RPC Handlers (`rust/crates/devkitd/src/rpc/schedule.rs`):** Routes `schedule.create`, `schedule.list`, `schedule.cancel` from `server.rs`, enforcing the in-memory `in_flight` cancel guard so `cancel` cannot race an active delivery. +4. **Delivery Engine (`rust/crates/devkitd/src/scheduler.rs`, `runtime/tmux.rs`, `runtime/herdr.rs`):** + - Fire-time resolution by exact `agent_name` against `store.lookup_name` (after `import_legacy_agents`), falling back to unique live match in `daemon.enriched`, rejecting tombstoned/dead/ambiguous/durable targets. + - `HerdrRuntime::send_prompt(pane_id, message)` (`herdr agent prompt `, 10s timeout). + - `TmuxRuntime::pane_for_pid(pid)` (`ps -p -o tty=` + `tmux list-panes -a -F "#{pane_tty}|#{pane_id}"`) and `TmuxRuntime::send_to_pane(pane_id, message)` (`load-buffer` stdin + `paste-buffer -p -d` + `150ms` + `send-keys Enter`, 10s timeout per step, best-effort `delete-buffer` on error). + - Narrow subprocess fallback (`ai-devkit agent send --id --stdin`, 15s timeout) only for live agents outside `herdr`/`tmux`. +5. **Dedicated 2s Scheduler Task (`rust/crates/devkitd/src/server.rs`):** Spawned in `serve()` **after** `UnixListener::bind()` and `main.rs`'s initial `apply_sweep()`. Immediate first tick (`t=0`) runs startup reconciliation; subsequent 2s ticks run on `spawn_blocking` independently of `apply_sweep()`. +6. **CLI (`packages/cli`):** + - `util/time.ts`: `parseDurationMs` (`s`/`m`/`h`/`d`, compound ok, `<=365d`) and `parseFutureIsoTimestamp` (strict TZ-required RFC3339, rollover check). + - `services/agent/agent-schedule.service.ts`: Daemon-only service matching `agent-group.service.ts`. + - `services/agent/agent.service.ts`: Extended `assertSendTargetOptions` (`--in` XOR `--at`, rejects `--group`/`--wait`/`--timeout`). + - `commands/agent/send.command.ts`: Branches to scheduled create when `--in`/`--at` is present, rejects durable targets upfront, warns non-fatally if target is not currently live, computes `dueAt` after `ensureDaemon()`. + - `commands/agent/schedule.command.ts`: `agent schedule list` and `agent schedule cancel `. + +## Data Models + +```sql +CREATE TABLE IF NOT EXISTS scheduled_sends ( + id TEXT PRIMARY KEY, + agent_name TEXT NOT NULL, + message TEXT NOT NULL, + due_at TEXT NOT NULL, + status TEXT NOT NULL CHECK(status IN ('pending','sent','late','cancelled','failed','skipped')), + failure_reason TEXT, + created_by TEXT, + created_at TEXT NOT NULL, + sent_at TEXT +); + +CREATE INDEX IF NOT EXISTS idx_scheduled_sends_pending_due + ON scheduled_sends(due_at, id) WHERE status = 'pending'; + +CREATE INDEX IF NOT EXISTS idx_scheduled_sends_due + ON scheduled_sends(due_at DESC, id DESC); +``` + +### State Machine + +- Initial state: `pending` +- Terminal states (immutable): + - `pending -> sent`: delivered on time (`due_at >= daemon.started_at` and `age <= 60s`), `sent_at` set. + - `pending -> late`: delivered overdue within 1h (`age <= 3_600_000` and (`due_at < daemon.started_at` or `age > 60s`)), `sent_at` set. + - `pending -> skipped`: overdue beyond 1h (`age > 3_600_000`), `failure_reason` set, `sent_at` NULL. + - `pending -> failed`: target missing/exited/ambiguous/durable or delivery error, `failure_reason` set, `sent_at` NULL. + - `pending -> cancelled`: cancelled via `schedule.cancel` while not in-flight. + +## API Design + +| Method | Params | Result | Coded Errors | +| :--- | :--- | :--- | :--- | +| `schedule.create` | `{ agentName, message, dueAt, createdBy? }` | `ScheduledSend` | `invalid_params`, `storage` | +| `schedule.list` | `{ status?, agentName?, limit? }` (default 50, max 500) | `ScheduledSend[]` | `invalid_params`, `storage` | +| `schedule.cancel` | `{ id }` | `ScheduledSend` | `invalid_params`, `not_found`, `not_cancellable`, `storage` | + +## Design Decisions + +- **Dedicated 2s interval task vs piggyback in `apply_sweep()`:** Separate task prevents delivery I/O from stalling `agent.list`/`agent wait` events and keeps `agent.start`'s synchronous `apply_sweep()` side-effect-free. Wall-clock polling avoids monotonic-sleep drift across OS suspend. +- **`load-buffer` + `paste-buffer -p -d` vs `send-keys -l`:** Mirrors TS `tmuxBackend`, avoids `ARG_MAX` and key-name interpretation, preserves multiline prompts via bracketed paste. +- **64 KiB message cap:** Protects PTY buffers, DB size, and stays safely under Linux's 128 KiB `MAX_ARG_STRLEN` for `herdr agent prompt `. +- **Independent from PR #481:** Uses crate-internal `TmuxRuntime::pane_for_pid(pid)` to avoid blocking on #481 or creating merge conflicts in `proto.rs`/`lookup.rs`/`registry.rs`. +- **In-memory `in_flight` guard:** Prevents `schedule.cancel` racing an active paste without introducing a 7th DB status. + +## Non-Functional Requirements + +- **Security:** `execFile`/argv-only subprocess calls (no shell); socket remains `0600` same-uid (`SO_PEERCRED`); `64 KiB` message cap; per-command timeouts (10s tmux/herdr, 15s CLI fallback). +- **Reliability:** WAL SQLite persistence across crashes/reboots; sequential same-tick execution ordered by `(due_at ASC, id ASC)`; amortized history pruning keeps DB bounded. diff --git a/docs/ai/implementation/2026-11-25-feature-scheduled-sends.md b/docs/ai/implementation/2026-11-25-feature-scheduled-sends.md new file mode 100644 index 00000000..bd8049b4 --- /dev/null +++ b/docs/ai/implementation/2026-11-25-feature-scheduled-sends.md @@ -0,0 +1,32 @@ +--- +phase: implementation +title: Implementation Guide +description: Implementation notes and file inventory for scheduled agent sends (#482) +--- + +# Implementation Guide + +## Development Setup +- Worktree: `/home/ubuntu/code/ai-devkit/.worktrees/feature-scheduled-sends` (branch `feature-scheduled-sends`). +- Build Rust workspace: `cargo test --workspace` / `cargo build -p devkitd`. +- Regenerate TS bindings from Rust `proto.rs`: `cargo test -p devkit-core export_ts_bindings`. +- Build TS packages: `npm run build`. + +## Code Structure (Planned & Updated as Implemented) +- `rust/crates/devkit-core/src/store/schedules.rs` — SQLite schema, RFC3339 parser, `ScheduledSend` store ops. +- `rust/crates/devkit-core/src/store.rs` — wire `init_schedules` and re-exports. +- `rust/crates/devkit-core/src/proto.rs` — wire types + `ts-rs` exports. +- `rust/crates/devkitd/src/runtime/tmux.rs` — `pane_for_pid` and `send_to_pane`. +- `rust/crates/devkitd/src/runtime/herdr.rs` — `send_prompt`. +- `rust/crates/devkitd/src/scheduler.rs` — fire-time resolution, hybrid deliverer, unified tick/late engine. +- `rust/crates/devkitd/src/rpc/schedule.rs` — `schedule.create/list/cancel` handlers. +- `rust/crates/devkitd/src/server.rs` — `in_flight` guard, `schedule.*` dispatch, dedicated 2s scheduler task. +- `packages/daemon-client/src/{client.ts,index.ts,gen/*}` — generated types + `DaemonClient` schedule methods. +- `packages/cli/src/util/time.ts` — `parseDurationMs`, `parseFutureIsoTimestamp`. +- `packages/cli/src/services/agent/agent-schedule.service.ts` — daemon-only schedule service. +- `packages/cli/src/services/agent/agent.service.ts` — `assertSendTargetOptions` schedule validation. +- `packages/cli/src/commands/agent/{send,schedule,agent}.command.ts` — CLI commands. + +## Implementation Notes +- All components match the design doc: `scheduled_sends` SQLite table with partial pending index and amortized retention pruning (`1000` rows / `30d`), zero-`chrono` RFC3339 parser, `ts-rs` generated bindings in `packages/daemon-client/src/gen/`, `schedule.create`/`list`/`cancel` RPC handlers with `in_flight_schedules` cancel guard, dedicated 2s `tokio::time::interval` scheduler loop spawned after socket bind, hybrid delivery engine (`herdr` → exact TTY-matched `tmux` bracketed paste → CLI fallback), and daemon-only CLI commands (`agent send --in/--at`, `agent schedule list/cancel`). +- Follow-up (non-blocking): `schedule.cancel` checks `in_flight_schedules` before acquiring the SQLite connection lock, leaving a narrow theoretical race window if a cancel arrives in the same microsecond a due schedule begins delivery; acceptable for v1 and can be tightened with a shared lock if needed. diff --git a/docs/ai/planning/2026-11-25-feature-scheduled-sends.md b/docs/ai/planning/2026-11-25-feature-scheduled-sends.md new file mode 100644 index 00000000..1428b89e --- /dev/null +++ b/docs/ai/planning/2026-11-25-feature-scheduled-sends.md @@ -0,0 +1,50 @@ +--- +phase: planning +title: Project Planning & Task Breakdown +description: Ordered TDD implementation plan for scheduled agent sends (#482) +--- + +# Project Planning & Task Breakdown + +## Milestones + +- [x] Milestone 1: Rust store, RFC3339 parser, and wire protocol (`devkit-core` + `daemon-client` gen types) +- [x] Milestone 2: Rust delivery engine, RPC handlers, and dedicated scheduler task (`devkitd`) +- [x] Milestone 3: TypeScript `DaemonClient`, CLI `agent send --in/--at`, and `agent schedule list/cancel` +- [x] Milestone 4: Full unit/integration test suites, real-daemon end-to-end smoke test, review, rebase, and PR + +## Task Breakdown + +### Phase 1: Rust Store & Wire Types (`devkit-core`) +- [x] Task 1.1: Implement `parse_iso8601_utc_ms` and `scheduled_sends` store module (`rust/crates/devkit-core/src/store/schedules.rs`) with TDD unit tests (`rust/crates/devkit-core/tests/schedules.rs`): create, list (filters/ordering/limit), cancel (pending/missing/terminal), due query, state transitions (`sent`/`late`/`skipped`/`failed`/`cancelled`), validation (64 KiB cap, blank fields, past/invalid timestamps), retention pruning. +- [x] Task 1.2: Add `ScheduledSend`, `ScheduleCreateParams`, `ScheduleListParams`, `ScheduleCancelParams` to `rust/crates/devkit-core/src/proto.rs` and regenerate `packages/daemon-client/src/gen/*.ts` via `cargo test -p devkit-core`. + +### Phase 2: Rust Delivery Engine, RPC & Scheduler (`devkitd`) +- [x] Task 2.1: Add `TmuxRuntime::pane_for_pid` and `TmuxRuntime::send_to_pane` (stdin `load-buffer` + `paste-buffer -p -d` + 150ms + `send-keys Enter` + cleanup/timeouts) and `HerdrRuntime::send_prompt` with `FixtureDir` unit tests. +- [x] Task 2.2: Implement `rust/crates/devkitd/src/scheduler.rs` (fire-time resolution, hybrid delivery engine with injectable deliverer, unified late/skip policy, sequential `(due_at, id)` execution, `in_flight` guard) and `rust/crates/devkitd/src/rpc/schedule.rs` (`schedule.create/list/cancel`). +- [x] Task 2.3: Wire `schedule.*` dispatch and dedicated 2s scheduler task in `rust/crates/devkitd/src/server.rs`, plus integration tests in `rust/crates/devkitd/tests/rpc/schedules.rs`. + +### Phase 3: Daemon Client & CLI (`packages/daemon-client`, `packages/cli`) +- [x] Task 3.1: Add `createSchedule`, `listSchedules`, `cancelSchedule` to `packages/daemon-client/src/client.ts` and re-export generated types in `packages/daemon-client/src/index.ts`. +- [x] Task 3.2: Add `parseDurationMs` and `parseFutureIsoTimestamp` to `packages/cli/src/util/time.ts` with unit tests. +- [x] Task 3.3: Create `packages/cli/src/services/agent/agent-schedule.service.ts`, extend `assertSendTargetOptions` in `packages/cli/src/services/agent/agent.service.ts`, wire `--in`/`--at` into `packages/cli/src/commands/agent/send.command.ts`, and add `packages/cli/src/commands/agent/schedule.command.ts` (registered in `agent.command.ts`). Add unit tests for all new service and command paths. + +### Phase 4: Verification, Smoke, Review & PR +- [x] Task 4.1: Run full Rust tests (`cargo test --workspace`), TS build (`npm run build`), TS tests (`npx vitest run` across affected packages), and linter/formatter. +- [x] Task 4.2: Run disposable sandboxed `dev-smoke` script against real built `devkitd` + real CLI + real/stub tmux session verifying schedule creation, exact multi-pane delivery, cancel, late/skip on daemon restart, and missing-target failure. +- [x] Task 4.3: Reconcile docs, perform `dev-simplify` + `dev-review`, commit cleanly, rebase onto `origin/main`, push, and open PR referencing #482. + +## Dependencies + +- Task 1.2 depends on 1.1 (`ScheduledSend` type). +- Task 2.2 depends on 1.1, 1.2, 2.1. +- Task 2.3 depends on 2.2. +- Task 3.1 depends on 1.2 (generated TS types). +- Task 3.3 depends on 3.1 and 3.2. +- Task 4.1–4.3 depend on all implementation tasks. + +## Risks & Mitigation + +- **PR #481 merge conflict:** Avoid touching `proto.rs` `AgentLookup*`, `lookup.rs`, or `registry.rs`; keep `pane_for_pid` internal in `tmux.rs`. +- **Autostart 3s timeout:** Spawn scheduler task strictly after `UnixListener::bind()` in `serve()`. +- **Subprocess hangs:** Enforce hard timeouts on tmux/herdr (10s) and CLI fallback (15s). diff --git a/docs/ai/requirements/2026-11-25-feature-scheduled-sends.md b/docs/ai/requirements/2026-11-25-feature-scheduled-sends.md new file mode 100644 index 00000000..9f514368 --- /dev/null +++ b/docs/ai/requirements/2026-11-25-feature-scheduled-sends.md @@ -0,0 +1,64 @@ +--- +phase: requirements +title: Requirements & Problem Understanding +description: Scheduled agent sends (#482) — persistent one-shot delayed message delivery via devkitd +--- + +# Requirements & Problem Understanding + +## Problem Statement + +Waking or messaging an agent at a future time currently requires external machinery (host `crontab` shelling `ai-devkit agent send`, or ad-hoc `tmux` sleep scripts). Those workarounds are machine-local, invisible to `ai-devkit`, unlistable/uncancellable, and break when `cron` is unavailable or `devkitd` restarts. + +`devkitd` is the natural owner: it runs persistently, owns `daemon.db`, owns live agent discovery and registration lookup, and can resolve exact terminal panes for running agents. + +## Goals & Objectives + +### Primary Goals +- Persist one-shot scheduled sends in `daemon.db` (`scheduled_sends`) owned exclusively by `devkitd`. +- Deliver due messages server-side to the target agent's exact terminal pane (exact tmux pane via TTY matching, `herdr` pane via `herdr agent prompt`, and narrow subprocess fallback for unmanaged desktop terminals). +- Resolve target `agent_name` at fire time (never pinning PIDs at schedule time), failing honestly when renamed, exited, ambiguous, or durable. +- Apply an explicit late/skip policy when `devkitd` was down or the host slept past `due_at`: deliver as `late` if age ≤ 1 hour, else mark `skipped`. +- Expose daemon RPC methods (`schedule.create`, `schedule.list`, `schedule.cancel`) with generated TypeScript wire types in `@ai-devkit/daemon-client`. +- Expose CLI UX: + - `ai-devkit agent send --id (--in | --at ) [message] [--stdin] [--json]` + - `ai-devkit agent schedule list [--status ] [--agent ] [--limit ] [--json]` + - `ai-devkit agent schedule cancel [--json]` + +### Non-Goals (Out of Scope for v1) +- Recurring schedules, `--every`, or cron expressions. +- Telegram/Slack relay of scheduled messages (direct pane delivery only). +- Scheduled sends to `--group` or durable (print-mode) agents. +- Real-time delivery SLA tighter than the 2s scheduler tick or guarantees beyond the 1h late policy. +- Speculative `schedule.*` daemon events (no v1 subscriber). + +## User Stories & Use Cases + +- **Self-wakeup orchestration:** As an orchestrator agent, I want to run `ai-devkit agent send --id --in 15m "checkin orchestration"` and end my turn so `devkitd` wakes me reliably even across daemon restarts or machine reboots (with `devkitd install`). +- **Absolute scheduling:** As a user or agent, I want to schedule a message for an exact UTC/offset ISO-8601 timestamp with `--at 2026-11-25T21:00:00Z`. +- **Visibility and cancellation:** As a user or agent, I want to inspect pending and historical schedules via `ai-devkit agent schedule list [--json]` and cancel pending ones via `ai-devkit agent schedule cancel `. +- **Multi-pane tmux accuracy:** As a user running multiple agents in panes of one tmux session, I want scheduled sends delivered to the exact pane hosting the target agent, not the active pane. + +## Success Criteria + +- Scheduling with `--in` or `--at` persists a `pending` row in `daemon.db` and returns its `id` and canonical UTC `dueAt`. +- Due sends deliver to the exact tmux pane (`%pane_id` matched by TTY) using bracketed paste (`load-buffer` + `paste-buffer -p -d` + `150ms` + `send-keys Enter`), or to `herdr` via `herdr agent prompt`, or via subprocess fallback for unmanaged non-tmux/non-herdr terminals. +- `agent schedule list [--json]` reflects `pending | sent | late | cancelled | failed | skipped`; `agent schedule cancel ` cancels `pending` rows and rejects unknown or terminal rows with clear errors. +- Daemon restart (or host sleep/wake) past `due_at` delivers as `late` if age ≤ 1h and marks `skipped` if age > 1h. +- Target renamed or exited at fire time transitions to `failed` with an explicit `failure_reason`. +- CLI validates `--in` XOR `--at`, rejects incompatible `--group`/`--wait`/`--timeout`, rejects durable agents upfront, and warns non-fatally if no live interactive agent currently matches `--id`. +- Unit tests cover store/state machine, delivery engine, RPC handlers, scheduler ticks, duration/ISO parsing, and CLI flag validation; stub-provider integration/E2E tests verify full flow without real provider APIs. + +## Constraints & Assumptions + +- Build independently on `main` without depending on unmerged PR #481 (`feature-channel-resolution`); implement a small internal `TmuxRuntime::pane_for_pid(pid)` that can later unify with #481's `terminal_target()`. +- Keep `devkit-core` free of `chrono` (use existing `iso8601_utc` + `days_from_civil`). +- Tests follow `AGENTS.md`: package tests in `packages//tests/` and Rust crate tests in `rust/crates//tests/` or `#[cfg(test)]`. +- Scheduled sends require a running `devkitd` (no local fallback, matching `agent group`). + +## Resolved Rulings + +All open design questions were resolved before implementation (A/A/A): +1. **PR #481 sequencing:** Independent on `main` via internal `TmuxRuntime::pane_for_pid(pid)`. +2. **Create-time target check:** Allow any non-empty `agent_name` with a non-fatal CLI warning if not currently live; fail fast upfront if `--id` resolves to a durable agent. +3. **Unmanaged terminal fallback:** Include narrow subprocess fallback (`ai-devkit agent send --id --stdin`, 15s timeout) when a live agent is outside `tmux`/`herdr`. diff --git a/docs/ai/testing/2026-11-25-feature-scheduled-sends.md b/docs/ai/testing/2026-11-25-feature-scheduled-sends.md new file mode 100644 index 00000000..5f122a43 --- /dev/null +++ b/docs/ai/testing/2026-11-25-feature-scheduled-sends.md @@ -0,0 +1,60 @@ +--- +phase: testing +title: Testing Strategy +description: Unit, integration, and smoke test plan for scheduled agent sends (#482) +--- + +# Testing Strategy + +## Test Coverage Goals + +- Unit tests covering 100% of new state-machine transitions, validation branches, duration/ISO parsers, delivery adapters, and CLI option validation. +- Integration tests exercising real `devkitd` RPC (`schedule.create/list/cancel`), scheduler ticks, startup restart reconciliation, and multi-pane tmux fixture delivery. +- Disposable sandboxed smoke test driving real compiled `devkitd` + built `ai-devkit` CLI end to end. + +## Unit Tests + +### `devkit-core` Store & Timestamp Parser (`rust/crates/devkit-core/tests/schedules.rs`) +- [x] Create schedule persists canonical UTC ISO-8601 `due_at`, `created_at`, `pending` status, short `sch_` ID, optional `created_by`. +- [x] Validation rejects blank `agent_name`, `agent_name > 128` chars, blank `message`, `message > 64 KiB`, invalid ISO-8601, missing timezone, past `due_at`. +- [x] ISO-8601 parser accepts `Z` and `±HH:MM` offsets, fractional seconds, and rejects invalid dates (e.g. Feb 30). +- [x] State transitions: `pending -> sent`, `pending -> late`, `pending -> skipped`, `pending -> failed`, `pending -> cancelled`. +- [x] Cancel on non-existent ID returns `not_found`; cancel on terminal row returns `not_cancellable` with current status. +- [x] `list_schedules` supports `status` filter, `agent_name` filter, `limit` clamping, and ordering (pending soonest-first, terminal newest-first). +- [x] `due_pending` returns only `pending` rows with `due_at <= now`, ordered by `(due_at ASC, id ASC)`. +- [x] Amortized pruning deletes old terminal rows past retention cap while never deleting `pending` rows. + +### `devkitd` Runtimes & Scheduler (`rust/crates/devkitd/src/runtime/{tmux,herdr}.rs`, `scheduler.rs`) +- [x] `TmuxRuntime::pane_for_pid` selects exact TTY-matched `%pane_id` in multi-pane tmux output (not first pane). +- [x] `TmuxRuntime::send_to_pane` pipes stdin to `load-buffer`, calls `paste-buffer -t %pane -p -d`, and sends `send-keys -t %pane Enter`; deletes buffer on paste failure. +- [x] `HerdrRuntime::send_prompt` runs `herdr agent prompt ` and surfaces JSON errors. +- [x] Scheduler tick marks `age > 1h` as `skipped` without invoking deliverer. +- [x] Scheduler tick marks overdue `<= 1h` (when `due_at < started_at` or `age > 60s`) as `late` on delivery success. +- [x] Scheduler tick marks on-time due sends as `sent` with `sent_at`. +- [x] Renamed/missing, dead/tombstoned, ambiguous unregistered, and durable targets mark `failed` with explicit `failure_reason`. +- [x] Concurrent same-tick due rows deliver sequentially in `(due_at, id)` order. +- [x] `in_flight` guard rejects `schedule.cancel` with `not_cancellable` while delivery is active. +- [x] Unmanaged live agent (outside tmux/herdr) routes to subprocess fallback; missing CLI fails with clear PATH-aware reason. + +### CLI & Daemon Client (`packages/cli/tests/...`, `packages/daemon-client/tests/...`) +- [x] `parseDurationMs`: valid single/compound (`30s`, `15m`, `2h`, `1d`, `1h30m`, uppercase); rejects bare numbers, `0m`, negatives, duplicates (`1h2h`), `>365d`. +- [x] `parseFutureIsoTimestamp`: valid `Z` and offset timestamps normalized to UTC; rejects missing TZ, invalid calendar dates (`2026-02-30`), and past timestamps. +- [x] `assertSendTargetOptions`: `--in` XOR `--at`, rejects `--group` + `--in/--at`, rejects `--wait`/`--timeout` + `--in/--at`, preserves immediate sends. +- [x] `AgentScheduleService`: daemon-only error when no daemon, `unknown method` upgrade hint, coded error mapping (`not_found`, `not_cancellable`, `invalid_params`). +- [x] `agent send --id --in/--at`: creates schedule, rejects durable target upfront, warns non-fatally when target not currently live, outputs `--json` or human summary. +- [x] `agent schedule list [--status] [--agent] [--limit] [--json]` and `agent schedule cancel [--json]`. + +## Integration Tests (`rust/crates/devkitd/tests/rpc/schedules.rs`) +- [x] Full socket RPC round-trip: `schedule.create` → `schedule.list` → `schedule.cancel` → verify cancelled state. +- [x] Restart recovery: seed DB with one due 5m ago and one due 2h ago → start fresh `Daemon` → verify first fires as `late` and second marks `skipped`. + +## End-to-End / Smoke Tests (Disposable Sandboxed Script) +- [x] Real built `devkitd` + built `ai-devkit` CLI in isolated `HOME` with stub tmux session (multi-pane): schedule send via `agent send --id --in 2s "hello"`, verify exact pane receives message, verify `agent schedule list --json` shows `sent`. +- [x] Schedule future send, cancel via `agent schedule cancel `, verify `cancelled` and never delivered. +- [x] Restart `devkitd` with pre-seeded overdue rows (5m late + 2h late), verify `late` and `skipped` statuses. +- [x] Schedule for non-existent target, verify warning on create and `failed` status with reason at fire time. + +## Test Reporting & Coverage +- Rust: `cargo test --workspace` +- TS build & tests: `npm run build && npx vitest run` (in `packages/daemon-client`, `packages/cli`) +- Lint: `npx ai-devkit@latest lint --feature scheduled-sends` diff --git a/packages/cli/src/commands/agent/agent.command.ts b/packages/cli/src/commands/agent/agent.command.ts index 9316b72c..6f1914d3 100644 --- a/packages/cli/src/commands/agent/agent.command.ts +++ b/packages/cli/src/commands/agent/agent.command.ts @@ -11,6 +11,7 @@ import { registerAgentDetailCommand } from "./detail.command.js"; import { registerAgentRenameCommand } from "./rename.command.js"; import { registerAgentConsoleCommand } from "./console.command.js"; import { registerAgentWaitCommand } from "./wait.command.js"; +import { registerAgentScheduleCommand } from "./schedule.command.js"; export function registerAgentCommand(program: Command): void { const agentCommand = program.command("agent").description("Manage AI Agents"); @@ -19,6 +20,7 @@ export function registerAgentCommand(program: Command): void { registerAgentListCommand(agentCommand); registerAgentSessionsCommand(agentCommand); registerAgentGroupCommand(agentCommand); + registerAgentScheduleCommand(agentCommand); registerAgentSessionCommand(agentCommand); registerAgentOpenCommand(agentCommand); registerAgentSendCommand(agentCommand); diff --git a/packages/cli/src/commands/agent/schedule.command.ts b/packages/cli/src/commands/agent/schedule.command.ts new file mode 100644 index 00000000..e0680628 --- /dev/null +++ b/packages/cli/src/commands/agent/schedule.command.ts @@ -0,0 +1,145 @@ +import { Command } from "commander"; +import chalk from "chalk"; +import { ui } from "../../util/terminal-ui.js"; +import { withErrorHandler } from "../../util/errors.js"; +import { createLogger, enableDebug } from "../../util/debug.js"; +import { formatRelativeOrAbsoluteTime } from "../../util/time-format.js"; +import { + createDefaultAgentScheduleService, + type ScheduledSend, +} from "../../services/agent/agent-schedule.service.js"; + +const debug = createLogger("agent:schedule"); + +function scheduleService(options?: { debug?: boolean }) { + if (options?.debug) { + enableDebug(); + } + return createDefaultAgentScheduleService({ onDebug: debug }); +} + +function colorScheduleStatus(status: string): string { + switch (status) { + case "pending": + return chalk.yellow(status); + case "sent": + return chalk.green(status); + case "late": + return chalk.cyan(status); + case "failed": + return chalk.red(status); + case "cancelled": + case "skipped": + return chalk.dim(status); + default: + return status; + } +} + +function formatMessagePreview(schedule: ScheduledSend): string { + const singleLine = schedule.message.replace(/\s+/g, " ").trim(); + const preview = singleLine.length > 60 ? `${singleLine.slice(0, 57)}...` : singleLine; + if (schedule.failureReason) { + return `${preview} (${schedule.failureReason})`; + } + return preview; +} + +function parseLimit(value: string | undefined): number | undefined { + if (value === undefined) return undefined; + const trimmed = value.trim(); + if (!/^\d+$/.test(trimmed)) { + throw new Error(`Invalid --limit "${value}". Expected a positive integer.`); + } + const n = Number(trimmed); + if (!Number.isFinite(n) || n < 1) { + throw new Error(`Invalid --limit "${value}". Expected a positive integer.`); + } + return n; +} + +export function registerAgentScheduleCommand(agentCommand: Command): void { + const scheduleCommand = agentCommand + .command("schedule") + .description("List and manage scheduled agent sends"); + + scheduleCommand + .command("list") + .description("List scheduled agent sends") + .option( + "--status ", + "Filter by status (pending, sent, late, cancelled, failed, skipped)", + ) + .option("--agent ", "Filter by target agent name") + .option("--limit ", "Maximum number of rows to return (default: 50, max: 500)") + .option("-j, --json", "Output as JSON") + .option("--debug", "Enable debug logging") + .action( + withErrorHandler( + "list scheduled sends", + async (options: { + status?: string; + agent?: string; + limit?: string; + json?: boolean; + debug?: boolean; + }) => { + const limit = parseLimit(options.limit); + const schedules = await scheduleService(options).list({ + ...(options.status ? { status: options.status } : {}), + ...(options.agent ? { agentName: options.agent } : {}), + ...(limit !== undefined ? { limit } : {}), + }); + + if (options.json) { + console.log(JSON.stringify(schedules, null, 2)); + return; + } + + if (schedules.length === 0) { + ui.info("No scheduled sends."); + return; + } + + const maxWidth = process.stdout.columns ?? 120; + ui.table({ + headers: ["ID", "Agent", "Status", "Due", "Message"], + rows: schedules.map((item) => [ + item.id, + item.agentName, + item.status, + formatRelativeOrAbsoluteTime(item.dueAt), + formatMessagePreview(item), + ]), + maxWidth, + columnStyles: [ + (text) => chalk.dim(text), + (text) => chalk.cyan(text), + colorScheduleStatus, + (text) => chalk.dim(text), + (text) => text, + ], + }); + }, + ), + ); + + scheduleCommand + .command("cancel ") + .description("Cancel a pending scheduled send") + .option("-j, --json", "Output as JSON") + .option("--debug", "Enable debug logging") + .action( + withErrorHandler( + "cancel scheduled send", + async (id: string, options: { json?: boolean; debug?: boolean }) => { + const cancelled = await scheduleService(options).cancel(id); + if (options.json) { + console.log(JSON.stringify(cancelled, null, 2)); + return; + } + ui.success(`Cancelled scheduled send "${cancelled.id}" for "${cancelled.agentName}".`); + }, + ), + ); +} diff --git a/packages/cli/src/commands/agent/send.command.ts b/packages/cli/src/commands/agent/send.command.ts index b1cbbc3b..1c2381de 100644 --- a/packages/cli/src/commands/agent/send.command.ts +++ b/packages/cli/src/commands/agent/send.command.ts @@ -17,7 +17,10 @@ import { type SendReporter, } from "../../services/agent/agent.service.js"; import { resolveTextFromStdinOption } from "../../util/stdin.js"; +import { parseDurationMs, parseFutureIsoTimestamp } from "../../util/time.js"; +import { formatLocalTimestampWithRelative } from "../../util/time-format.js"; import { createDefaultAgentGroupService } from "../../services/agent/agent-group.service.js"; +import { createDefaultAgentScheduleService } from "../../services/agent/agent-schedule.service.js"; import { resolveDurableAgentEntry } from "../../services/agent/resolve-agent.service.js"; import { createAgentManager, @@ -114,16 +117,38 @@ function createCommandSendReporter(): SendReporter { }; } +async function isLiveInteractiveTarget(daemon: DaemonClient, agentName: string): Promise { + try { + const entry = await daemon.lookupAgent(agentName); + return entry.alive; + } catch (error) { + if (!(error instanceof DaemonRpcError && error.code === "not_found")) { + return false; + } + } + try { + const live = await daemon.listAgents(); + return live.some((agent) => agent.name === agentName); + } catch { + return false; + } +} + export function registerAgentSendCommand(agentCommand: Command): void { agentCommand .command("send [message]") - .description("Send a message to a running agent") + .description("Send a message to a running agent (or schedule one for later)") .option("--id ", "Agent name or partial match") .option("--group ", "Agent group name") + .option("--in ", "Schedule delivery after a relative duration (e.g. 15m, 2h, 1d)") + .option( + "--at ", + "Schedule delivery at an ISO-8601 UTC/offset timestamp (e.g. 2026-11-25T21:00:00Z)", + ) .option("--stdin", "Read the message from stdin") .option("--wait", "Wait for and print the agent response") .option("--timeout ", "Maximum time to wait with --wait, in milliseconds") - .option("-j, --json", "Output wait result as JSON") + .option("-j, --json", "Output wait or schedule result as JSON") .option("--debug", "Enable debug logging") .action( withErrorHandler("send message", async (message, options) => { @@ -132,6 +157,61 @@ export function registerAgentSendCommand(agentCommand: Command): void { } assertSendTargetOptions(options); const prompt = await resolveSendMessage(message, options); + + if (options.in !== undefined || options.at !== undefined) { + const manager = createAgentManager(); + const durableResolved = await resolveDurableAgentEntry(options.id, () => + manager.listAgents(), + ); + if (durableResolved) { + throw new Error( + `Agent "${durableResolved.name}" is a durable agent; scheduled sends support direct pane delivery only.`, + ); + } + + const daemon = await ensureDaemon({ onDebug: debug }); + if (!daemon) { + throw new Error( + "A running, capable daemon is required for scheduled sends. Start devkitd and retry.", + ); + } + try { + const targetName = String(options.id).trim(); + if (!(await isLiveInteractiveTarget(daemon, targetName))) { + const warn = `No running interactive agent named "${targetName}" right now; it will be resolved at fire time.`; + if (options.json) { + process.stderr.write(`Warning: ${warn}\n`); + } else { + ui.warning(warn); + } + } + const dueAt = + options.in !== undefined + ? new Date(Date.now() + parseDurationMs(options.in)).toISOString() + : parseFutureIsoTimestamp(options.at); + const createdBy = process.env.AI_DEVKIT_AGENT_NAME?.trim() || undefined; + const schedule = await createDefaultAgentScheduleService({ + client: daemon, + onDebug: debug, + }).create({ + agentName: targetName, + message: prompt, + dueAt, + ...(createdBy ? { createdBy } : {}), + }); + if (options.json) { + console.log(JSON.stringify(schedule, null, 2)); + } else { + ui.success( + `Scheduled message for "${schedule.agentName}" at ${formatLocalTimestampWithRelative(new Date(schedule.dueAt))} [id: ${schedule.id}].`, + ); + } + } finally { + daemon.close(); + } + return; + } + const focusManager = new TerminalFocusManager(); if (options.group) { diff --git a/packages/cli/src/services/agent/agent-schedule.service.ts b/packages/cli/src/services/agent/agent-schedule.service.ts new file mode 100644 index 00000000..f55821a0 --- /dev/null +++ b/packages/cli/src/services/agent/agent-schedule.service.ts @@ -0,0 +1,136 @@ +import { + DaemonRpcError, + ensureDaemon, + type DaemonClient, + type ScheduleCreateParams, + type ScheduleListParams, + type ScheduledSend, +} from "@ai-devkit/daemon-client"; + +export type { + ScheduleCreateParams, + ScheduleListParams, + ScheduledSend, +} from "@ai-devkit/daemon-client"; + +export class ScheduledSendNotFoundError extends Error { + constructor(public scheduleId: string) { + super(`Scheduled send "${scheduleId}" not found.`); + this.name = "ScheduledSendNotFoundError"; + } +} + +export class ScheduledSendNotCancellableError extends Error { + constructor( + public scheduleId: string, + public status?: string, + message?: string, + ) { + super( + message ?? + `Cannot cancel scheduled send "${scheduleId}"${status ? `: status is "${status}"` : ""}.`, + ); + this.name = "ScheduledSendNotCancellableError"; + } +} + +export class ScheduledSendInvalidParamsError extends Error { + constructor(message: string) { + super(message); + this.name = "ScheduledSendInvalidParamsError"; + } +} + +export class ScheduledSendStorageError extends Error { + constructor(message: string) { + super(message); + this.name = "ScheduledSendStorageError"; + } +} + +export interface AgentScheduleServiceOptions { + client?: DaemonClient; + onDebug?: (msg: string) => void; +} + +function mapScheduleRpcError(error: unknown, context: { id?: string }): unknown { + if (error instanceof Error && error.message.startsWith("unknown method")) { + return new Error("Upgrade and restart devkitd to use scheduled sends."); + } + if (!(error instanceof DaemonRpcError)) return error; + + const details = error.details as { id?: string; status?: string } | undefined; + const id = details?.id ?? context.id ?? ""; + let mapped: Error; + switch (error.code) { + case "not_found": + mapped = new ScheduledSendNotFoundError(id); + break; + case "not_cancellable": + mapped = new ScheduledSendNotCancellableError(id, details?.status, error.message); + break; + case "invalid_params": + mapped = new ScheduledSendInvalidParamsError(error.message); + break; + case "storage": + mapped = new ScheduledSendStorageError(error.message); + break; + default: + return error; + } + mapped.message = error.message; + return mapped; +} + +/** Daemon-owned scheduled sends. Requires a running devkitd; no local fallback. */ +export class AgentScheduleService { + constructor(private readonly options?: AgentScheduleServiceOptions) {} + + async create(params: ScheduleCreateParams): Promise { + return this.withDaemon("schedule.create", (daemon) => daemon.createSchedule(params), {}); + } + + async list(params: ScheduleListParams = {}): Promise { + return this.withDaemon("schedule.list", (daemon) => daemon.listSchedules(params), {}); + } + + async cancel(id: string): Promise { + return this.withDaemon("schedule.cancel", (daemon) => daemon.cancelSchedule(id), { id }); + } + + private async withDaemon( + method: string, + operation: (daemon: DaemonClient) => Promise, + context: { id?: string }, + ): Promise { + const debug = this.options?.onDebug; + const owned = !this.options?.client; + const daemon = + this.options?.client ?? (await ensureDaemon(debug ? { onDebug: debug } : undefined)); + if (!daemon) { + debug?.(`no daemon available for ${method}; refusing fallback`); + throw new Error( + "A running, capable daemon is required for scheduled sends. Start devkitd and retry.", + ); + } + debug?.(`daemon path: calling ${method}`); + try { + return await operation(daemon); + } catch (error) { + if (error instanceof DaemonRpcError && error.code) { + debug?.(`daemon ${method} returned coded error ${error.code}`); + } else if (error instanceof Error) { + debug?.(`daemon ${method} failed: ${error.message}`); + } + throw mapScheduleRpcError(error, context); + } finally { + if (owned) daemon.close(); + } + } +} + +export function createDefaultAgentScheduleService( + options?: AgentScheduleServiceOptions, +): AgentScheduleService { + return new AgentScheduleService(options); +} diff --git a/packages/cli/src/services/agent/agent.service.ts b/packages/cli/src/services/agent/agent.service.ts index b3900152..d588b216 100644 --- a/packages/cli/src/services/agent/agent.service.ts +++ b/packages/cli/src/services/agent/agent.service.ts @@ -15,7 +15,12 @@ import { AgentTerminalNotFoundError, sendAgentPrompt, } from "@ai-devkit/agent-manager"; -import { parseMilliseconds, sleep } from "../../util/time.js"; +import { + parseDurationMs, + parseFutureIsoTimestamp, + parseMilliseconds, + sleep, +} from "../../util/time.js"; import { ui } from "../../util/terminal-ui.js"; import type { AgentGroup } from "./agent-group.service.js"; import { reportAgentResolution, resolveAgentByName } from "./resolve-agent.service.js"; @@ -107,11 +112,31 @@ export function assertSendTargetOptions(options: { wait?: boolean; timeout?: string; json?: boolean; + in?: string; + at?: string; }): void { const targetCount = Number(Boolean(options.id)) + Number(Boolean(options.group)); if (targetCount !== 1) { throw new Error("Use exactly one of --id or --group."); } + if (options.in !== undefined && options.at !== undefined) { + throw new Error("Use either --in or --at, not both."); + } + const isScheduled = options.in !== undefined || options.at !== undefined; + if (isScheduled && options.group) { + throw new Error("Scheduled sends are not supported with --group; use --id ."); + } + if (isScheduled && (options.wait || options.timeout !== undefined)) { + throw new Error( + "Cannot combine --in/--at with --wait or --timeout; scheduled sends return immediately.", + ); + } + if (options.in !== undefined) { + parseDurationMs(options.in); + } + if (options.at !== undefined) { + parseFutureIsoTimestamp(options.at); + } if (options.group && options.wait) { throw new Error("Use --wait only with --id; group wait mode is not supported."); } diff --git a/packages/cli/src/util/time.ts b/packages/cli/src/util/time.ts index 31e5cb2a..f78b144f 100644 --- a/packages/cli/src/util/time.ts +++ b/packages/cli/src/util/time.ts @@ -1,5 +1,97 @@ const MS_PATTERN = /^\d+$/; const MILLISECONDS_ERROR = "Expected positive integer milliseconds."; +const DURATION_FULL_PATTERN = /^(\d+[smhd])+$/i; +const DURATION_PART_PATTERN = /(\d+)([smhd])/gi; +const MAX_SCHEDULE_DURATION_MS = 365 * 24 * 60 * 60 * 1000; +const ISO_TZ_PATTERN = + /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,9}))?)?(Z|z|[+-]\d{2}:\d{2})$/; + +const DURATION_UNIT_MS: Record = { + s: 1000, + m: 60 * 1000, + h: 60 * 60 * 1000, + d: 24 * 60 * 60 * 1000, +}; + +function daysInMonth(year: number, month: number): number { + if (month === 2) { + const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; + return leap ? 29 : 28; + } + return [4, 6, 9, 11].includes(month) ? 30 : 31; +} + +export function parseDurationMs(value: string): number { + const trimmed = value.trim(); + const invalid = () => + new Error( + `Invalid --in duration "${value}". Use positive durations with units s, m, h, or d (e.g. 30s, 15m, 2h, 1d, 1h30m).`, + ); + if (!DURATION_FULL_PATTERN.test(trimmed)) { + throw invalid(); + } + const seenUnits = new Set(); + let totalMs = 0; + for (const match of trimmed.matchAll(DURATION_PART_PATTERN)) { + const amount = Number(match[1]); + const unit = match[2].toLowerCase(); + if (seenUnits.has(unit) || !Number.isFinite(amount)) { + throw invalid(); + } + seenUnits.add(unit); + totalMs += amount * DURATION_UNIT_MS[unit]; + } + if (!Number.isFinite(totalMs) || totalMs <= 0 || totalMs > MAX_SCHEDULE_DURATION_MS) { + throw invalid(); + } + return totalMs; +} + +export function parseFutureIsoTimestamp(value: string, nowMs = Date.now()): string { + const trimmed = value.trim(); + const invalid = () => + new Error( + `Invalid --at timestamp "${value}". Expected ISO-8601 with timezone (e.g. 2026-11-25T21:00:00Z).`, + ); + const match = ISO_TZ_PATTERN.exec(trimmed); + if (!match) { + throw invalid(); + } + const year = Number(match[1]); + const month = Number(match[2]); + const day = Number(match[3]); + const hour = Number(match[4]); + const minute = Number(match[5]); + const second = match[6] !== undefined ? Number(match[6]) : 0; + const tz = match[8]; + if ( + year < 1970 || + month < 1 || + month > 12 || + day < 1 || + day > daysInMonth(year, month) || + hour > 23 || + minute > 59 || + second > 59 + ) { + throw invalid(); + } + if (tz !== "Z" && tz !== "z") { + const tzHour = Number(tz.slice(1, 3)); + const tzMinute = Number(tz.slice(4, 6)); + if (tzHour > 23 || tzMinute > 59) { + throw invalid(); + } + } + const parsedMs = Date.parse(trimmed); + if (!Number.isFinite(parsedMs)) { + throw invalid(); + } + if (parsedMs <= nowMs) { + throw new Error("--at timestamp must be in the future."); + } + return new Date(parsedMs).toISOString(); +} export interface ParsedMilliseconds { milliseconds: number; diff --git a/packages/cli/tests/commands/agent-schedule.test.ts b/packages/cli/tests/commands/agent-schedule.test.ts new file mode 100644 index 00000000..05d9aa01 --- /dev/null +++ b/packages/cli/tests/commands/agent-schedule.test.ts @@ -0,0 +1,286 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { Command } from "commander"; +import { DaemonRpcError, type ScheduledSend } from "@ai-devkit/daemon-client"; +import { assertSendTargetOptions } from "../../src/services/agent/agent.service.js"; +import { registerAgentSendCommand } from "../../src/commands/agent/send.command.js"; +import { registerAgentScheduleCommand } from "../../src/commands/agent/schedule.command.js"; + +const mocks = vi.hoisted(() => ({ + ensureDaemon: vi.fn(), + lookupAgent: vi.fn(), + listAgents: vi.fn(), + createSchedule: vi.fn(), + listSchedules: vi.fn(), + cancelSchedule: vi.fn(), + close: vi.fn(), + resolveDurable: vi.fn(), + uiSuccess: vi.fn(), + uiWarning: vi.fn(), + uiInfo: vi.fn(), + uiError: vi.fn(), + uiTable: vi.fn(), +})); + +vi.mock("@ai-devkit/daemon-client", async (original) => ({ + ...(await original()), + ensureDaemon: mocks.ensureDaemon, +})); + +vi.mock("../../src/services/agent/resolve-agent.service.js", async (original) => ({ + ...(await original()), + resolveDurableAgentEntry: mocks.resolveDurable, +})); + +vi.mock("../../src/util/terminal-ui.js", () => ({ + ui: { + success: mocks.uiSuccess, + warning: mocks.uiWarning, + info: mocks.uiInfo, + error: mocks.uiError, + table: mocks.uiTable, + text: vi.fn(), + }, +})); + +const sampleSchedule: ScheduledSend = { + id: "sch_deadbeef", + agentName: "worker-1", + message: "checkin", + dueAt: "2026-11-26T12:00:00.000Z", + status: "pending", + createdAt: "2026-11-25T20:00:00.000Z", +}; + +function makeDaemon() { + return { + lookupAgent: mocks.lookupAgent, + listAgents: mocks.listAgents, + createSchedule: mocks.createSchedule, + listSchedules: mocks.listSchedules, + cancelSchedule: mocks.cancelSchedule, + close: mocks.close, + }; +} + +function buildProgram() { + const program = new Command(); + program.exitOverride(); + const agent = program.command("agent"); + registerAgentSendCommand(agent); + registerAgentScheduleCommand(agent); + return program; +} + +describe("scheduled send CLI", () => { + const savedExitCode = process.exitCode; + const savedAgentEnv = process.env.AI_DEVKIT_AGENT_NAME; + let logSpy: ReturnType; + let stderrSpy: ReturnType; + + beforeEach(() => { + vi.clearAllMocks(); + process.exitCode = undefined; + delete process.env.AI_DEVKIT_AGENT_NAME; + logSpy = vi.spyOn(console, "log").mockImplementation(() => {}); + stderrSpy = vi.spyOn(process.stderr, "write").mockImplementation(() => true); + mocks.resolveDurable.mockResolvedValue(null); + mocks.ensureDaemon.mockResolvedValue(makeDaemon()); + mocks.lookupAgent.mockResolvedValue({ + name: "worker-1", + type: "claude", + pid: 123, + runtime: "tmux", + runtimeRef: { session: "worker-1" }, + cwd: "/repo", + pinned: false, + alive: true, + }); + mocks.listAgents.mockResolvedValue([]); + mocks.createSchedule.mockResolvedValue(sampleSchedule); + mocks.listSchedules.mockResolvedValue([sampleSchedule]); + mocks.cancelSchedule.mockResolvedValue({ ...sampleSchedule, status: "cancelled" }); + }); + + afterEach(() => { + process.exitCode = savedExitCode; + if (savedAgentEnv === undefined) delete process.env.AI_DEVKIT_AGENT_NAME; + else process.env.AI_DEVKIT_AGENT_NAME = savedAgentEnv; + logSpy.mockRestore(); + stderrSpy.mockRestore(); + }); + + describe("assertSendTargetOptions schedule flag matrix", () => { + it("enforces --in XOR --at and rejects incompatible flags", () => { + expect(() => + assertSendTargetOptions({ id: "w", in: "15m", at: "2099-01-01T00:00:00Z" }), + ).toThrow("Use either --in or --at, not both."); + expect(() => assertSendTargetOptions({ group: "team", in: "15m" })).toThrow( + /not supported with --group/i, + ); + expect(() => assertSendTargetOptions({ id: "w", in: "15m", wait: true })).toThrow( + /Cannot combine --in\/--at with --wait/i, + ); + expect(() => assertSendTargetOptions({ id: "w", in: "15m", timeout: "5000" })).toThrow( + /Cannot combine --in\/--at with --wait/i, + ); + expect(() => assertSendTargetOptions({ id: "w", in: "15m" })).not.toThrow(); + expect(() => assertSendTargetOptions({ id: "w", at: "2099-01-01T00:00:00Z" })).not.toThrow(); + }); + }); + + it("schedules via --in, captures AI_DEVKIT_AGENT_NAME, and prints human confirmation", async () => { + process.env.AI_DEVKIT_AGENT_NAME = "orchestrator"; + await buildProgram().parseAsync([ + "node", + "ai-devkit", + "agent", + "send", + "--id", + "worker-1", + "--in", + "15m", + "checkin", + ]); + + expect(mocks.createSchedule).toHaveBeenCalledWith( + expect.objectContaining({ + agentName: "worker-1", + message: "checkin", + createdBy: "orchestrator", + }), + ); + expect(mocks.uiWarning).not.toHaveBeenCalled(); + expect(mocks.uiSuccess).toHaveBeenCalledWith(expect.stringContaining("sch_deadbeef")); + expect(mocks.close).toHaveBeenCalledOnce(); + }); + + it("warns to stderr when target is not currently live and outputs pure JSON under --json", async () => { + mocks.lookupAgent.mockRejectedValue(new DaemonRpcError("not found", "not_found")); + mocks.listAgents.mockResolvedValue([]); + + await buildProgram().parseAsync([ + "node", + "ai-devkit", + "agent", + "send", + "--id", + "future-worker", + "--at", + "2099-01-01T00:00:00Z", + "--json", + "wake up", + ]); + + expect(stderrSpy).toHaveBeenCalledWith(expect.stringContaining("future-worker")); + expect(mocks.uiWarning).not.toHaveBeenCalled(); + expect(logSpy).toHaveBeenCalledWith(JSON.stringify(sampleSchedule, null, 2)); + expect(mocks.createSchedule).toHaveBeenCalledWith({ + agentName: "future-worker", + message: "wake up", + dueAt: "2099-01-01T00:00:00.000Z", + }); + }); + + it("rejects durable targets upfront before contacting schedule.create", async () => { + const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as never); + mocks.resolveDurable.mockResolvedValue({ id: "dur-1", name: "dur-agent", provider: "claude" }); + + try { + await buildProgram().parseAsync([ + "node", + "ai-devkit", + "agent", + "send", + "--id", + "dur-agent", + "--in", + "5m", + "hello", + ]); + + expect(mocks.createSchedule).not.toHaveBeenCalled(); + expect(mocks.uiError).toHaveBeenCalledWith(expect.stringMatching(/durable agent/i)); + expect(exitSpy).toHaveBeenCalledWith(1); + } finally { + exitSpy.mockRestore(); + } + }); + + it("shows empty info message when no schedules exist", async () => { + mocks.listSchedules.mockResolvedValue([]); + await buildProgram().parseAsync(["node", "ai-devkit", "agent", "schedule", "list"]); + expect(mocks.uiInfo).toHaveBeenCalledWith("No scheduled sends."); + expect(mocks.uiTable).not.toHaveBeenCalled(); + }); + + it("rejects non-numeric --limit on schedule list", async () => { + const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as never); + try { + await buildProgram().parseAsync([ + "node", + "ai-devkit", + "agent", + "schedule", + "list", + "--limit", + "abc", + ]); + expect(mocks.listSchedules).not.toHaveBeenCalled(); + expect(mocks.uiError).toHaveBeenCalledWith(expect.stringMatching(/Invalid --limit/)); + expect(exitSpy).toHaveBeenCalledWith(1); + } finally { + exitSpy.mockRestore(); + } + }); + + it("lists schedules in table and JSON formats and passes filters", async () => { + await buildProgram().parseAsync([ + "node", + "ai-devkit", + "agent", + "schedule", + "list", + "--status", + "pending", + "--agent", + "worker-1", + "--limit", + "5", + ]); + expect(mocks.listSchedules).toHaveBeenCalledWith({ + status: "pending", + agentName: "worker-1", + limit: 5, + }); + expect(mocks.uiTable).toHaveBeenCalledOnce(); + + await buildProgram().parseAsync(["node", "ai-devkit", "agent", "schedule", "list", "--json"]); + expect(logSpy).toHaveBeenCalledWith(JSON.stringify([sampleSchedule], null, 2)); + }); + + it("cancels a pending schedule and prints confirmation or JSON", async () => { + await buildProgram().parseAsync([ + "node", + "ai-devkit", + "agent", + "schedule", + "cancel", + "sch_deadbeef", + ]); + expect(mocks.cancelSchedule).toHaveBeenCalledWith("sch_deadbeef"); + expect(mocks.uiSuccess).toHaveBeenCalledWith(expect.stringContaining("sch_deadbeef")); + + await buildProgram().parseAsync([ + "node", + "ai-devkit", + "agent", + "schedule", + "cancel", + "sch_deadbeef", + "--json", + ]); + expect(logSpy).toHaveBeenCalledWith( + JSON.stringify({ ...sampleSchedule, status: "cancelled" }, null, 2), + ); + }); +}); diff --git a/packages/cli/tests/services/agent/agent-schedule.service.test.ts b/packages/cli/tests/services/agent/agent-schedule.service.test.ts new file mode 100644 index 00000000..290cad9c --- /dev/null +++ b/packages/cli/tests/services/agent/agent-schedule.service.test.ts @@ -0,0 +1,94 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { DaemonRpcError, type ScheduledSend } from "@ai-devkit/daemon-client"; +import { + AgentScheduleService, + ScheduledSendInvalidParamsError, + ScheduledSendNotCancellableError, + ScheduledSendNotFoundError, + ScheduledSendStorageError, +} from "../../../src/services/agent/agent-schedule.service.js"; + +const mocks = vi.hoisted(() => ({ + ensure: vi.fn(), + close: vi.fn(), + createSchedule: vi.fn(), + listSchedules: vi.fn(), + cancelSchedule: vi.fn(), +})); + +vi.mock("@ai-devkit/daemon-client", async (original) => ({ + ...(await original()), + ensureDaemon: mocks.ensure, +})); + +const sample: ScheduledSend = { + id: "sch_1234abcd", + agentName: "worker-1", + message: "checkin", + dueAt: "2026-11-25T21:00:00.000Z", + status: "pending", + createdAt: "2026-11-25T20:00:00.000Z", +}; + +function makeClient() { + return { + createSchedule: mocks.createSchedule, + listSchedules: mocks.listSchedules, + cancelSchedule: mocks.cancelSchedule, + close: mocks.close, + }; +} + +beforeEach(() => { + vi.clearAllMocks(); + mocks.ensure.mockResolvedValue(makeClient()); + mocks.createSchedule.mockResolvedValue(sample); + mocks.listSchedules.mockResolvedValue([sample]); + mocks.cancelSchedule.mockResolvedValue({ ...sample, status: "cancelled" }); +}); + +describe("AgentScheduleService", () => { + it("routes create, list, and cancel through DaemonClient and closes owned client", async () => { + const svc = new AgentScheduleService(); + await expect( + svc.create({ agentName: "worker-1", message: "checkin", dueAt: sample.dueAt }), + ).resolves.toEqual(sample); + await expect(svc.list({ status: "pending", limit: 10 })).resolves.toEqual([sample]); + await expect(svc.cancel("sch_1234abcd")).resolves.toMatchObject({ status: "cancelled" }); + expect(mocks.close).toHaveBeenCalledTimes(3); + }); + + it("reuses a caller-owned client without closing it", async () => { + const client = makeClient(); + const svc = new AgentScheduleService({ client: client as any }); + await svc.list(); + expect(mocks.ensure).not.toHaveBeenCalled(); + expect(mocks.close).not.toHaveBeenCalled(); + }); + + it.each([ + ["not_found", ScheduledSendNotFoundError], + ["not_cancellable", ScheduledSendNotCancellableError], + ["invalid_params", ScheduledSendInvalidParamsError], + ["storage", ScheduledSendStorageError], + ])("maps coded error %s to domain error", async (code, ErrorType) => { + mocks.cancelSchedule.mockRejectedValue( + new DaemonRpcError("domain error", code, { id: "sch_1234abcd", status: "sent" }), + ); + await expect(new AgentScheduleService().cancel("sch_1234abcd")).rejects.toBeInstanceOf( + ErrorType, + ); + expect(mocks.close).toHaveBeenCalledOnce(); + }); + + it("fails clearly when no daemon is running", async () => { + mocks.ensure.mockResolvedValue(null); + await expect(new AgentScheduleService().list()).rejects.toThrow(/daemon.*required/i); + }); + + it("requires daemon upgrade on unknown method", async () => { + mocks.listSchedules.mockRejectedValue(new DaemonRpcError("unknown method: schedule.list")); + await expect(new AgentScheduleService().list()).rejects.toThrow(/upgrade|restart/i); + expect(mocks.close).toHaveBeenCalledOnce(); + }); +}); diff --git a/packages/cli/tests/util/time.test.ts b/packages/cli/tests/util/time.test.ts index 7bf1380c..057cf18d 100644 --- a/packages/cli/tests/util/time.test.ts +++ b/packages/cli/tests/util/time.test.ts @@ -1,4 +1,9 @@ -import { formatLocalDate, parseMilliseconds } from "../../src/util/time.js"; +import { + formatLocalDate, + parseDurationMs, + parseFutureIsoTimestamp, + parseMilliseconds, +} from "../../src/util/time.js"; describe("time util", () => { describe("formatLocalDate", () => { @@ -37,4 +42,50 @@ describe("time util", () => { } }); }); + + describe("parseDurationMs", () => { + it("parses single and compound durations case-insensitively", () => { + expect(parseDurationMs("30s")).toBe(30_000); + expect(parseDurationMs("15m")).toBe(15 * 60_000); + expect(parseDurationMs("2h")).toBe(2 * 3_600_000); + expect(parseDurationMs("1d")).toBe(86_400_000); + expect(parseDurationMs(" 1H30m10s ")).toBe(3_600_000 + 30 * 60_000 + 10_000); + }); + + it("rejects bare numbers, zero, negatives, duplicate units, and >365d", () => { + for (const bad of ["30", "0s", "0m", "-5m", "1h2h", "366d", "", "soon", "1.5h"]) { + expect(() => parseDurationMs(bad)).toThrow(/Invalid --in duration/); + } + }); + }); + + describe("parseFutureIsoTimestamp", () => { + const now = Date.parse("2026-11-25T20:00:00.000Z"); + + it("normalizes valid future UTC and offset timestamps to canonical UTC ISO", () => { + expect(parseFutureIsoTimestamp("2026-11-25T21:00:00Z", now)).toBe("2026-11-25T21:00:00.000Z"); + expect(parseFutureIsoTimestamp("2026-11-25T16:30:00-05:00", now)).toBe( + "2026-11-25T21:30:00.000Z", + ); + expect(parseFutureIsoTimestamp("2026-11-25T20:05Z", now)).toBe("2026-11-25T20:05:00.000Z"); + }); + + it("rejects missing timezone, rollover dates, and past timestamps", () => { + for (const bad of [ + "2026-11-25T21:00:00", + "2026-02-30T12:00:00Z", + "2026-11-25", + "tomorrow", + "2026-11-25T21:00:00+25:00", + ]) { + expect(() => parseFutureIsoTimestamp(bad, now)).toThrow(/Invalid --at timestamp/); + } + expect(() => parseFutureIsoTimestamp("2026-11-25T20:00:00Z", now)).toThrow( + "--at timestamp must be in the future.", + ); + expect(() => parseFutureIsoTimestamp("2026-11-25T19:59:59Z", now)).toThrow( + "--at timestamp must be in the future.", + ); + }); + }); }); diff --git a/packages/daemon-client/src/client.ts b/packages/daemon-client/src/client.ts index bee401cf..92c2712d 100644 --- a/packages/daemon-client/src/client.ts +++ b/packages/daemon-client/src/client.ts @@ -4,6 +4,10 @@ import type { AgentGroup } from "./gen/AgentGroup.js"; import type { GroupNameParams } from "./gen/GroupNameParams.js"; import type { GroupMembersParams } from "./gen/GroupMembersParams.js"; import type { GroupMemberParams } from "./gen/GroupMemberParams.js"; +import type { ScheduledSend } from "./gen/ScheduledSend.js"; +import type { ScheduleCreateParams } from "./gen/ScheduleCreateParams.js"; +import type { ScheduleListParams } from "./gen/ScheduleListParams.js"; +import type { ScheduleCancelParams } from "./gen/ScheduleCancelParams.js"; import * as net from "node:net"; import * as os from "node:os"; import * as path from "node:path"; @@ -269,6 +273,18 @@ export class DaemonClient { return (await this.request("group.lookup", { name } satisfies GroupNameParams)) as AgentGroup; } + async createSchedule(params: ScheduleCreateParams): Promise { + return (await this.request("schedule.create", params)) as ScheduledSend; + } + async listSchedules(params: ScheduleListParams = {}): Promise { + return (await this.request("schedule.list", params)) as ScheduledSend[]; + } + async cancelSchedule(id: string): Promise { + return (await this.request("schedule.cancel", { + id, + } satisfies ScheduleCancelParams)) as ScheduledSend; + } + private onData(chunk: Buffer) { this.buffer += chunk.toString("utf8"); let idx: number; diff --git a/packages/daemon-client/src/gen/ScheduleCancelParams.ts b/packages/daemon-client/src/gen/ScheduleCancelParams.ts new file mode 100644 index 00000000..a7b3d701 --- /dev/null +++ b/packages/daemon-client/src/gen/ScheduleCancelParams.ts @@ -0,0 +1,6 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Params for `schedule.cancel`. + */ +export type ScheduleCancelParams = { id: string, }; diff --git a/packages/daemon-client/src/gen/ScheduleCreateParams.ts b/packages/daemon-client/src/gen/ScheduleCreateParams.ts new file mode 100644 index 00000000..24c3677a --- /dev/null +++ b/packages/daemon-client/src/gen/ScheduleCreateParams.ts @@ -0,0 +1,6 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Params for `schedule.create`. + */ +export type ScheduleCreateParams = { agentName: string, message: string, dueAt: string, createdBy?: string, }; diff --git a/packages/daemon-client/src/gen/ScheduleListParams.ts b/packages/daemon-client/src/gen/ScheduleListParams.ts new file mode 100644 index 00000000..93a1ed3b --- /dev/null +++ b/packages/daemon-client/src/gen/ScheduleListParams.ts @@ -0,0 +1,6 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Params for `schedule.list`. + */ +export type ScheduleListParams = { status?: string, agentName?: string, limit?: number, }; diff --git a/packages/daemon-client/src/gen/ScheduledSend.ts b/packages/daemon-client/src/gen/ScheduledSend.ts new file mode 100644 index 00000000..5a865666 --- /dev/null +++ b/packages/daemon-client/src/gen/ScheduledSend.ts @@ -0,0 +1,3 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ScheduledSend = { id: string, agentName: string, message: string, dueAt: string, status: string, failureReason?: string, createdBy?: string, createdAt: string, sentAt?: string, }; diff --git a/packages/daemon-client/src/index.ts b/packages/daemon-client/src/index.ts index 52f17bc4..7fe693b0 100644 --- a/packages/daemon-client/src/index.ts +++ b/packages/daemon-client/src/index.ts @@ -23,3 +23,7 @@ export type { AgentGroup } from "./gen/AgentGroup.js"; export type { GroupNameParams } from "./gen/GroupNameParams.js"; export type { GroupMembersParams } from "./gen/GroupMembersParams.js"; export type { GroupMemberParams } from "./gen/GroupMemberParams.js"; +export type { ScheduledSend } from "./gen/ScheduledSend.js"; +export type { ScheduleCreateParams } from "./gen/ScheduleCreateParams.js"; +export type { ScheduleListParams } from "./gen/ScheduleListParams.js"; +export type { ScheduleCancelParams } from "./gen/ScheduleCancelParams.js"; diff --git a/packages/daemon-client/tests/schedules.test.ts b/packages/daemon-client/tests/schedules.test.ts new file mode 100644 index 00000000..26986acc --- /dev/null +++ b/packages/daemon-client/tests/schedules.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it, vi } from "vitest"; +import { DaemonClient } from "../src/client.js"; + +describe("DaemonClient schedule methods", () => { + it("forwards schedule.create, schedule.list, and schedule.cancel with expected payloads", async () => { + const client = Object.create(DaemonClient.prototype) as DaemonClient; + const req = vi.fn().mockResolvedValue([]); + client.request = req; + + await client.createSchedule({ + agentName: "worker", + message: "hi", + dueAt: "2026-11-25T21:00:00.000Z", + createdBy: "orch", + }); + await client.listSchedules({ status: "pending", limit: 20 }); + await client.listSchedules(); + await client.cancelSchedule("sch_11223344"); + + expect(req.mock.calls).toEqual([ + [ + "schedule.create", + { + agentName: "worker", + message: "hi", + dueAt: "2026-11-25T21:00:00.000Z", + createdBy: "orch", + }, + ], + ["schedule.list", { status: "pending", limit: 20 }], + ["schedule.list", {}], + ["schedule.cancel", { id: "sch_11223344" }], + ]); + }); +}); diff --git a/rust/crates/devkit-core/src/proto.rs b/rust/crates/devkit-core/src/proto.rs index ae7be3cd..17ec92d4 100644 --- a/rust/crates/devkit-core/src/proto.rs +++ b/rust/crates/devkit-core/src/proto.rs @@ -223,6 +223,10 @@ mod tests { GroupNameParams::export(&cfg).unwrap(); GroupMembersParams::export(&cfg).unwrap(); GroupMemberParams::export(&cfg).unwrap(); + crate::store::ScheduledSend::export(&cfg).unwrap(); + ScheduleCreateParams::export(&cfg).unwrap(); + ScheduleListParams::export(&cfg).unwrap(); + ScheduleCancelParams::export(&cfg).unwrap(); AgentStartParams::export(&cfg).unwrap(); AgentStartResult::export(&cfg).unwrap(); AgentNameParams::export(&cfg).unwrap(); @@ -425,3 +429,36 @@ pub struct GroupMemberParams { pub name: String, pub member: String, } + +/// Params for `schedule.create`. +#[derive(Debug, Deserialize, TS)] +#[serde(rename_all = "camelCase")] +pub struct ScheduleCreateParams { + pub agent_name: String, + pub message: String, + pub due_at: String, + #[serde(default)] + #[ts(optional)] + pub created_by: Option, +} + +/// Params for `schedule.list`. +#[derive(Debug, Default, Deserialize, TS)] +#[serde(rename_all = "camelCase")] +pub struct ScheduleListParams { + #[serde(default)] + #[ts(optional)] + pub status: Option, + #[serde(default)] + #[ts(optional)] + pub agent_name: Option, + #[serde(default)] + #[ts(optional, type = "number")] + pub limit: Option, +} + +/// Params for `schedule.cancel`. +#[derive(Debug, Deserialize, TS)] +pub struct ScheduleCancelParams { + pub id: String, +} diff --git a/rust/crates/devkit-core/src/store.rs b/rust/crates/devkit-core/src/store.rs index 675aaa85..ccf59cac 100644 --- a/rust/crates/devkit-core/src/store.rs +++ b/rust/crates/devkit-core/src/store.rs @@ -15,8 +15,14 @@ mod groups; /// Daemon-owned store: the persisted agent snapshot (for diff/events across /// restarts) and the durable event log. The daemon is the sole writer. mod registry; +mod schedules; pub use groups::{AgentGroup, GroupError}; pub use registry::Registration; +pub use schedules::{ + parse_iso8601_utc_ms, ScheduleError, ScheduleFilter, ScheduledSend, + DEFAULT_SCHEDULE_LIST_LIMIT, MAX_SCHEDULE_AGENT_NAME_CHARS, MAX_SCHEDULE_LIST_LIMIT, + MAX_SCHEDULE_MESSAGE_BYTES, +}; pub struct Store { conn: Mutex, @@ -97,6 +103,7 @@ impl Store { } durable::init(&conn)?; Self::init_groups(&conn)?; + Self::init_schedules(&conn)?; Ok(Self { conn: Mutex::new(conn), legacy_db: Mutex::new(None), diff --git a/rust/crates/devkit-core/src/store/schedules.rs b/rust/crates/devkit-core/src/store/schedules.rs new file mode 100644 index 00000000..8b3a9854 --- /dev/null +++ b/rust/crates/devkit-core/src/store/schedules.rs @@ -0,0 +1,527 @@ +//! Daemon-owned one-shot scheduled sends. Persisted in `daemon.db`, delivered +//! by devkitd's scheduler task with fire-time target resolution. +use super::{chrono_now, iso8601_utc, Store}; +use rusqlite::{params, Connection, OptionalExtension}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::io::Read; +use ts_rs::TS; + +/// Hard cap on scheduled message payload (bytes). Safely under Linux's 128 KiB +/// single-argv `MAX_ARG_STRLEN` (for `herdr agent prompt`) and PTY paste buffers. +pub const MAX_SCHEDULE_MESSAGE_BYTES: usize = 64 * 1024; +pub const MAX_SCHEDULE_AGENT_NAME_CHARS: usize = 128; +pub const DEFAULT_SCHEDULE_LIST_LIMIT: u32 = 50; +pub const MAX_SCHEDULE_LIST_LIMIT: u32 = 500; +const TERMINAL_RETENTION_MAX: i64 = 1000; +const TERMINAL_RETENTION_AGE_MS: i64 = 30 * 24 * 60 * 60 * 1000; + +const VALID_STATUSES: &[&str] = &["pending", "sent", "late", "cancelled", "failed", "skipped"]; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +#[serde(rename_all = "camelCase")] +pub struct ScheduledSend { + pub id: String, + pub agent_name: String, + pub message: String, + pub due_at: String, + pub status: String, + #[serde(skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub failure_reason: Option, + #[serde(skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub created_by: Option, + pub created_at: String, + #[serde(skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub sent_at: Option, +} + +#[derive(Debug, Default, Clone)] +pub struct ScheduleFilter { + pub status: Option, + pub agent_name: Option, + pub limit: Option, +} + +#[derive(Debug)] +pub struct ScheduleError { + pub code: &'static str, + pub message: String, + pub details: Value, +} + +impl std::fmt::Display for ScheduleError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for ScheduleError {} + +impl From for ScheduleError { + fn from(err: rusqlite::Error) -> Self { + schedule_error("storage", err.to_string(), json!({})) + } +} + +fn schedule_error(code: &'static str, message: impl Into, details: Value) -> ScheduleError { + ScheduleError { + code, + message: message.into(), + details, + } +} + +fn invalid_params(message: impl Into) -> ScheduleError { + schedule_error("invalid_params", message, json!({})) +} + +/// Strict RFC3339 / ISO-8601 timestamp with explicit timezone (`Z` or `±HH:MM`) +/// parsed into UTC epoch milliseconds without pulling in `chrono`. +pub fn parse_iso8601_utc_ms(input: &str) -> Result { + let s = input.trim(); + let err = || { + invalid_params(format!( + "Invalid timestamp \"{input}\". Expected ISO-8601 with timezone (e.g. 2026-11-25T21:00:00Z)." + )) + }; + + let (date_part, rest) = s.split_once(['T', 't']).ok_or_else(err)?; + let mut date_parts = date_part.split('-'); + let year: i32 = date_parts + .next() + .filter(|p| p.len() == 4 && p.bytes().all(|b| b.is_ascii_digit())) + .ok_or_else(err)? + .parse() + .map_err(|_| err())?; + let month: u32 = date_parts + .next() + .filter(|p| p.len() == 2 && p.bytes().all(|b| b.is_ascii_digit())) + .ok_or_else(err)? + .parse() + .map_err(|_| err())?; + let day: u32 = date_parts + .next() + .filter(|p| p.len() == 2 && p.bytes().all(|b| b.is_ascii_digit())) + .ok_or_else(err)? + .parse() + .map_err(|_| err())?; + if date_parts.next().is_some() { + return Err(err()); + } + if !(1970..=9999).contains(&year) || !(1..=12).contains(&month) { + return Err(err()); + } + if day < 1 || day > days_in_month(year, month) { + return Err(err()); + } + + // Split timezone suffix (`Z`/`z` or `±HH:MM`) from time portion. + let (time_part, offset_secs): (&str, i64) = if let Some(t) = rest.strip_suffix(['Z', 'z']) { + (t, 0) + } else { + let tz_pos = rest.rfind(['+', '-']).ok_or_else(err)?; + let (t, tz) = rest.split_at(tz_pos); + let sign: i64 = if tz.starts_with('+') { 1 } else { -1 }; + let tz_body = &tz[1..]; + let (tz_h_s, tz_m_s) = tz_body.split_once(':').ok_or_else(err)?; + if tz_h_s.len() != 2 + || tz_m_s.len() != 2 + || !tz_h_s.bytes().all(|b| b.is_ascii_digit()) + || !tz_m_s.bytes().all(|b| b.is_ascii_digit()) + { + return Err(err()); + } + let tz_h: i64 = tz_h_s.parse().map_err(|_| err())?; + let tz_m: i64 = tz_m_s.parse().map_err(|_| err())?; + if tz_h > 23 || tz_m > 59 { + return Err(err()); + } + (t, sign * (tz_h * 3600 + tz_m * 60)) + }; + + // Split optional fractional seconds. + let (hms, ms): (&str, i64) = match time_part.split_once('.') { + Some((hms, frac)) => { + if frac.is_empty() || frac.len() > 9 || !frac.bytes().all(|b| b.is_ascii_digit()) { + return Err(err()); + } + let mut digits = [b'0'; 3]; + for (i, b) in frac.bytes().take(3).enumerate() { + digits[i] = b; + } + let ms_str = std::str::from_utf8(&digits).map_err(|_| err())?; + (hms, ms_str.parse::().map_err(|_| err())?) + } + None => (time_part, 0), + }; + + let mut t_parts = hms.split(':'); + let hour: u32 = t_parts + .next() + .filter(|p| p.len() == 2 && p.bytes().all(|b| b.is_ascii_digit())) + .ok_or_else(err)? + .parse() + .map_err(|_| err())?; + let minute: u32 = t_parts + .next() + .filter(|p| p.len() == 2 && p.bytes().all(|b| b.is_ascii_digit())) + .ok_or_else(err)? + .parse() + .map_err(|_| err())?; + let second: u32 = match t_parts.next() { + Some(sec_s) => { + if sec_s.len() != 2 || !sec_s.bytes().all(|b| b.is_ascii_digit()) { + return Err(err()); + } + sec_s.parse().map_err(|_| err())? + } + None => 0, + }; + if t_parts.next().is_some() || hour > 23 || minute > 59 || second > 59 { + return Err(err()); + } + + let days = days_from_civil(year, month, day); + let local_secs = days * 86_400 + (hour as i64) * 3600 + (minute as i64) * 60 + (second as i64); + let utc_secs = local_secs - offset_secs; + let total_ms = utc_secs + .checked_mul(1000) + .and_then(|v| v.checked_add(ms)) + .ok_or_else(err)?; + if total_ms < 0 { + return Err(err()); + } + Ok(total_ms) +} + +fn is_leap_year(year: i32) -> bool { + (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) +} + +fn days_in_month(year: i32, month: u32) -> u32 { + match month { + 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, + 4 | 6 | 9 | 11 => 30, + 2 => { + if is_leap_year(year) { + 29 + } else { + 28 + } + } + _ => 0, + } +} + +fn days_from_civil(y: i32, m: u32, d: u32) -> i64 { + let y = if m <= 2 { y - 1 } else { y } as i64; + let era = if y >= 0 { y } else { y - 399 } / 400; + let yoe = y - era * 400; + let mp = ((m as i64) + 9) % 12; + let doy = (153 * mp + 2) / 5 + (d as i64) - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +fn generate_schedule_id() -> Result { + let mut b = [0u8; 4]; + std::fs::File::open("/dev/urandom") + .and_then(|mut f| f.read_exact(&mut b)) + .map_err(|e| schedule_error("storage", format!("failed to generate id: {e}"), json!({})))?; + Ok(format!( + "sch_{:02x}{:02x}{:02x}{:02x}", + b[0], b[1], b[2], b[3] + )) +} + +fn row_to_schedule(r: &rusqlite::Row<'_>) -> rusqlite::Result { + Ok(ScheduledSend { + id: r.get(0)?, + agent_name: r.get(1)?, + message: r.get(2)?, + due_at: r.get(3)?, + status: r.get(4)?, + failure_reason: r.get(5)?, + created_by: r.get(6)?, + created_at: r.get(7)?, + sent_at: r.get(8)?, + }) +} + +fn fetch_schedule(conn: &Connection, id: &str) -> Result, ScheduleError> { + conn.query_row( + "SELECT id, agent_name, message, due_at, status, failure_reason, created_by, created_at, sent_at + FROM scheduled_sends WHERE id = ?1", + [id], + row_to_schedule, + ) + .optional() + .map_err(Into::into) +} + +fn prune_terminal_in_conn( + conn: &Connection, + keep_max: i64, + now_ms: i64, +) -> rusqlite::Result { + let cutoff = iso8601_utc(now_ms.saturating_sub(TERMINAL_RETENTION_AGE_MS)); + let mut deleted = conn.execute( + "DELETE FROM scheduled_sends WHERE status != 'pending' AND created_at < ?1", + [cutoff], + )?; + deleted += conn.execute( + "DELETE FROM scheduled_sends + WHERE status != 'pending' + AND id NOT IN ( + SELECT id FROM scheduled_sends + WHERE status != 'pending' + ORDER BY created_at DESC, due_at DESC, id DESC + LIMIT ?1 + )", + [keep_max.max(0)], + )?; + Ok(deleted) +} + +impl Store { + pub(super) fn init_schedules(conn: &Connection) -> rusqlite::Result<()> { + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS scheduled_sends ( + id TEXT PRIMARY KEY, + agent_name TEXT NOT NULL, + message TEXT NOT NULL, + due_at TEXT NOT NULL, + status TEXT NOT NULL CHECK(status IN ('pending','sent','late','cancelled','failed','skipped')), + failure_reason TEXT, + created_by TEXT, + created_at TEXT NOT NULL, + sent_at TEXT + ); + CREATE INDEX IF NOT EXISTS idx_scheduled_sends_pending_due + ON scheduled_sends(due_at, id) WHERE status = 'pending'; + CREATE INDEX IF NOT EXISTS idx_scheduled_sends_due + ON scheduled_sends(due_at DESC, id DESC);", + ) + } + + pub fn create_schedule( + &self, + agent_name: &str, + message: &str, + due_at: &str, + created_by: Option<&str>, + ) -> Result { + self.create_schedule_at(agent_name, message, due_at, created_by, chrono_now()) + } + + pub fn create_schedule_at( + &self, + agent_name: &str, + message: &str, + due_at: &str, + created_by: Option<&str>, + now_ms: i64, + ) -> Result { + let agent_name = agent_name.trim(); + if agent_name.is_empty() || agent_name.chars().count() > MAX_SCHEDULE_AGENT_NAME_CHARS { + return Err(invalid_params(format!( + "Invalid agentName: must be 1–{MAX_SCHEDULE_AGENT_NAME_CHARS} non-blank characters." + ))); + } + if message.trim().is_empty() { + return Err(invalid_params("Message cannot be blank.")); + } + if message.len() > MAX_SCHEDULE_MESSAGE_BYTES { + return Err(invalid_params(format!( + "Message exceeds maximum size of {MAX_SCHEDULE_MESSAGE_BYTES} bytes." + ))); + } + let due_ms = parse_iso8601_utc_ms(due_at)?; + if due_ms <= now_ms { + return Err(invalid_params("dueAt must be in the future.")); + } + let due_iso = iso8601_utc(due_ms); + let created_iso = iso8601_utc(now_ms); + let created_by = created_by + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + + let conn = self.conn.lock().unwrap(); + let mut id = String::new(); + for _ in 0..5 { + let candidate = generate_schedule_id()?; + let inserted = conn.execute( + "INSERT OR IGNORE INTO scheduled_sends + (id, agent_name, message, due_at, status, failure_reason, created_by, created_at, sent_at) + VALUES (?1, ?2, ?3, ?4, 'pending', NULL, ?5, ?6, NULL)", + params![candidate, agent_name, message, due_iso, created_by, created_iso], + )?; + if inserted == 1 { + id = candidate; + break; + } + } + if id.is_empty() { + return Err(schedule_error( + "storage", + "Failed to allocate unique schedule id.", + json!({}), + )); + } + let _ = prune_terminal_in_conn(&conn, TERMINAL_RETENTION_MAX, now_ms); + Ok(ScheduledSend { + id, + agent_name: agent_name.to_owned(), + message: message.to_owned(), + due_at: due_iso, + status: "pending".into(), + failure_reason: None, + created_by, + created_at: created_iso, + sent_at: None, + }) + } + + pub fn get_schedule(&self, id: &str) -> Result, ScheduleError> { + let conn = self.conn.lock().unwrap(); + fetch_schedule(&conn, id.trim()) + } + + pub fn list_schedules( + &self, + filter: &ScheduleFilter, + ) -> Result, ScheduleError> { + if let Some(status) = filter.status.as_deref() { + if !VALID_STATUSES.contains(&status) { + return Err(invalid_params(format!( + "Invalid status \"{status}\". Allowed: {}.", + VALID_STATUSES.join(", ") + ))); + } + } + let limit = filter + .limit + .unwrap_or(DEFAULT_SCHEDULE_LIST_LIMIT) + .clamp(1, MAX_SCHEDULE_LIST_LIMIT) as i64; + let agent_name = filter + .agent_name + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()); + + let conn = self.conn.lock().unwrap(); + let mut stmt = conn.prepare( + "SELECT id, agent_name, message, due_at, status, failure_reason, created_by, created_at, sent_at + FROM scheduled_sends + WHERE (?1 IS NULL OR status = ?1) + AND (?2 IS NULL OR agent_name = ?2) + ORDER BY + CASE WHEN status = 'pending' THEN 0 ELSE 1 END ASC, + CASE WHEN status = 'pending' THEN due_at END ASC, + due_at DESC, + id ASC + LIMIT ?3", + )?; + let rows = stmt + .query_map(params![filter.status, agent_name, limit], row_to_schedule)? + .collect::>>()?; + Ok(rows) + } + + pub fn cancel_schedule(&self, id: &str) -> Result { + let id = id.trim(); + if id.is_empty() { + return Err(invalid_params("Schedule id cannot be blank.")); + } + let conn = self.conn.lock().unwrap(); + let updated = conn.execute( + "UPDATE scheduled_sends SET status = 'cancelled' WHERE id = ?1 AND status = 'pending'", + [id], + )?; + let Some(row) = fetch_schedule(&conn, id)? else { + return Err(schedule_error( + "not_found", + format!("Scheduled send \"{id}\" not found."), + json!({ "id": id }), + )); + }; + if updated == 0 { + return Err(schedule_error( + "not_cancellable", + format!( + "Cannot cancel scheduled send \"{id}\": status is \"{}\".", + row.status + ), + json!({ "id": id, "status": row.status }), + )); + } + Ok(row) + } + + /// Pending sends whose `due_at <= now_ms`, deterministically ordered by + /// `(due_at ASC, id ASC)`. + pub fn due_pending_schedules(&self, now_ms: i64) -> Result, ScheduleError> { + let now_iso = iso8601_utc(now_ms); + let conn = self.conn.lock().unwrap(); + let mut stmt = conn.prepare( + "SELECT id, agent_name, message, due_at, status, failure_reason, created_by, created_at, sent_at + FROM scheduled_sends + WHERE status = 'pending' AND due_at <= ?1 + ORDER BY due_at ASC, id ASC", + )?; + let rows = stmt + .query_map([now_iso], row_to_schedule)? + .collect::>>()?; + Ok(rows) + } + + pub fn mark_schedule_delivered( + &self, + id: &str, + sent_at_ms: i64, + late: bool, + ) -> Result { + let status = if late { "late" } else { "sent" }; + let sent_iso = iso8601_utc(sent_at_ms); + let conn = self.conn.lock().unwrap(); + let n = conn.execute( + "UPDATE scheduled_sends SET status = ?2, sent_at = ?3, failure_reason = NULL + WHERE id = ?1 AND status = 'pending'", + params![id, status, sent_iso], + )?; + Ok(n == 1) + } + + pub fn mark_schedule_failed(&self, id: &str, reason: &str) -> Result { + let conn = self.conn.lock().unwrap(); + let n = conn.execute( + "UPDATE scheduled_sends SET status = 'failed', failure_reason = ?2, sent_at = NULL + WHERE id = ?1 AND status = 'pending'", + params![id, reason], + )?; + Ok(n == 1) + } + + pub fn mark_schedule_skipped(&self, id: &str, reason: &str) -> Result { + let conn = self.conn.lock().unwrap(); + let n = conn.execute( + "UPDATE scheduled_sends SET status = 'skipped', failure_reason = ?2, sent_at = NULL + WHERE id = ?1 AND status = 'pending'", + params![id, reason], + )?; + Ok(n == 1) + } + + pub fn prune_terminal_schedules( + &self, + keep_max: i64, + now_ms: i64, + ) -> Result { + let conn = self.conn.lock().unwrap(); + Ok(prune_terminal_in_conn(&conn, keep_max, now_ms)?) + } +} diff --git a/rust/crates/devkit-core/tests/schedules.rs b/rust/crates/devkit-core/tests/schedules.rs new file mode 100644 index 00000000..01cc0ba5 --- /dev/null +++ b/rust/crates/devkit-core/tests/schedules.rs @@ -0,0 +1,268 @@ +use devkit_core::store::{ + iso8601_utc, parse_iso8601_utc_ms, ScheduleFilter, Store, MAX_SCHEDULE_MESSAGE_BYTES, +}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +struct Fixture(PathBuf); +impl Fixture { + fn new() -> Self { + static N: AtomicU64 = AtomicU64::new(0); + let p = std::env::temp_dir().join(format!( + "schedule-store-{}-{}", + std::process::id(), + N.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&p).unwrap(); + Self(p) + } + fn store(&self) -> Store { + Store::open(&self.0.join("daemon.db")).unwrap() + } +} +impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[test] +fn iso8601_parser_handles_utc_offsets_fractions_and_rejects_invalid() { + let base = parse_iso8601_utc_ms("2026-11-25T20:00:00Z").unwrap(); + assert_eq!(iso8601_utc(base), "2026-11-25T20:00:00.000Z"); + + assert_eq!( + parse_iso8601_utc_ms("2026-11-25T20:00:00.250Z").unwrap(), + base + 250 + ); + assert_eq!( + parse_iso8601_utc_ms("2026-11-25T20:00:00.5Z").unwrap(), + base + 500 + ); + // -05:00 -> +5h in UTC + assert_eq!( + parse_iso8601_utc_ms("2026-11-25T15:00:00-05:00").unwrap(), + base + ); + // +02:30 -> -2h30m in UTC + assert_eq!( + parse_iso8601_utc_ms("2026-11-25T22:30:00+02:30").unwrap(), + base + ); + // Leap year Feb 29 valid, non-leap invalid + assert!(parse_iso8601_utc_ms("2024-02-29T12:00:00Z").is_ok()); + assert!(parse_iso8601_utc_ms("2026-02-29T12:00:00Z").is_err()); + assert!(parse_iso8601_utc_ms("2026-02-30T12:00:00Z").is_err()); + // Missing timezone rejected + assert!(parse_iso8601_utc_ms("2026-11-25T20:00:00").is_err()); + assert!(parse_iso8601_utc_ms("not-a-date").is_err()); +} + +#[test] +fn create_list_cancel_and_restart_persistence() { + let f = Fixture::new(); + let s = f.store(); + let now_ms = parse_iso8601_utc_ms("2026-11-25T20:00:00Z").unwrap(); + + let created = s + .create_schedule_at( + " worker-1 ", + "check status", + "2026-11-25T20:15:00+00:00", + Some("orchestrator"), + now_ms, + ) + .unwrap(); + assert!(created.id.starts_with("sch_")); + assert_eq!(created.id.len(), 12); + assert_eq!(created.agent_name, "worker-1"); + assert_eq!(created.message, "check status"); + assert_eq!(created.due_at, "2026-11-25T20:15:00.000Z"); + assert_eq!(created.status, "pending"); + assert_eq!(created.created_by.as_deref(), Some("orchestrator")); + assert_eq!(created.sent_at, None); + assert_eq!(created.failure_reason, None); + + drop(s); + let s2 = f.store(); + let listed = s2.list_schedules(&ScheduleFilter::default()).unwrap(); + assert_eq!(listed, vec![created.clone()]); + + let cancelled = s2.cancel_schedule(&created.id).unwrap(); + assert_eq!(cancelled.status, "cancelled"); + assert_eq!(cancelled.id, created.id); + + // Re-cancelling terminal row returns not_cancellable with current status + let err = s2.cancel_schedule(&created.id).unwrap_err(); + assert_eq!(err.code, "not_cancellable"); + assert_eq!(err.details["status"], "cancelled"); + + // Unknown ID returns not_found + let err = s2.cancel_schedule("sch_00000000").unwrap_err(); + assert_eq!(err.code, "not_found"); +} + +#[test] +fn create_validation_enforces_limits_and_future_due_at() { + let f = Fixture::new(); + let s = f.store(); + let now_ms = parse_iso8601_utc_ms("2026-11-25T20:00:00Z").unwrap(); + let future = "2026-11-25T20:05:00Z"; + + assert_eq!( + s.create_schedule_at(" ", "hi", future, None, now_ms) + .unwrap_err() + .code, + "invalid_params" + ); + assert_eq!( + s.create_schedule_at(&"a".repeat(129), "hi", future, None, now_ms) + .unwrap_err() + .code, + "invalid_params" + ); + assert_eq!( + s.create_schedule_at("agent-1", " \n ", future, None, now_ms) + .unwrap_err() + .code, + "invalid_params" + ); + let too_big = "x".repeat(MAX_SCHEDULE_MESSAGE_BYTES + 1); + assert_eq!( + s.create_schedule_at("agent-1", &too_big, future, None, now_ms) + .unwrap_err() + .code, + "invalid_params" + ); + let exact_max = "x".repeat(MAX_SCHEDULE_MESSAGE_BYTES); + assert!(s + .create_schedule_at("agent-1", &exact_max, future, None, now_ms) + .is_ok()); + + // Past due_at rejected + assert_eq!( + s.create_schedule_at("agent-1", "hi", "2026-11-25T19:59:59Z", None, now_ms) + .unwrap_err() + .code, + "invalid_params" + ); + // Invalid timestamp rejected + assert_eq!( + s.create_schedule_at("agent-1", "hi", "2026-11-25T20:05:00", None, now_ms) + .unwrap_err() + .code, + "invalid_params" + ); +} + +#[test] +fn state_transitions_due_ordering_and_list_filters() { + let f = Fixture::new(); + let s = f.store(); + let t0 = parse_iso8601_utc_ms("2026-11-25T20:00:00Z").unwrap(); + + let a = s + .create_schedule_at("alpha", "m1", "2026-11-25T20:01:00Z", None, t0) + .unwrap(); + let b = s + .create_schedule_at("beta", "m2", "2026-11-25T20:01:00Z", None, t0) + .unwrap(); + let c = s + .create_schedule_at("alpha", "m3", "2026-11-25T20:05:00Z", None, t0) + .unwrap(); + let d = s + .create_schedule_at("gamma", "m4", "2026-11-25T20:10:00Z", None, t0) + .unwrap(); + + // At 20:01:00Z only a and b are due, ordered by (due_at ASC, id ASC) + let t1 = parse_iso8601_utc_ms("2026-11-25T20:01:00Z").unwrap(); + let due = s.due_pending_schedules(t1).unwrap(); + let mut expected_ids = vec![a.id.clone(), b.id.clone()]; + expected_ids.sort(); + assert_eq!( + due.iter().map(|r| r.id.clone()).collect::>(), + expected_ids + ); + + // Transition a -> sent, b -> late, c -> failed, d -> skipped + assert!(s.mark_schedule_delivered(&a.id, t1, false).unwrap()); + // Double transition is a no-op returning false + assert!(!s.mark_schedule_delivered(&a.id, t1, false).unwrap()); + assert!(s.mark_schedule_delivered(&b.id, t1 + 90_000, true).unwrap()); + assert!(s.mark_schedule_failed(&c.id, "target gone").unwrap()); + assert!(s + .mark_schedule_skipped(&d.id, "missed due time by >1h") + .unwrap()); + + assert!(s.due_pending_schedules(t1 + 999_999).unwrap().is_empty()); + + // Filter by status + let failed = s + .list_schedules(&ScheduleFilter { + status: Some("failed".into()), + agent_name: None, + limit: None, + }) + .unwrap(); + assert_eq!(failed.len(), 1); + assert_eq!(failed[0].id, c.id); + assert_eq!(failed[0].failure_reason.as_deref(), Some("target gone")); + assert_eq!(failed[0].sent_at, None); + + // Filter by agent_name + let alphas = s + .list_schedules(&ScheduleFilter { + status: None, + agent_name: Some("alpha".into()), + limit: None, + }) + .unwrap(); + assert_eq!(alphas.len(), 2); + + // Invalid status filter rejected + assert_eq!( + s.list_schedules(&ScheduleFilter { + status: Some("bogus".into()), + agent_name: None, + limit: None, + }) + .unwrap_err() + .code, + "invalid_params" + ); + + // Pending rows sort before terminal rows in list + let e = s + .create_schedule_at("alpha", "future", "2026-11-25T21:00:00Z", None, t0) + .unwrap(); + let all = s.list_schedules(&ScheduleFilter::default()).unwrap(); + assert_eq!(all[0].id, e.id); +} + +#[test] +fn retention_pruning_preserves_pending_and_caps_terminal_rows() { + let f = Fixture::new(); + let s = f.store(); + let t0 = parse_iso8601_utc_ms("2026-11-25T20:00:00Z").unwrap(); + + let pending = s + .create_schedule_at("keep", "stay", "2026-11-25T22:00:00Z", None, t0) + .unwrap(); + for i in 0..10 { + let due = iso8601_utc(t0 + (i + 1) * 1000); + let row = s.create_schedule_at("a", "m", &due, None, t0).unwrap(); + s.mark_schedule_delivered(&row.id, t0 + (i + 1) * 1000, false) + .unwrap(); + } + let deleted = s.prune_terminal_schedules(3, t0 + 100_000).unwrap(); + assert_eq!(deleted, 7); + + let remaining = s + .list_schedules(&ScheduleFilter { + limit: Some(50), + ..Default::default() + }) + .unwrap(); + assert_eq!(remaining.len(), 4); + assert_eq!(remaining[0].id, pending.id); +} diff --git a/rust/crates/devkitd/src/main.rs b/rust/crates/devkitd/src/main.rs index 16709025..b6072e39 100644 --- a/rust/crates/devkitd/src/main.rs +++ b/rust/crates/devkitd/src/main.rs @@ -1,6 +1,7 @@ mod durable; mod rpc; mod runtime; +mod scheduler; mod server; use anyhow::Result; diff --git a/rust/crates/devkitd/src/rpc.rs b/rust/crates/devkitd/src/rpc.rs index c695adb7..32fee5e3 100644 --- a/rust/crates/devkitd/src/rpc.rs +++ b/rust/crates/devkitd/src/rpc.rs @@ -3,6 +3,7 @@ pub mod agent; pub mod group; +pub mod schedule; use serde_json::Value; diff --git a/rust/crates/devkitd/src/rpc/schedule.rs b/rust/crates/devkitd/src/rpc/schedule.rs new file mode 100644 index 00000000..d1e677a5 --- /dev/null +++ b/rust/crates/devkitd/src/rpc/schedule.rs @@ -0,0 +1,65 @@ +//! Daemon-owned scheduled send operations (`schedule.create/list/cancel`). +use crate::rpc::RpcError; +use crate::server::Daemon; +use devkit_core::proto::{ScheduleCancelParams, ScheduleCreateParams, ScheduleListParams}; +use devkit_core::store::{ScheduleError, ScheduleFilter}; +use serde::de::DeserializeOwned; +use serde_json::{json, Value}; + +fn parse(params: Value) -> Result { + serde_json::from_value(params).map_err(|err| RpcError::invalid(err.to_string())) +} + +fn domain(err: ScheduleError) -> RpcError { + RpcError::new(err.code, err.message, Some(err.details)) +} + +pub fn run(daemon: &Daemon, method: &str, params: Value) -> Result { + match method { + "schedule.create" => { + let p: ScheduleCreateParams = parse(params)?; + let created = daemon + .store + .create_schedule( + &p.agent_name, + &p.message, + &p.due_at, + p.created_by.as_deref(), + ) + .map_err(domain)?; + serde_json::to_value(created).map_err(RpcError::internal) + } + "schedule.list" => { + let p: ScheduleListParams = if params.is_null() { + ScheduleListParams::default() + } else { + parse(params)? + }; + let filter = ScheduleFilter { + status: p.status, + agent_name: p.agent_name, + limit: p.limit, + }; + let items = daemon.store.list_schedules(&filter).map_err(domain)?; + serde_json::to_value(items).map_err(RpcError::internal) + } + "schedule.cancel" => { + let p: ScheduleCancelParams = parse(params)?; + let id = p.id.trim(); + if daemon.in_flight_schedules.lock().unwrap().contains(id) { + return Err(RpcError::new( + "not_cancellable", + format!("Cannot cancel scheduled send \"{id}\": currently being delivered."), + Some(json!({ "id": id, "status": "delivering" })), + )); + } + let cancelled = daemon.store.cancel_schedule(id).map_err(domain)?; + serde_json::to_value(cancelled).map_err(RpcError::internal) + } + _ => Err(RpcError::new( + "unknown_method", + format!("unknown method: {method}"), + None, + )), + } +} diff --git a/rust/crates/devkitd/src/runtime.rs b/rust/crates/devkitd/src/runtime.rs index 3436adf7..9f4304d6 100644 --- a/rust/crates/devkitd/src/runtime.rs +++ b/rust/crates/devkitd/src/runtime.rs @@ -113,6 +113,64 @@ pub(crate) fn spawn_output( } } +/// Spawn a command with optional stdin bytes and a hard timeout; SIGKILLs the +/// child on timeout so a wedged tmux/herdr/CLI call cannot wedge the scheduler. +pub(crate) fn spawn_output_with_timeout( + cmd: &mut std::process::Command, + stdin_bytes: Option<&[u8]>, + timeout: std::time::Duration, +) -> std::io::Result { + use std::io::Write; + use std::process::Stdio; + + cmd.stdin(if stdin_bytes.is_some() { + Stdio::piped() + } else { + Stdio::null() + }) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + + const ETXTBSY: i32 = 26; + let mut attempts = 0; + let mut child = loop { + match cmd.spawn() { + Err(e) if e.raw_os_error() == Some(ETXTBSY) && attempts < 3 => { + attempts += 1; + std::thread::sleep(std::time::Duration::from_millis(20)); + } + other => break other?, + } + }; + + if let Some(bytes) = stdin_bytes { + if let Some(mut stdin) = child.stdin.take() { + let owned = bytes.to_vec(); + std::thread::spawn(move || { + let _ = stdin.write_all(&owned); + }); + } + } + + let pid = child.id(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send(child.wait_with_output()); + }); + match rx.recv_timeout(timeout) { + Ok(res) => res, + Err(_) => { + unsafe { + libc::kill(pid as i32, libc::SIGKILL); + } + Err(std::io::Error::new( + std::io::ErrorKind::TimedOut, + format!("command timed out after {}s", timeout.as_secs()), + )) + } + } +} + /// Runtimes bundle — injectable so tests can pass fixture-backed impls. #[derive(Default)] pub struct Runtimes { diff --git a/rust/crates/devkitd/src/runtime/herdr.rs b/rust/crates/devkitd/src/runtime/herdr.rs index 255c8876..6d6eb8ea 100644 --- a/rust/crates/devkitd/src/runtime/herdr.rs +++ b/rust/crates/devkitd/src/runtime/herdr.rs @@ -45,6 +45,36 @@ impl HerdrRuntime { } } + /// `agent prompt ` — delivers a scheduled message directly + /// to a herdr-managed pane with a bounded timeout. + pub fn send_prompt(&self, pane_id: &str, message: &str) -> Result<(), String> { + let o = crate::runtime::spawn_output_with_timeout( + Command::new(&self.herdr).args(["agent", "prompt", pane_id, message]), + None, + Duration::from_secs(10), + ) + .map_err(|e| e.to_string())?; + let stdout: Option = serde_json::from_slice(&o.stdout).ok(); + if let Some(err) = stdout.as_ref().and_then(|v| v.get("error")) { + return Err(format!( + "{}: {}", + err["code"].as_str().unwrap_or("error"), + err["message"] + .as_str() + .unwrap_or("herdr agent prompt failed.") + )); + } + if !o.status.success() { + let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string(); + return Err(if stderr.is_empty() { + format!("herdr agent prompt exited with {}", o.status) + } else { + stderr + }); + } + Ok(()) + } + /// `agent rename ` — target is the pane id hosting the /// agent. herdr reports failures as `{"error":{code,message}}` on stdout /// with a non-zero exit, so stdout is checked before the status. @@ -375,4 +405,17 @@ mod tests { let out = f.herdr().start(&input("agent-a", &[])).unwrap(); assert_eq!(out.pid, 4321); } + + #[test] + fn send_prompt_invokes_agent_prompt_and_surfaces_error_json() { + let f = FixtureDir::new("herdr-prompt"); + let h = f.herdr(); + h.send_prompt("w1:p1", "check status").unwrap(); + assert!(f + .log("herdr-calls.log") + .contains("agent prompt w1:p1 check status")); + f.set("prompt-fail", ""); + let err = h.send_prompt("w1:p1", "check status").unwrap_err(); + assert!(err.contains("pane_not_found"), "{err}"); + } } diff --git a/rust/crates/devkitd/src/runtime/testkit.rs b/rust/crates/devkitd/src/runtime/testkit.rs index 9e799e89..3a133155 100644 --- a/rust/crates/devkitd/src/runtime/testkit.rs +++ b/rust/crates/devkitd/src/runtime/testkit.rs @@ -80,6 +80,12 @@ case "$1" in case "$1" in -s) touch "$DIR/session-$2"; shift 2;; *) shift;; esac done;; send-keys) :;; + load-buffer) + cat > "$DIR/tmux-stdin.log";; + paste-buffer) + [ -f "$DIR/paste-fail" ] && { echo "paste failed" >&2; exit 1; } + ;; + delete-buffer) :;; list-panes) cat "$DIR/pane_pid" 2>/dev/null;; kill-session) rm -f "$DIR/session-${3#=}";; rename-session) @@ -124,6 +130,11 @@ case "$1 $2" in echo '{"error":{"code":"agent_name_taken","message":"name taken"}}'; exit 1 fi echo '{"result":{}}';; + "agent prompt") + if [ -f "$DIR/prompt-fail" ]; then + echo '{"error":{"code":"pane_not_found","message":"pane gone"}}'; exit 1 + fi + echo '{"result":{}}';; esac exit 0 "#; diff --git a/rust/crates/devkitd/src/runtime/tmux.rs b/rust/crates/devkitd/src/runtime/tmux.rs index e24d311d..738879ce 100644 --- a/rust/crates/devkitd/src/runtime/tmux.rs +++ b/rust/crates/devkitd/src/runtime/tmux.rs @@ -12,6 +12,8 @@ use std::time::{Duration, Instant}; /// Same-pid observations required before a pid is trusted — mirrors /// `REQUIRED_STABLE_PID_POLLS`. const REQUIRED_STABLE_POLLS: u32 = 5; +const TMUX_DELIVERY_TIMEOUT: Duration = Duration::from_secs(10); +const TMUX_PASTE_ENTER_DELAY: Duration = Duration::from_millis(150); /// Binary paths are injectable so tests can point at fixture scripts instead /// of real tmux/pgrep/ps. @@ -53,6 +55,98 @@ impl TmuxRuntime { }) } + fn run_with_timeout( + &self, + args: &[&str], + stdin_bytes: Option<&[u8]>, + ) -> Result { + crate::runtime::spawn_output_with_timeout( + Command::new(&self.tmux).args(args), + stdin_bytes, + TMUX_DELIVERY_TIMEOUT, + ) + .map_err(|e| e.to_string()) + .and_then(|o| { + if o.status.success() { + Ok(String::from_utf8_lossy(&o.stdout).trim().to_string()) + } else { + let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string(); + Err(if stderr.is_empty() { + format!("tmux exited with {}", o.status) + } else { + stderr + }) + } + }) + } + + /// Resolve the exact tmux pane (`%N`) hosting `pid` by matching its TTY + /// against `tmux list-panes -a`. Keeps PR #482 independent of PR #481's + /// wire types; can unify with `terminal_target` once both land. + pub fn pane_for_pid(&self, pid: i64) -> Option<(String, String)> { + let output = crate::runtime::spawn_output_with_timeout( + Command::new(&self.ps).args(["-p", &pid.to_string(), "-o", "tty="]), + None, + TMUX_DELIVERY_TIMEOUT, + ) + .ok()?; + let raw_tty = String::from_utf8_lossy(&output.stdout); + let tty = raw_tty.trim(); + if !output.status.success() || tty.is_empty() || tty.starts_with('?') { + return None; + } + let full_tty = if tty.starts_with("/dev/") { + tty.to_owned() + } else { + format!("/dev/{tty}") + }; + let panes = self + .run_with_timeout(&["list-panes", "-a", "-F", "#{pane_tty}|#{pane_id}"], None) + .ok()?; + panes + .lines() + .filter_map(|line| line.split_once('|')) + .find_map(|(pane_tty, id)| { + (pane_tty == full_tty && id.starts_with('%')) + .then(|| (id.to_owned(), full_tty.clone())) + }) + } + + /// Deliver `message` to an exact tmux pane using bracketed paste via stdin + /// (`load-buffer` + `paste-buffer -p -d`), matching TS `tmuxBackend.send`. + pub fn send_to_pane(&self, pane_id: &str, message: &str) -> Result<(), String> { + self.send_to_pane_with_delay(pane_id, message, TMUX_PASTE_ENTER_DELAY) + } + + pub(crate) fn send_to_pane_with_delay( + &self, + pane_id: &str, + message: &str, + delay: Duration, + ) -> Result<(), String> { + static BUF_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let buf = format!( + "ai-devkit-sched-{}-{}", + std::process::id(), + BUF_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + ); + self.run_with_timeout(&["load-buffer", "-b", &buf, "-"], Some(message.as_bytes())) + .map_err(|e| format!("tmux load-buffer failed: {e}"))?; + if let Err(e) = self.run_with_timeout( + &["paste-buffer", "-t", pane_id, "-b", &buf, "-p", "-d"], + None, + ) { + let _ = self.run_with_timeout(&["delete-buffer", "-b", &buf], None); + return Err(format!("tmux paste-buffer failed: {e}")); + } + if !delay.is_zero() { + std::thread::sleep(delay); + } + self.run_with_timeout(&["send-keys", "-t", pane_id, "Enter"], None) + .map_err(|e| format!("tmux send-keys Enter failed: {e}"))?; + Ok(()) + } + pub fn session_exists(&self, name: &str) -> bool { self.run(&["has-session", "-t", name]).is_ok() } @@ -302,4 +396,39 @@ mod tests { let out = f.tmux().start(&input("deep", &matcher, 5000)).unwrap(); assert_eq!(out.pid, 9003); } + + #[test] + fn pane_for_pid_matches_exact_tty_not_first_pane() { + let f = FixtureDir::new("pane-for-pid"); + f.set("cmd-12", "pts/20"); + f.set("pane_pid", "/dev/pts/2|%1\n/dev/pts/20|%3"); + let (pane, tty) = f.tmux().pane_for_pid(12).expect("matching tmux pane"); + assert_eq!(pane, "%3"); + assert_eq!(tty, "/dev/pts/20"); + assert!(f.tmux().pane_for_pid(13).is_none()); + } + + #[test] + fn send_to_pane_uses_load_buffer_bracketed_paste_and_cleans_up_on_error() { + let f = FixtureDir::new("send-pane"); + let t = f.tmux(); + t.send_to_pane_with_delay("%3", "hello\n-world", Duration::ZERO) + .unwrap(); + let calls = f.log("tmux-calls.log"); + assert!(calls.contains("load-buffer -b ai-devkit-sched-")); + assert!(calls.contains("paste-buffer -t %3 -b ai-devkit-sched-")); + assert!(calls.contains(" -p -d")); + assert!(calls.contains("send-keys -t %3 Enter")); + assert_eq!(f.log("tmux-stdin.log"), "hello\n-world"); + + // On paste failure, delete-buffer is invoked for cleanup + f.set("paste-fail", ""); + let err = t + .send_to_pane_with_delay("%3", "fail-msg", Duration::ZERO) + .unwrap_err(); + assert!(err.contains("paste-buffer failed"), "{err}"); + assert!(f + .log("tmux-calls.log") + .contains("delete-buffer -b ai-devkit-sched-")); + } } diff --git a/rust/crates/devkitd/src/scheduler.rs b/rust/crates/devkitd/src/scheduler.rs new file mode 100644 index 00000000..d9ee92ff --- /dev/null +++ b/rust/crates/devkitd/src/scheduler.rs @@ -0,0 +1,617 @@ +//! Scheduled send delivery engine and unified tick evaluator. +//! +//! Fire-time resolution looks up `agent_name` dynamically (never pinning PIDs +//! at schedule time), dispatches to Rust-native `herdr` or exact-pane `tmux`, +//! and falls back to `ai-devkit agent send --id --stdin` only for live +//! agents running in unmanaged terminals (WezTerm, Ghostty, iTerm2, Terminal.app). + +use crate::runtime::Runtimes; +use crate::server::Daemon; +use devkit_core::discover::pid_alive; +use devkit_core::store::parse_iso8601_utc_ms; +use serde_json::Value; +use std::process::Command; +use std::time::Duration; + +/// Overdue sends older than 1 hour are marked `skipped`. +pub const LATE_WINDOW_MS: i64 = 60 * 60 * 1000; +/// Steady-state overdue sends older than 60s (e.g. host suspend/wake) are +/// marked `late` rather than `sent`. +pub const LATE_THRESHOLD_MS: i64 = 60 * 1000; +const CLI_FALLBACK_TIMEOUT: Duration = Duration::from_secs(15); + +#[derive(Debug, Clone)] +pub struct ResolvedTarget { + pub name: String, + pub pid: i64, + pub runtime: String, + pub runtime_ref: Value, +} + +pub trait ScheduleDeliverer: Send + Sync { + fn deliver(&self, target: &ResolvedTarget, message: &str) -> Result<(), String>; +} + +pub struct HybridDeliverer { + pub runtimes: Runtimes, + pub cli_bin: String, +} + +impl Default for HybridDeliverer { + fn default() -> Self { + Self { + runtimes: Runtimes::default(), + cli_bin: "ai-devkit".into(), + } + } +} + +impl HybridDeliverer { + #[cfg(test)] + pub fn with_bins(runtimes: Runtimes, cli_bin: &str) -> Self { + Self { + runtimes, + cli_bin: cli_bin.into(), + } + } + + fn deliver_via_cli_fallback(&self, name: &str, message: &str) -> Result<(), String> { + let out = crate::runtime::spawn_output_with_timeout( + Command::new(&self.cli_bin).args(["agent", "send", "--id", name, "--stdin"]), + Some(message.as_bytes()), + CLI_FALLBACK_TIMEOUT, + ); + match out { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(format!( + "Agent \"{name}\" is not in a tmux or herdr pane, and fallback CLI \"{}\" was not found in devkitd PATH.", + self.cli_bin + )), + Err(e) => Err(format!("Fallback CLI delivery failed: {e}")), + Ok(o) if o.status.success() => Ok(()), + Ok(o) => { + let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string(); + let stdout = String::from_utf8_lossy(&o.stdout).trim().to_string(); + let detail = if !stderr.is_empty() { + stderr + } else if !stdout.is_empty() { + stdout + } else { + format!("exited with {}", o.status) + }; + Err(format!("Fallback CLI delivery failed: {detail}")) + } + } + } +} + +impl ScheduleDeliverer for HybridDeliverer { + fn deliver(&self, target: &ResolvedTarget, message: &str) -> Result<(), String> { + if target.runtime == "herdr" { + let pane_id = target.runtime_ref["paneId"] + .as_str() + .filter(|s| !s.trim().is_empty()) + .ok_or_else(|| { + format!( + "Herdr agent \"{}\" is missing runtimeRef.paneId.", + target.name + ) + })?; + return self.runtimes.herdr.send_prompt(pane_id, message); + } + if let Some((pane_id, _tty)) = self.runtimes.tmux.pane_for_pid(target.pid) { + return self.runtimes.tmux.send_to_pane(&pane_id, message); + } + self.deliver_via_cli_fallback(&target.name, message) + } +} + +/// Fire-time target resolution by exact `agent_name`: +/// 1. Registered agents (re-syncing legacy `agents.db`), checking liveness. +/// 2. Unique live match in `daemon.enriched` (manually launched agents). +/// 3. Explicit error when target is a durable agent, ambiguous, dead, or missing. +pub fn resolve_fire_target(daemon: &Daemon, agent_name: &str) -> Result { + let _ = daemon.store.import_legacy_agents(); + if let Some(reg) = daemon + .store + .lookup_name(agent_name) + .map_err(|e| format!("Registry lookup failed: {e}"))? + { + if reg.gone_at.is_some() || !pid_alive(reg.pid) { + return Err(format!( + "Target agent \"{agent_name}\" is no longer running." + )); + } + return Ok(ResolvedTarget { + name: reg.name, + pid: reg.pid, + runtime: reg.runtime, + runtime_ref: serde_json::from_str(®.runtime_ref).unwrap_or(Value::Null), + }); + } + + let matches: Vec<(String, i64)> = { + let enriched = daemon.enriched.read().unwrap(); + enriched + .iter() + .filter(|a| a.name == agent_name && pid_alive(a.pid as i64)) + .map(|a| (a.name.clone(), a.pid as i64)) + .collect() + }; + match matches.len() { + 1 => { + let (name, pid) = matches.into_iter().next().unwrap(); + return Ok(ResolvedTarget { + name, + pid, + runtime: String::new(), + runtime_ref: Value::Null, + }); + } + n if n > 1 => { + return Err(format!( + "Multiple live agents ({n}) match \"{agent_name}\"." + )); + } + _ => {} + } + + if let Ok(val) = daemon.store.durable_resolve(agent_name) { + if !val.is_null() { + return Err(format!( + "Target agent \"{agent_name}\" is a durable agent; scheduled sends support direct pane delivery only." + )); + } + } + + Err(format!("Target agent \"{agent_name}\" not found.")) +} + +struct InFlightGuard<'a> { + daemon: &'a Daemon, + id: String, +} + +impl<'a> InFlightGuard<'a> { + fn acquire(daemon: &'a Daemon, id: String) -> Self { + daemon + .in_flight_schedules + .lock() + .unwrap() + .insert(id.clone()); + Self { daemon, id } + } +} + +impl Drop for InFlightGuard<'_> { + fn drop(&mut self) { + self.daemon + .in_flight_schedules + .lock() + .unwrap() + .remove(&self.id); + } +} + +fn format_overdue(age_ms: i64) -> String { + let mins = (age_ms / 60_000).max(1); + if mins < 60 { + format!("{mins}m") + } else { + let hrs = mins / 60; + let rem = mins % 60; + if rem == 0 { + format!("{hrs}h") + } else { + format!("{hrs}h{rem}m") + } + } +} + +/// Evaluate and process all pending schedules due at `now_ms` sequentially in +/// `(due_at ASC, id ASC)` order. Returns the number of due rows processed. +pub fn tick_schedules(daemon: &Daemon, now_ms: i64, deliverer: &dyn ScheduleDeliverer) -> usize { + let due = match daemon.store.due_pending_schedules(now_ms) { + Ok(rows) => rows, + Err(e) => { + tracing::warn!("due_pending_schedules query failed: {e}"); + return 0; + } + }; + + let mut processed = 0; + for item in due { + let due_ms = match parse_iso8601_utc_ms(&item.due_at) { + Ok(ms) => ms, + Err(e) => { + let _ = daemon + .store + .mark_schedule_failed(&item.id, &format!("Corrupt due_at: {e}")); + processed += 1; + continue; + } + }; + let age_ms = now_ms - due_ms; + if age_ms > LATE_WINDOW_MS { + let reason = format!( + "Skipped: missed due time by {} (>1h late window).", + format_overdue(age_ms) + ); + if let Err(e) = daemon.store.mark_schedule_skipped(&item.id, &reason) { + tracing::warn!("failed to mark schedule {} skipped: {e}", item.id); + } + processed += 1; + continue; + } + + let _guard = InFlightGuard::acquire(daemon, item.id.clone()); + // Re-check after acquiring in-flight guard in case a concurrent cancel won. + match daemon.store.get_schedule(&item.id) { + Ok(Some(row)) if row.status == "pending" => {} + _ => continue, + } + + let outcome = resolve_fire_target(daemon, &item.agent_name) + .and_then(|target| deliverer.deliver(&target, &item.message)); + + match outcome { + Ok(()) => { + let is_late = due_ms < daemon.started_at || age_ms > LATE_THRESHOLD_MS; + if let Err(e) = daemon + .store + .mark_schedule_delivered(&item.id, now_ms, is_late) + { + tracing::warn!("failed to mark schedule {} delivered: {e}", item.id); + } + } + Err(reason) => { + if let Err(e) = daemon.store.mark_schedule_failed(&item.id, &reason) { + tracing::warn!("failed to mark schedule {} failed: {e}", item.id); + } + } + } + processed += 1; + } + processed +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::runtime::testkit::FixtureDir; + use devkit_core::agent::EnrichedAgent; + use devkit_core::store::{chrono_now, iso8601_utc}; + use serde_json::json; + use std::sync::{Arc, Mutex}; + + struct MockDeliverer { + calls: Mutex>, + fail_with: Option, + } + + impl MockDeliverer { + fn ok() -> Self { + Self { + calls: Mutex::new(Vec::new()), + fail_with: None, + } + } + fn failing(msg: &str) -> Self { + Self { + calls: Mutex::new(Vec::new()), + fail_with: Some(msg.into()), + } + } + } + + impl ScheduleDeliverer for MockDeliverer { + fn deliver(&self, target: &ResolvedTarget, message: &str) -> Result<(), String> { + self.calls + .lock() + .unwrap() + .push((target.name.clone(), target.pid, message.to_owned())); + match &self.fail_with { + Some(err) => Err(err.clone()), + None => Ok(()), + } + } + } + + fn test_daemon(f: &FixtureDir) -> Arc { + let data = f.0.join("data"); + Arc::new(Daemon::new(&data, data.join("d.sock"), data.clone()).unwrap()) + } + + #[test] + fn tick_delivers_on_time_late_and_skips_past_one_hour() { + let f = FixtureDir::new("sched-states"); + let d = test_daemon(&f); + let self_pid = std::process::id() as i64; + d.store + .register_start( + self_pid, + "worker", + "claude", + "/repo", + "tmux", + &json!({"session": "worker"}), + ) + .unwrap(); + + let base = d.started_at; + // 1. Overdue > 1h before startup -> skipped + let s_skip = d + .store + .create_schedule_at( + "worker", + "too old", + &iso8601_utc(base - 4_000_000), + None, + base - 5_000_000, + ) + .unwrap(); + // 2. Overdue 5m before startup -> late + let s_late = d + .store + .create_schedule_at( + "worker", + "catchup", + &iso8601_utc(base - 300_000), + None, + base - 600_000, + ) + .unwrap(); + // 3. Due 5s after startup -> sent on time + let s_sent = d + .store + .create_schedule_at("worker", "ontime", &iso8601_utc(base + 5_000), None, base) + .unwrap(); + + let mock = MockDeliverer::ok(); + let processed = tick_schedules(&d, base + 6_000, &mock); + assert_eq!(processed, 3); + + let r_skip = d.store.get_schedule(&s_skip.id).unwrap().unwrap(); + assert_eq!(r_skip.status, "skipped"); + assert!(r_skip.failure_reason.as_deref().unwrap().contains(">1h")); + assert!(r_skip.sent_at.is_none()); + + let r_late = d.store.get_schedule(&s_late.id).unwrap().unwrap(); + assert_eq!(r_late.status, "late"); + assert!(r_late.sent_at.is_some()); + + let r_sent = d.store.get_schedule(&s_sent.id).unwrap().unwrap(); + assert_eq!(r_sent.status, "sent"); + assert!(r_sent.sent_at.is_some()); + + let calls = mock.calls.lock().unwrap(); + assert_eq!(calls.len(), 2); + assert_eq!(calls[0].2, "catchup"); + assert_eq!(calls[1].2, "ontime"); + } + + #[test] + fn tick_handles_missing_dead_ambiguous_and_durable_targets_honestly() { + let f = FixtureDir::new("sched-failures"); + let d = test_daemon(&f); + let now = chrono_now(); + let due = iso8601_utc(now + 1000); + + // Dead registered target + d.store + .register_start( + i32::MAX as i64, + "dead-agent", + "codex", + "/repo", + "tmux", + &json!({"session": "dead-agent"}), + ) + .unwrap(); + // Ambiguous unregistered targets in enriched cache + let self_pid = std::process::id() as u64; + *d.enriched.write().unwrap() = vec![ + EnrichedAgent { + name: "dup".into(), + agent_type: "claude".into(), + status: "idle".into(), + summary: String::new(), + pid: self_pid, + project_path: "/a".into(), + session_id: "s1".into(), + last_active: iso8601_utc(now), + pinned: None, + session_file_path: None, + }, + EnrichedAgent { + name: "dup".into(), + agent_type: "claude".into(), + status: "idle".into(), + summary: String::new(), + pid: self_pid, + project_path: "/b".into(), + session_id: "s2".into(), + last_active: iso8601_utc(now), + pinned: None, + session_file_path: None, + }, + ]; + // Durable agent + d.store + .durable_create("dur-1", "claude", f.0.to_str().unwrap()) + .unwrap(); + + let s_missing = d + .store + .create_schedule_at("ghost", "m", &due, None, now) + .unwrap(); + let s_dead = d + .store + .create_schedule_at("dead-agent", "m", &due, None, now) + .unwrap(); + let s_dup = d + .store + .create_schedule_at("dup", "m", &due, None, now) + .unwrap(); + let s_dur = d + .store + .create_schedule_at("dur-1", "m", &due, None, now) + .unwrap(); + + let mock = MockDeliverer::ok(); + tick_schedules(&d, now + 2000, &mock); + assert!(mock.calls.lock().unwrap().is_empty()); + + for (id, expected_substr) in [ + (&s_missing.id, "not found"), + (&s_dead.id, "no longer running"), + (&s_dup.id, "Multiple live agents"), + (&s_dur.id, "durable agent"), + ] { + let row = d.store.get_schedule(id).unwrap().unwrap(); + assert_eq!(row.status, "failed"); + assert!( + row.failure_reason + .as_deref() + .unwrap() + .contains(expected_substr), + "expected {expected_substr:?} in {:?}", + row.failure_reason + ); + } + } + + #[test] + fn tick_marks_failed_when_deliverer_errors_and_orders_concurrent_by_id() { + let f = FixtureDir::new("sched-order"); + let d = test_daemon(&f); + let self_pid = std::process::id() as i64; + d.store + .register_start(self_pid, "w", "claude", "/repo", "tmux", &json!({})) + .unwrap(); + let now = chrono_now(); + let due = iso8601_utc(now + 1000); + let s1 = d + .store + .create_schedule_at("w", "m1", &due, None, now) + .unwrap(); + let s2 = d + .store + .create_schedule_at("w", "m2", &due, None, now) + .unwrap(); + + let mock = MockDeliverer::failing("pane closed"); + tick_schedules(&d, now + 2000, &mock); + + assert_eq!( + d.store.get_schedule(&s1.id).unwrap().unwrap().status, + "failed" + ); + assert_eq!( + d.store + .get_schedule(&s2.id) + .unwrap() + .unwrap() + .failure_reason + .as_deref(), + Some("pane closed") + ); + // Verify deterministic order by id + let calls = mock.calls.lock().unwrap(); + let mut expected = [(&s1.id, "m1"), (&s2.id, "m2")]; + expected.sort_by_key(|(id, _)| *id); + assert_eq!( + calls.iter().map(|c| c.2.as_str()).collect::>(), + expected.iter().map(|(_, m)| *m).collect::>() + ); + } + + #[test] + fn hybrid_deliverer_routes_herdr_tmux_and_cli_fallback() { + let f = FixtureDir::new("sched-hybrid"); + f.set("cmd-12", "pts/20"); + f.set("pane_pid", "/dev/pts/2|%1\n/dev/pts/20|%3"); + let fake_cli = f.script( + "fake-ai-devkit", + "#!/bin/sh\nDIR=\"$(dirname \"$0\")\"\necho \"$@\" >> \"$DIR/cli-calls.log\"\ncat > \"$DIR/cli-stdin.log\"\nexit 0\n", + ); + + let deliverer = HybridDeliverer::with_bins( + Runtimes { + tmux: f.tmux(), + herdr: f.herdr(), + }, + fake_cli.to_str().unwrap(), + ); + + // 1. Herdr route + deliverer + .deliver( + &ResolvedTarget { + name: "h-agent".into(), + pid: 99, + runtime: "herdr".into(), + runtime_ref: json!({"paneId": "w1:p9"}), + }, + "ping herdr", + ) + .unwrap(); + assert!(f + .log("herdr-calls.log") + .contains("agent prompt w1:p9 ping herdr")); + + // 2. Tmux exact pane route + deliverer + .deliver( + &ResolvedTarget { + name: "t-agent".into(), + pid: 12, + runtime: "tmux".into(), + runtime_ref: json!({"session": "t-agent"}), + }, + "line1\nline2", + ) + .unwrap(); + let tmux_calls = f.log("tmux-calls.log"); + assert!(tmux_calls.contains("paste-buffer -t %3")); + assert!(tmux_calls.contains("send-keys -t %3 Enter")); + assert_eq!(f.log("tmux-stdin.log"), "line1\nline2"); + + // 3. Unmanaged terminal -> CLI fallback + deliverer + .deliver( + &ResolvedTarget { + name: "wez-agent".into(), + pid: 55, // no tty match + runtime: String::new(), + runtime_ref: Value::Null, + }, + "hello wez", + ) + .unwrap(); + assert!(f + .log("cli-calls.log") + .contains("agent send --id wez-agent --stdin")); + assert_eq!(f.log("cli-stdin.log"), "hello wez"); + + // 4. Missing CLI binary reports clear PATH-aware error + let missing = HybridDeliverer::with_bins( + Runtimes { + tmux: f.tmux(), + herdr: f.herdr(), + }, + &f.bin("nonexistent-cli"), + ); + let err = missing + .deliver( + &ResolvedTarget { + name: "wez-agent".into(), + pid: 55, + runtime: String::new(), + runtime_ref: Value::Null, + }, + "hi", + ) + .unwrap_err(); + assert!(err.contains("not found in devkitd PATH"), "{err}"); + } +} diff --git a/rust/crates/devkitd/src/server.rs b/rust/crates/devkitd/src/server.rs index a0e2e275..99a7cfd8 100644 --- a/rust/crates/devkitd/src/server.rs +++ b/rust/crates/devkitd/src/server.rs @@ -34,6 +34,9 @@ pub struct Daemon { pub home: PathBuf, /// Serializes agent.start so name-uniqueness can't race. pub start_mutex: std::sync::Mutex<()>, + /// Schedule IDs actively being delivered — blocks concurrent `schedule.cancel` + /// without introducing a 7th DB status. + pub in_flight_schedules: Mutex>, } impl Daemon { @@ -86,6 +89,7 @@ impl Daemon { swept_pids: Mutex::new(HashSet::new()), home, start_mutex: std::sync::Mutex::new(()), + in_flight_schedules: Mutex::new(HashSet::new()), }) } @@ -201,6 +205,11 @@ impl Daemon { Ok(result) => Response::ok(id, result), Err(e) => Response::err_coded(id, e.code, e.message, e.details), }, + m if m.starts_with("schedule.") => match crate::rpc::schedule::run(self, m, req.params) + { + Ok(result) => Response::ok(id, result), + Err(e) => Response::err_coded(id, e.code, e.message, e.details), + }, "shutdown" => { // Caller expects a response before exit; schedule exit. tokio::spawn(async { @@ -456,6 +465,29 @@ pub async fn serve(daemon: Arc) -> Result<()> { }); } + // Dedicated scheduler loop: runs independently of apply_sweep() so slow + // deliveries never stall discovery/events, and runs its first tick + // immediately after bind (post-warmup startup reconciliation). + { + let d = daemon.clone(); + tokio::spawn(async move { + let mut tick = tokio::time::interval(std::time::Duration::from_secs(2)); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + tick.tick().await; + let d = d.clone(); + if let Err(e) = tokio::task::spawn_blocking(move || { + let deliverer = crate::scheduler::HybridDeliverer::default(); + crate::scheduler::tick_schedules(&d, chrono_now(), &deliverer); + }) + .await + { + tracing::warn!("scheduler task failed: {e}"); + } + } + }); + } + loop { let (stream, _) = listener.accept().await?; if !peer_is_same_user(&stream) { @@ -1048,3 +1080,7 @@ mod tests { #[cfg(test)] #[path = "../tests/rpc/groups.rs"] mod group_tests; + +#[cfg(test)] +#[path = "../tests/rpc/schedules.rs"] +mod schedule_tests; diff --git a/rust/crates/devkitd/tests/rpc/schedules.rs b/rust/crates/devkitd/tests/rpc/schedules.rs new file mode 100644 index 00000000..8a5de2f7 --- /dev/null +++ b/rust/crates/devkitd/tests/rpc/schedules.rs @@ -0,0 +1,76 @@ +use super::*; +use crate::runtime::testkit::FixtureDir; + +fn request(d: &Daemon, method: &str, params: Value) -> Response { + d.dispatch(Request { + id: Some(9), + method: method.into(), + params, + }) +} + +#[test] +fn schedule_rpc_lifecycle_filters_and_in_flight_cancel_guard() { + let f = FixtureDir::new("schedule-rpc"); + let d = Daemon::new(&f.0, f.0.join("sock"), f.0.clone()).unwrap(); + let future = devkit_core::store::iso8601_utc(chrono_now() + 300_000); + + let created = request( + &d, + "schedule.create", + json!({ + "agentName": "worker-1", + "message": "ping", + "dueAt": future, + "createdBy": "orchestrator" + }), + ); + assert!(created.error.is_none(), "{:?}", created.error); + let created_val = created.result.unwrap(); + let id = created_val["id"].as_str().unwrap().to_owned(); + assert_eq!(created_val["status"], "pending"); + assert_eq!(created_val["createdBy"], "orchestrator"); + + // List with default empty params and with filter + let listed = request(&d, "schedule.list", json!({})).result.unwrap(); + assert_eq!(listed.as_array().unwrap().len(), 1); + let filtered = request( + &d, + "schedule.list", + json!({"status": "pending", "agentName": "worker-1", "limit": 10}), + ) + .result + .unwrap(); + assert_eq!(filtered.as_array().unwrap().len(), 1); + + // In-flight guard blocks cancel during active delivery + d.in_flight_schedules.lock().unwrap().insert(id.clone()); + let blocked = request(&d, "schedule.cancel", json!({"id": id})); + assert_eq!(blocked.code.as_deref(), Some("not_cancellable")); + assert_eq!(blocked.details.unwrap()["status"], "delivering"); + d.in_flight_schedules.lock().unwrap().remove(&id); + + // Cancel succeeds once not in-flight + let cancelled = request(&d, "schedule.cancel", json!({"id": id})); + assert!(cancelled.error.is_none(), "{:?}", cancelled.error); + assert_eq!(cancelled.result.unwrap()["status"], "cancelled"); + + // Second cancel returns not_cancellable with cancelled status + let again = request(&d, "schedule.cancel", json!({"id": id})); + assert_eq!(again.code.as_deref(), Some("not_cancellable")); + assert_eq!(again.details.unwrap()["status"], "cancelled"); + + // Missing id -> not_found + assert_eq!( + request(&d, "schedule.cancel", json!({"id": "sch_00000000"})) + .code + .as_deref(), + Some("not_found") + ); + + // Unknown schedule method -> unknown_method + assert_eq!( + request(&d, "schedule.unknown", json!({})).code.as_deref(), + Some("unknown_method") + ); +}