Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions docs/ai/design/2026-11-25-feature-scheduled-sends.md
Original file line number Diff line number Diff line change
@@ -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 <name> --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 <paneId> <msg>`, 10s timeout).
- `TmuxRuntime::pane_for_pid(pid)` (`ps -p <pid> -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 <name> --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 <id>`.

## 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 <paneId> <msg>`.
- **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.
32 changes: 32 additions & 0 deletions docs/ai/implementation/2026-11-25-feature-scheduled-sends.md
Original file line number Diff line number Diff line change
@@ -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.
50 changes: 50 additions & 0 deletions docs/ai/planning/2026-11-25-feature-scheduled-sends.md
Original file line number Diff line number Diff line change
@@ -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).
64 changes: 64 additions & 0 deletions docs/ai/requirements/2026-11-25-feature-scheduled-sends.md
Original file line number Diff line number Diff line change
@@ -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 <agent> (--in <duration> | --at <iso-8601>) [message] [--stdin] [--json]`
- `ai-devkit agent schedule list [--status <status>] [--agent <name>] [--limit <n>] [--json]`
- `ai-devkit agent schedule cancel <id> [--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 <self> --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 <id>`.
- **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 <id>` 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/<pkg>/tests/` and Rust crate tests in `rust/crates/<crate>/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 <name> --stdin`, 15s timeout) when a live agent is outside `tmux`/`herdr`.
Loading
Loading