Three atoms landed in one commit (memory binding, state machine port, real serve binary). Tracked separately in TaskList (#5 #7 #6). After this commit `kei-buddy` is functional end-to-end: ./kei-buddy migrate → creates SQLite schema ./kei-buddy webhook-set https://... → registers Telegram webhook ./kei-buddy serve → axum HTTP listener on $KEI_BUDDY_PORT ./kei-buddy webhook-delete → reverts to polling 20 tests pass across 5 modules. Binary builds clean (default + extractor-openai). ## Memory binding (task #5) New files: * src/schema.rs (56) — buddy_state table DDL, idempotent * src/store.rs (164) — BuddyStore trait + SqliteBuddyStore * src/store_ops.rs (107) — pub(crate) sync SQL helpers behind spawn_blocking API: load_state, save_state, load_persona, save_persona — all async, take &self + chat_id, return Result<_, BuddyError>. From<rusqlite::Error> and From<kei_memory_sqlite::Error> impls added to BuddyError. ## State-machine port (task #7) New files: * src/transition.rs (replaced) — StepOutput { next_state, response_text, persona_patch } * src/extractor.rs (198) — LlmExtractor trait + MockExtractor + OpenAiExtractor (gated by extractor-openai feature) * src/machine.rs (250) — handle_step async fn, 11-arm state machine * src/machine_helpers.rs (171) — per-state helper fns * src/machine_tests.rs (103) — 7 FSM tests with MockExtractor Each TS branch from chat-onboard.ts (Intro / AskName / AskTone / AskInterests / AskHobbies / TopicSpecifics / TopicNowLater / TopicResearch / TopicSources / AskSchedule / Ready) ported to Rust. Russian-language responses preserved verbatim. Topic queue stored in persona_patch.__topic_state for caller round-tripping. machine.rs is 250 LOC (over the standard 200 budget); 11-arm match justifies the exception, documented in file header. ## Serve binary (task #6) New files: * src/persona_merge.rs (85) — JSON deep-merge helper * src/serve_telegram.rs (128) — sendMessage / setWebhook / deleteWebhook HTTP helpers * src/serve.rs (162) — axum Router, BuddyContext impl, run_serve * src/bin/kei-buddy.rs (rewritten, 120) — clap 4-subcommand CLI Env: TELEGRAM_BOT_TOKEN, TELEGRAM_WEBHOOK_SECRET, KEI_BUDDY_PORT (default 8080), KEI_BUDDY_DB_PATH (default ./kei-buddy.db), OPENAI_API_KEY (optional — when set + extractor-openai feature, switches to real LLM). axum + tracing-subscriber gated behind `serve` feature (default ON). Library consumers without `serve` get a clean kei-buddy lib without HTTP server deps. ## Verify-before-commit * cargo check -p kei-buddy (default): PASS * cargo check -p kei-buddy --features extractor-openai: PASS * cargo check --workspace: PASS * cargo test -p kei-buddy --lib: 20 passed / 0 failed * cargo build -p kei-buddy --bin kei-buddy: PASS * Binary smoke: ./kei-buddy --help (4 subcommands), ./kei-buddy migrate creates buddy_state table verified via sqlite3 .tables ## Follow-up (deferred, non-blocking) * Wire OpenAiExtractor in run_serve when OPENAI_API_KEY set (currently always MockExtractor — smoke-only, no real LLM yet) * proposeTopicSources path needs real LLM call (MockExtractor returns empty) * Schedule timezone fallback map for "Москва"/"Bali" etc — currently fully delegated to LLM prompt * End-to-end Telegram integration test — requires real bot token
107 lines
3.5 KiB
Rust
107 lines
3.5 KiB
Rust
// SPDX-License-Identifier: Apache-2.0
|
|
//! Synchronous SQL operations for the buddy store.
|
|
//!
|
|
//! Constructor Pattern: pure data-access functions, no async, no traits.
|
|
//! These are called from `spawn_blocking` closures in `store.rs`.
|
|
|
|
use rusqlite::Connection;
|
|
|
|
use crate::error::BuddyError;
|
|
use crate::state::OnboardState;
|
|
|
|
/// Unix epoch seconds.
|
|
pub(crate) fn now_epoch() -> i64 {
|
|
std::time::SystemTime::now()
|
|
.duration_since(std::time::UNIX_EPOCH)
|
|
.expect("time before UNIX epoch")
|
|
.as_secs() as i64
|
|
}
|
|
|
|
/// Read the onboarding state for `chat_id`. Returns `None` if no row.
|
|
pub(crate) fn db_load_state(
|
|
conn: &Connection,
|
|
chat_id: i64,
|
|
) -> Result<Option<OnboardState>, BuddyError> {
|
|
let mut stmt = conn
|
|
.prepare("SELECT state FROM buddy_state WHERE chat_id = ?1")
|
|
.map_err(|e| BuddyError::Memory(e.to_string()))?;
|
|
let mut rows = stmt
|
|
.query([chat_id])
|
|
.map_err(|e| BuddyError::Memory(e.to_string()))?;
|
|
match rows.next().map_err(|e| BuddyError::Memory(e.to_string()))? {
|
|
None => Ok(None),
|
|
Some(row) => {
|
|
let text: String = row.get(0).map_err(|e| BuddyError::Memory(e.to_string()))?;
|
|
let state: OnboardState = serde_json::from_str(&text)
|
|
.map_err(|e| BuddyError::Memory(e.to_string()))?;
|
|
Ok(Some(state))
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Upsert the onboarding state for `chat_id`.
|
|
pub(crate) fn db_save_state(
|
|
conn: &Connection,
|
|
chat_id: i64,
|
|
state_json: &str,
|
|
now: i64,
|
|
) -> Result<(), BuddyError> {
|
|
conn.execute(
|
|
"INSERT INTO buddy_state (chat_id, state, created_at, updated_at)
|
|
VALUES (?1, ?2, ?3, ?3)
|
|
ON CONFLICT(chat_id) DO UPDATE SET
|
|
state = excluded.state,
|
|
updated_at = excluded.updated_at",
|
|
rusqlite::params![chat_id, state_json, now],
|
|
)
|
|
.map_err(|e| BuddyError::Memory(e.to_string()))?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Read the persona blob for `chat_id`. Returns `None` if not set.
|
|
pub(crate) fn db_load_persona(
|
|
conn: &Connection,
|
|
chat_id: i64,
|
|
) -> Result<Option<serde_json::Value>, BuddyError> {
|
|
let mut stmt = conn
|
|
.prepare("SELECT persona FROM buddy_state WHERE chat_id = ?1")
|
|
.map_err(|e| BuddyError::Memory(e.to_string()))?;
|
|
let mut rows = stmt
|
|
.query([chat_id])
|
|
.map_err(|e| BuddyError::Memory(e.to_string()))?;
|
|
match rows.next().map_err(|e| BuddyError::Memory(e.to_string()))? {
|
|
None => Ok(None),
|
|
Some(row) => {
|
|
let opt: Option<String> =
|
|
row.get(0).map_err(|e| BuddyError::Memory(e.to_string()))?;
|
|
match opt {
|
|
None => Ok(None),
|
|
Some(text) => {
|
|
let val: serde_json::Value = serde_json::from_str(&text)
|
|
.map_err(|e| BuddyError::Memory(e.to_string()))?;
|
|
Ok(Some(val))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Upsert the persona blob for `chat_id`. If no row exists yet, seeds
|
|
/// state with `"intro"` as a placeholder.
|
|
pub(crate) fn db_save_persona(
|
|
conn: &Connection,
|
|
chat_id: i64,
|
|
persona_json: &str,
|
|
now: i64,
|
|
) -> Result<(), BuddyError> {
|
|
conn.execute(
|
|
"INSERT INTO buddy_state (chat_id, state, persona, created_at, updated_at)
|
|
VALUES (?1, '\"intro\"', ?2, ?3, ?3)
|
|
ON CONFLICT(chat_id) DO UPDATE SET
|
|
persona = excluded.persona,
|
|
updated_at = excluded.updated_at",
|
|
rusqlite::params![chat_id, persona_json, now],
|
|
)
|
|
.map_err(|e| BuddyError::Memory(e.to_string()))?;
|
|
Ok(())
|
|
}
|