mirror of
https://github.com/outbackdingo/optimclaw.git
synced 2026-08-25 14:53:34 +00:00
* feat: add inbound attachment support to WASM channel system Add attachment record to WIT interface and implement inbound media parsing across all four channel implementations (Telegram, Slack, WhatsApp, Discord). Attachments flow from WASM channels through EmittedMessage to IncomingMessage with validation (size limits, MIME allowlist, count caps) at the host boundary. - Add `attachment` record to `emitted-message` in wit/channel.wit - Add `IncomingAttachment` struct to channel.rs and re-export - Add host-side validation (20MB total, 10 max, MIME allowlist) - Telegram: parse photo, document, audio, video, voice, sticker - Slack: parse file attachments with url_private - WhatsApp: parse image, audio, video, document with captions - Discord: backward-compatible empty attachments - Update FEATURE_PARITY.md section 7 - Add fixture-based tests per channel and host integration tests [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: integrate outbound attachment support and reconcile WIT types (#409) Reconcile PR #409's outbound attachment work with our inbound attachment support into a unified design: WIT type split: - `inbound-attachment` in channel-host: metadata-only (id, mime_type, filename, size_bytes, source_url, storage_key, extracted_text) - `attachment` in channel: raw bytes (filename, mime_type, data) on agent-response for outbound sending Outbound features (from PR #409): - `on-broadcast` WIT export for proactive messages without prior inbound - Telegram: multipart sendPhoto/sendDocument with auto photo→document fallback for files >10MB - wrapper.rs: `call_on_broadcast`, `read_attachments` from disk, attachment params threaded through `call_on_respond` - HTTP tool: `save_to` param for binary downloads to /tmp/ (50MB limit, path traversal protection, SSRF-safe redirect following) - Message tool: allow /tmp/ paths for attachments alongside base_dir - Credential env var fallback in inject_channel_credentials Channel updates: - All 4 channels implement on_broadcast (Telegram full, others stub) - Telegram: polling_enabled config, adjusted poll timeout - Inbound attachment types renamed to InboundAttachment in all channels Tests: 1965 passing (9 new), 0 clippy warnings [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: add audio transcription pipeline and extensible WIT attachment design Add host-side transcription middleware (OpenAI Whisper) that detects audio attachments with inline data on incoming messages and transcribes them automatically. Refactor WIT inbound-attachment to use extras-json and a store-attachment-data host function instead of typed fields, so future attachment properties (dimensions, codec, etc.) don't require WIT changes that invalidate all channel plugins. - Add src/transcription/ module: TranscriptionProvider trait, TranscriptionMiddleware, AudioFormat enum, OpenAI Whisper provider - Add src/config/transcription.rs: TRANSCRIPTION_ENABLED/MODEL/BASE_URL - Wire middleware into agent message loop via AgentDeps - WIT: replace data + duration-secs with extras-json + store-attachment-data - Host: parse extras-json for well-known keys, merge stored binary data - Telegram: download voice files via store-attachment-data, add duration to extras-json, add /file/bot to HTTP allowlist, voice-only placeholder - Add reqwest multipart feature for Whisper API uploads - 5 regression tests for transcription middleware Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: wire attachment processing into LLM pipeline with multimodal image support Attachments on incoming messages are now augmented into user text via XML tags before entering the turn system, and images with data are passed as multimodal content parts (base64 data URIs) to LLM providers. This enables audio transcripts, document text, and image content to reach the LLM without changes to ChatMessage serialization or provider interfaces. - Add src/agent/attachments.rs with augment_with_attachments() and 9 unit tests - Add ContentPart/ImageUrl types to llm::provider with OpenAI-compatible serde - Carry image_content_parts transiently on Turn (skipped in serialization) - Update nearai_chat and rig_adapter to serialize multimodal content - Add 3 e2e tests verifying attachments flow through the full agent loop Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: CI failures — formatting, version bumps, and Telegram voice test - Fix cargo fmt formatting in attachments.rs, nearai_chat.rs, rig_adapter.rs, e2e_attachments.rs - Bump channel registry versions 0.1.0 → 0.2.0 (discord, slack, telegram, whatsapp) to satisfy version-bump CI check - Fix Telegram test_extract_attachments_voice: add missing required `duration` field to voice fixture JSON Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: bump WIT channel version to 0.3.0, fix Telegram voice test, add pre-commit hook - Bump wit/channel.wit package version 0.2.0 → 0.3.0 (interface changed with store-attachment-data) - Update WIT_CHANNEL_VERSION constant and registry wit_version fields to match - Fix Telegram test_extract_attachments_voice: gate voice download behind #[cfg(target_arch = "wasm32")] so host functions aren't called in native tests, update assertions for generated filename and extras_json duration - Add @0.3.0 linker stubs in wit_compat.rs - Add .githooks/pre-commit hook that runs scripts/check-version-bumps.sh when WIT or extension sources are staged - Symlink commit-msg regression hook into .githooks/ [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor: extract voice download from extract_attachments into handle_message Move download_voice_file + store_attachment_data calls out of extract_attachments into a separate download_and_store_voice function called from handle_message. This keeps extract_attachments as a pure data-mapping function with no host calls, making it fully testable in native unit tests without #[cfg(target_arch)] gates. [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: address PR review comments — security, correctness, and code quality Security fixes: - Add path validation to read_attachments (restrict to /tmp/) preventing arbitrary file reads from compromised tools - Escape XML special characters in attachment filenames, MIME types, and extracted text to prevent prompt injection via tag spoofing - Percent-encode file_id in Telegram getFile URL to prevent query injection - Clone SecretString directly instead of expose_secret().to_string() Correctness fixes: - Fix store_attachment_data overwrite accounting: subtract old entry size before adding new to prevent inflated totals and false rejections - Use max(reported, stored_size) for attachment size accounting to prevent WASM channels from under-reporting size_bytes to bypass limits - Add application/octet-stream to MIME allowlist (channels default unknown types to this) Code quality: - Extract send_response helper in Telegram, deduplicating on_respond and on_broadcast - Rename misleading Discord test to test_parse_slash_command_interaction - Fix .githooks/commit-msg to use relative symlink (portable across machines) [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: add tool_upgrade command + fix TOCTOU in save_to path validation Add `tool_upgrade` — a new extension management tool that automatically detects and reinstalls WASM extensions with outdated WIT versions. Preserves authentication secrets during upgrade. Supports upgrading a single extension by name or all installed WASM tools/channels at once. Fix TOCTOU in `validate_save_to_path`: validate the path *before* creating parent directories, so traversal paths like `/tmp/../../etc/` cannot cause filesystem mutations outside /tmp before being rejected. [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: unify WIT package version to 0.3.0 across tool.wit and all capabilities tool.wit and channel.wit share the `near:agent` package namespace, so they must declare the same version. Bumps tool.wit from 0.2.0 to 0.3.0 and updates all capabilities files and registry entries to match. Fixes `cargo component build` failure: "package identifier near:[email protected] does not match previous package name of near:[email protected]" [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: move WIT file comments after package declaration WIT treats `//` comments before `package` as doc comments. When both tool.wit and channel.wit had header comments, the parser rejected them as "doc comments on multiple 'package' items". Move comments after the package declaration in both files. Also bumps tool registry versions to 0.2.0 to match the WIT 0.3.0 bump. [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: display extension versions in gateway Extensions tab Add version field to InstalledExtension and RegistryEntry types, pipe through the web API (ExtensionInfo, RegistryEntryInfo), and render as a badge in the gateway UI for both installed and available extensions. For installed WASM extensions, version is read from the capabilities file with a fallback to the registry entry when the local file has no version (old installations). Bump all extension Cargo.toml and registry JSON versions from 0.1.0 to 0.2.0 to keep them in sync. [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: add document text extraction middleware for PDF, Office, and text files Extract text from document attachments (PDF, DOCX, PPTX, XLSX, RTF, plain text, code files) so the LLM can reason about uploaded documents. Uses pdf-extract for PDFs, zip+XML parsing for Office XML formats, and UTF-8 decode for text files. Wired into the agent loop after transcription middleware. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: download document files in Telegram channel for text extraction The DocumentExtractionMiddleware needs file bytes in the attachment `data` field, but only voice files were being downloaded. Document attachments (PDFs, DOCX, etc.) had empty `data` and a source_url with a credential placeholder that only works inside the WASM host's http_request. Add `download_and_store_documents()` that downloads non-voice, non-image, non-audio attachments via the existing two-step getFile→download flow and stores bytes via `store_attachment_data` for host-side extraction. Also rename `download_voice_file` → `download_telegram_file` since it's generic for any file_id. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: allow Office MIME types and increase file download limit for Telegram Two issues preventing document extraction from Telegram: 1. PPTX/DOCX/XLSX MIME types (application/vnd.*) were dropped by the WASM host attachment allowlist — add application/vnd., application/msword, and application/rtf prefixes. 2. Telegram file downloads over 10 MB failed with "Response body too large" — set max_response_bytes to 20 MB in Telegram capabilities. [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: report document extraction errors back to user instead of silently skipping - Bump max_response_bytes to 50 MB for Telegram file downloads - When document extraction fails (too large, download error, parse error), set extracted_text to a user-friendly error message instead of leaving it None. This ensures the LLM tells the user what went wrong. - On Telegram download failure, set extracted_text with the error so the user sees feedback even when the file never reaches the extraction middleware. Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: store extracted document text in workspace memory for search/recall After document extraction succeeds, write the extracted text to workspace memory at `documents/{date}/{filename}`. This enables: - Full-text and semantic search over past uploaded documents - Cross-conversation recall ("what did that PDF say?") - Automatic chunking and embedding via the workspace pipeline Documents are stored with metadata header (uploader, channel, date, MIME type). Error messages (extraction failures) are not stored — only successful extractions. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: CI failures — formatting, unused assignment warning - Run cargo fmt on document_extraction and agent_loop modules - Suppress unused_assignments warning on trace_llm_ref (used only behind #[cfg(feature = "libsql")]) [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: address PR review comments — security, correctness, and code quality Security fixes: - Remove SSRF-prone download() from DocumentExtractionMiddleware (#13) - Sanitize filenames in workspace path to prevent directory traversal (#11) - Pre-check file size before reading in WASM wrapper to prevent OOM (#2) - Percent-encode file_id in Telegram source URLs (#7) Correctness fixes: - Clear image_content_parts on turn end to prevent memory leak (#1) - Find first *successful* transcription instead of first overall (#3) - Enforce data.len() size limit in document extraction (#10) - Use UTF-8 safe truncation with char_indices() (#12) Robustness & code quality: - Add 120s timeout to OpenAI Whisper HTTP client (#5) - Trim trailing slash from Whisper base_url (#6) - Allow ~/.ironclaw/ paths in WASM wrapper (#8) - Return error from on_broadcast in Slack/Discord/WhatsApp (#9) - Fix doc comment in HTTP tool (#4) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: formatting — cargo fmt Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: address latest PR review — doc comments, error messages, version bumps - Fix DocumentExtractionMiddleware doc comment (no longer downloads from source_url) - Fix error message: "no inline data" instead of "no download URL" - Log error + fallback instead of silent unwrap_or_default on Whisper HTTP client - Bump all capabilities.json versions from 0.1.0 to 0.2.0 to match Cargo.toml Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: remove unsupported profile: minimal from CI workflows [skip-regression-check] dtolnay/rust-toolchain@stable does not accept the 'profile' input (it was a parameter for the deprecated actions-rs/toolchain action). Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: merge with latest main — resolve compilation errors and PR review nits - Add version: None to RegistryEntry/InstalledExtension test constructors - Fix MessageContent type mismatches in nearai_chat tests (String → MessageContent::Text) - Fix .contains() calls on MessageContent — use .as_text().unwrap() - Remove redundant trace_llm_ref = None assignment in test_rig - Check data size before clone in document extraction to avoid unnecessary allocation [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> --------- Co-authored-by: Claude Opus 4.6 <[email protected]>
422 lines
14 KiB
Rust
422 lines
14 KiB
Rust
//! E2E tests: routine engine and heartbeat (#575).
|
|
//!
|
|
//! These tests construct RoutineEngine and HeartbeatRunner directly
|
|
//! with a TraceLlm and libSQL database, bypassing the full TestRig.
|
|
|
|
#[cfg(feature = "libsql")]
|
|
mod support;
|
|
|
|
#[cfg(feature = "libsql")]
|
|
mod tests {
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
|
|
use chrono::Utc;
|
|
use uuid::Uuid;
|
|
|
|
use ironclaw::agent::routine::{
|
|
NotifyConfig, Routine, RoutineAction, RoutineGuardrails, Trigger,
|
|
};
|
|
use ironclaw::agent::routine_engine::RoutineEngine;
|
|
use ironclaw::agent::{HeartbeatConfig, HeartbeatRunner};
|
|
use ironclaw::channels::IncomingMessage;
|
|
use ironclaw::config::{RoutineConfig, SafetyConfig};
|
|
use ironclaw::db::Database;
|
|
use ironclaw::safety::SafetyLayer;
|
|
use ironclaw::workspace::Workspace;
|
|
use ironclaw::workspace::hygiene::HygieneConfig;
|
|
|
|
use crate::support::trace_llm::{LlmTrace, TraceLlm, TraceResponse, TraceStep};
|
|
|
|
/// Create a temp libSQL database with migrations applied.
|
|
async fn create_test_db() -> (Arc<dyn Database>, tempfile::TempDir) {
|
|
use ironclaw::db::libsql::LibSqlBackend;
|
|
|
|
let temp_dir = tempfile::tempdir().expect("tempdir");
|
|
let db_path = temp_dir.path().join("test.db");
|
|
let backend = LibSqlBackend::new_local(&db_path)
|
|
.await
|
|
.expect("LibSqlBackend");
|
|
backend.run_migrations().await.expect("migrations");
|
|
let db: Arc<dyn Database> = Arc::new(backend);
|
|
(db, temp_dir)
|
|
}
|
|
|
|
/// Create a workspace backed by the test database.
|
|
fn create_workspace(db: &Arc<dyn Database>) -> Arc<Workspace> {
|
|
Arc::new(Workspace::new_with_db("default", db.clone()))
|
|
}
|
|
|
|
/// Helper to insert a routine directly into the database.
|
|
fn make_routine(name: &str, trigger: Trigger, prompt: &str) -> Routine {
|
|
Routine {
|
|
id: Uuid::new_v4(),
|
|
name: name.to_string(),
|
|
description: format!("Test routine: {name}"),
|
|
user_id: "default".to_string(),
|
|
enabled: true,
|
|
trigger,
|
|
action: RoutineAction::Lightweight {
|
|
prompt: prompt.to_string(),
|
|
context_paths: vec![],
|
|
max_tokens: 1000,
|
|
},
|
|
guardrails: RoutineGuardrails {
|
|
cooldown: Duration::from_secs(0),
|
|
max_concurrent: 5,
|
|
dedup_window: None,
|
|
},
|
|
notify: NotifyConfig::default(),
|
|
last_run_at: None,
|
|
next_fire_at: None,
|
|
run_count: 0,
|
|
consecutive_failures: 0,
|
|
state: serde_json::json!({}),
|
|
created_at: Utc::now(),
|
|
updated_at: Utc::now(),
|
|
}
|
|
}
|
|
|
|
// -----------------------------------------------------------------------
|
|
// Test 1: cron_routine_fires
|
|
// -----------------------------------------------------------------------
|
|
|
|
#[tokio::test]
|
|
async fn cron_routine_fires() {
|
|
let (db, _tmp) = create_test_db().await;
|
|
let ws = create_workspace(&db);
|
|
|
|
// Create a TraceLlm that responds with ROUTINE_OK.
|
|
let trace = LlmTrace::single_turn(
|
|
"test-cron-fire",
|
|
"check",
|
|
vec![TraceStep {
|
|
request_hint: None,
|
|
response: TraceResponse::Text {
|
|
content: "ROUTINE_OK".to_string(),
|
|
input_tokens: 50,
|
|
output_tokens: 5,
|
|
},
|
|
expected_tool_results: vec![],
|
|
}],
|
|
);
|
|
let llm = Arc::new(TraceLlm::from_trace(trace));
|
|
|
|
let (notify_tx, mut notify_rx) = tokio::sync::mpsc::channel(16);
|
|
|
|
let engine = Arc::new(RoutineEngine::new(
|
|
RoutineConfig::default(),
|
|
db.clone(),
|
|
llm,
|
|
ws,
|
|
notify_tx,
|
|
None,
|
|
));
|
|
|
|
// Insert a cron routine with next_fire_at in the past.
|
|
let mut routine = make_routine(
|
|
"cron-test",
|
|
Trigger::Cron {
|
|
schedule: "* * * * *".to_string(),
|
|
},
|
|
"Check system status.",
|
|
);
|
|
routine.next_fire_at = Some(Utc::now() - chrono::Duration::minutes(5));
|
|
db.create_routine(&routine).await.expect("create_routine");
|
|
|
|
// Fire cron triggers.
|
|
engine.check_cron_triggers().await;
|
|
|
|
// Give the spawned task time to execute.
|
|
tokio::time::sleep(Duration::from_millis(500)).await;
|
|
|
|
// Verify a run was recorded.
|
|
let runs = db
|
|
.list_routine_runs(routine.id, 10)
|
|
.await
|
|
.expect("list_routine_runs");
|
|
assert!(
|
|
!runs.is_empty(),
|
|
"Expected at least one routine run after cron trigger"
|
|
);
|
|
|
|
// Notification may or may not be sent depending on config;
|
|
// just verify no panic occurred. Drain the channel.
|
|
let _ = notify_rx.try_recv();
|
|
}
|
|
|
|
// -----------------------------------------------------------------------
|
|
// Test 2: event_trigger_matches
|
|
// -----------------------------------------------------------------------
|
|
|
|
#[tokio::test]
|
|
async fn event_trigger_matches() {
|
|
let (db, _tmp) = create_test_db().await;
|
|
let ws = create_workspace(&db);
|
|
|
|
let trace = LlmTrace::single_turn(
|
|
"test-event-match",
|
|
"deploy",
|
|
vec![TraceStep {
|
|
request_hint: None,
|
|
response: TraceResponse::Text {
|
|
content: "Deployment detected".to_string(),
|
|
input_tokens: 50,
|
|
output_tokens: 10,
|
|
},
|
|
expected_tool_results: vec![],
|
|
}],
|
|
);
|
|
let llm = Arc::new(TraceLlm::from_trace(trace));
|
|
let (notify_tx, _notify_rx) = tokio::sync::mpsc::channel(16);
|
|
|
|
let engine = Arc::new(RoutineEngine::new(
|
|
RoutineConfig::default(),
|
|
db.clone(),
|
|
llm,
|
|
ws,
|
|
notify_tx,
|
|
None,
|
|
));
|
|
|
|
// Insert an event routine matching "deploy.*production".
|
|
let routine = make_routine(
|
|
"deploy-watcher",
|
|
Trigger::Event {
|
|
channel: None,
|
|
pattern: "deploy.*production".to_string(),
|
|
},
|
|
"Report on deployment.",
|
|
);
|
|
db.create_routine(&routine).await.expect("create_routine");
|
|
|
|
// Refresh the event cache so the engine knows about the routine.
|
|
engine.refresh_event_cache().await;
|
|
|
|
// Positive match: message containing "deploy to production".
|
|
let matching_msg = IncomingMessage {
|
|
id: Uuid::new_v4(),
|
|
channel: "test".to_string(),
|
|
user_id: "default".to_string(),
|
|
user_name: None,
|
|
content: "deploy to production now".to_string(),
|
|
thread_id: None,
|
|
received_at: Utc::now(),
|
|
metadata: serde_json::json!({}),
|
|
attachments: Vec::new(),
|
|
};
|
|
let fired = engine.check_event_triggers(&matching_msg).await;
|
|
assert!(
|
|
fired >= 1,
|
|
"Expected >= 1 routine fired on match, got {fired}"
|
|
);
|
|
|
|
// Give spawn time.
|
|
tokio::time::sleep(Duration::from_millis(500)).await;
|
|
|
|
// Negative match: message that doesn't match.
|
|
let non_matching_msg = IncomingMessage {
|
|
id: Uuid::new_v4(),
|
|
channel: "test".to_string(),
|
|
user_id: "default".to_string(),
|
|
user_name: None,
|
|
content: "check the staging environment".to_string(),
|
|
thread_id: None,
|
|
received_at: Utc::now(),
|
|
metadata: serde_json::json!({}),
|
|
attachments: Vec::new(),
|
|
};
|
|
let fired_neg = engine.check_event_triggers(&non_matching_msg).await;
|
|
assert_eq!(fired_neg, 0, "Expected 0 routines fired on non-match");
|
|
}
|
|
|
|
// -----------------------------------------------------------------------
|
|
// Test 3: routine_cooldown
|
|
// -----------------------------------------------------------------------
|
|
|
|
#[tokio::test]
|
|
async fn routine_cooldown() {
|
|
let (db, _tmp) = create_test_db().await;
|
|
let ws = create_workspace(&db);
|
|
|
|
// Need two LLM responses (one for the first fire).
|
|
let trace = LlmTrace::single_turn(
|
|
"test-cooldown",
|
|
"check",
|
|
vec![TraceStep {
|
|
request_hint: None,
|
|
response: TraceResponse::Text {
|
|
content: "ROUTINE_OK".to_string(),
|
|
input_tokens: 50,
|
|
output_tokens: 5,
|
|
},
|
|
expected_tool_results: vec![],
|
|
}],
|
|
);
|
|
let llm = Arc::new(TraceLlm::from_trace(trace));
|
|
let (notify_tx, _notify_rx) = tokio::sync::mpsc::channel(16);
|
|
|
|
let engine = Arc::new(RoutineEngine::new(
|
|
RoutineConfig::default(),
|
|
db.clone(),
|
|
llm,
|
|
ws,
|
|
notify_tx,
|
|
None,
|
|
));
|
|
|
|
// Insert an event routine with 1-hour cooldown.
|
|
let mut routine = make_routine(
|
|
"cooldown-test",
|
|
Trigger::Event {
|
|
channel: None,
|
|
pattern: "test-cooldown".to_string(),
|
|
},
|
|
"Check status.",
|
|
);
|
|
routine.guardrails.cooldown = Duration::from_secs(3600);
|
|
db.create_routine(&routine).await.expect("create_routine");
|
|
engine.refresh_event_cache().await;
|
|
|
|
// First fire should work.
|
|
let msg = IncomingMessage {
|
|
id: Uuid::new_v4(),
|
|
channel: "test".to_string(),
|
|
user_id: "default".to_string(),
|
|
user_name: None,
|
|
content: "test-cooldown trigger".to_string(),
|
|
thread_id: None,
|
|
received_at: Utc::now(),
|
|
metadata: serde_json::json!({}),
|
|
attachments: Vec::new(),
|
|
};
|
|
let fired1 = engine.check_event_triggers(&msg).await;
|
|
assert!(fired1 >= 1, "First fire should work");
|
|
|
|
// Give spawn time, then update last_run_at to simulate recent execution.
|
|
tokio::time::sleep(Duration::from_millis(300)).await;
|
|
|
|
// Update the routine's last_run_at to now (simulating it just ran).
|
|
db.update_routine_runtime(routine.id, Utc::now(), None, 1, 0, &serde_json::json!({}))
|
|
.await
|
|
.expect("update_routine_runtime");
|
|
|
|
// Refresh cache to pick up updated last_run_at.
|
|
engine.refresh_event_cache().await;
|
|
|
|
// Second fire should be blocked by cooldown.
|
|
let fired2 = engine.check_event_triggers(&msg).await;
|
|
assert_eq!(fired2, 0, "Second fire should be blocked by cooldown");
|
|
}
|
|
|
|
// -----------------------------------------------------------------------
|
|
// Test 4: heartbeat_findings
|
|
// -----------------------------------------------------------------------
|
|
|
|
#[tokio::test]
|
|
async fn heartbeat_findings() {
|
|
let (db, _tmp) = create_test_db().await;
|
|
let ws = create_workspace(&db);
|
|
|
|
// Write a real heartbeat checklist.
|
|
ws.write(
|
|
"HEARTBEAT.md",
|
|
"# Heartbeat Checklist\n\n- [ ] Check if the server is running\n- [ ] Review error logs",
|
|
)
|
|
.await
|
|
.expect("write heartbeat");
|
|
|
|
// LLM responds with findings (not HEARTBEAT_OK).
|
|
let trace = LlmTrace::single_turn(
|
|
"test-heartbeat-findings",
|
|
"heartbeat",
|
|
vec![TraceStep {
|
|
request_hint: None,
|
|
response: TraceResponse::Text {
|
|
content: "The server has elevated error rates. Review the logs immediately."
|
|
.to_string(),
|
|
input_tokens: 100,
|
|
output_tokens: 20,
|
|
},
|
|
expected_tool_results: vec![],
|
|
}],
|
|
);
|
|
let llm = Arc::new(TraceLlm::from_trace(trace));
|
|
let safety = Arc::new(SafetyLayer::new(&SafetyConfig {
|
|
max_output_length: 100_000,
|
|
injection_check_enabled: false,
|
|
}));
|
|
|
|
let (tx, mut rx) = tokio::sync::mpsc::channel(16);
|
|
|
|
let hygiene_config = HygieneConfig {
|
|
enabled: false,
|
|
daily_retention_days: 30,
|
|
conversation_retention_days: 7,
|
|
cadence_hours: 24,
|
|
state_dir: _tmp.path().to_path_buf(),
|
|
};
|
|
|
|
let runner =
|
|
HeartbeatRunner::new(HeartbeatConfig::default(), hygiene_config, ws, llm, safety)
|
|
.with_response_channel(tx);
|
|
|
|
let result = runner.check_heartbeat().await;
|
|
match result {
|
|
ironclaw::agent::HeartbeatResult::NeedsAttention(msg) => {
|
|
assert!(
|
|
msg.contains("error"),
|
|
"Expected 'error' in attention message: {msg}"
|
|
);
|
|
}
|
|
other => panic!("Expected NeedsAttention, got: {other:?}"),
|
|
}
|
|
|
|
// No notification since we called check_heartbeat directly (not run).
|
|
let _ = rx.try_recv();
|
|
}
|
|
|
|
// -----------------------------------------------------------------------
|
|
// Test 5: heartbeat_empty_skip
|
|
// -----------------------------------------------------------------------
|
|
|
|
#[tokio::test]
|
|
async fn heartbeat_empty_skip() {
|
|
let (db, _tmp) = create_test_db().await;
|
|
let ws = create_workspace(&db);
|
|
|
|
// Write an effectively empty heartbeat (just headers and comments).
|
|
ws.write(
|
|
"HEARTBEAT.md",
|
|
"# Heartbeat Checklist\n\n<!-- No tasks yet -->\n",
|
|
)
|
|
.await
|
|
.expect("write heartbeat");
|
|
|
|
// LLM should NOT be called, so provide a trace that would panic if called.
|
|
let trace = LlmTrace::single_turn("test-heartbeat-skip", "skip", vec![]);
|
|
let llm = Arc::new(TraceLlm::from_trace(trace));
|
|
let safety = Arc::new(SafetyLayer::new(&SafetyConfig {
|
|
max_output_length: 100_000,
|
|
injection_check_enabled: false,
|
|
}));
|
|
|
|
let hygiene_config = HygieneConfig {
|
|
enabled: false,
|
|
daily_retention_days: 30,
|
|
conversation_retention_days: 7,
|
|
cadence_hours: 24,
|
|
state_dir: _tmp.path().to_path_buf(),
|
|
};
|
|
|
|
let runner =
|
|
HeartbeatRunner::new(HeartbeatConfig::default(), hygiene_config, ws, llm, safety);
|
|
|
|
let result = runner.check_heartbeat().await;
|
|
assert!(
|
|
matches!(result, ironclaw::agent::HeartbeatResult::Skipped),
|
|
"Expected Skipped for empty checklist, got: {result:?}"
|
|
);
|
|
}
|
|
}
|