feat(voice_worker): record history from the app and answer reply requests with the brain

Worker (voice_worker.spec.md "History and brain"):
- --history <file> keeps the conversation history store; --brain hosts the
  jarvis reply engine (JarvisBrain, settings point ollama_base_url at /v1).
- voice_join / voice_leave / member_join / member_leave keep presence; the
  session end closes it. Non-empty finals are stored under the speaker's name
  in the current voice channel.
- chat_message / chat_edit / chat_delete keep registered chat channels.
- reply builds the asker's scoped history context, runs the brain on a thread
  (one at a time), answers reply_text, stores a voice answer, and with
  speak=true says it under the same id. memory settings in hello and
  memory_config. brain_unavailable without --brain.

App (discord_core.spec.md "History reporting"):
- WorkerClient sends the new messages; the core reports the voice channel
  and its heard members after a join, a move and every worker reconnect,
  member joins and leaves, voice_leave when a session ends, and every message
  of a readable registered channel (its own too, with `to` on replies), edits
  and deletes.
- live_discord runs the worker with --history and checks the store at the
  end: 8 finals under the speaker's name, the edited chat message only,
  Jarvis's own messages, 5 presence intervals, none left open (passed, 107.8 s).

Eval: history recall gains a chat-record case and fails a reply that reads a
record stamp out (field run with qwen2.5:7b did once in four).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-11 13:16:24 +09:00
parent 7a288129de
commit 864b2e7fdb
13 changed files with 775 additions and 18 deletions

View File

@@ -163,9 +163,12 @@ async fn discord_voice_core_on_real_discord() {
}
// The real voice worker.
let mut args = vec![];
// A fresh history store: the worker records what this test says and who was there.
let history_db = Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("live-history-{}.sqlite", std::process::id()));
let _ = std::fs::remove_file(&history_db);
let mut args = vec!["--history".to_string(), history_db.to_string_lossy().into_owned()];
if let Ok(m) = std::env::var("JARVIS_MELO_PYTHON") {
args = vec!["--melo-python".to_string(), m];
args.extend(["--melo-python".to_string(), m]);
}
let wp = WorkerProcess::new(WorkerProcessOptions::new(env("JARVIS_VOICE_PYTHON"), root.join("../src"), args)).unwrap();
let mut pev = wp.subscribe();
@@ -325,6 +328,14 @@ async fn discord_voice_core_on_real_discord() {
let history = core.read_chat(voice, 20).await.unwrap();
assert!(history.iter().any(|m| m.content == marker && !m.from_self));
assert!(history.iter().any(|m| m.from_self && m.content.contains("받아 적습니다")), "join notice missing");
// An edit and a delete reach the history store.
let mut marker_msg = ChannelId::new(voice).messages(&s_http, serenity::all::GetMessages::new().limit(5)).await.unwrap()
.into_iter().find(|m| m.content == marker).unwrap();
let edited = format!("{marker} 수정");
marker_msg.edit(&s_http, serenity::all::EditMessage::new().content(&edited)).await.unwrap();
let doomed = ChannelId::new(voice).send_message(&s_http, CreateMessage::new().content("곧 지울 메시지")).await.unwrap();
tokio::time::sleep(Duration::from_millis(800)).await;
doomed.delete(&s_http).await.unwrap();
let reply = format!("자비스 답장 @everyone {}", stop_at.elapsed().as_nanos());
let ids = core.send_chat(voice, &reply).await.unwrap();
let sent = ChannelId::new(voice).message(&s_http, serenity::all::MessageId::new(ids[0])).await.unwrap();
@@ -387,6 +398,41 @@ async fn discord_voice_core_on_real_discord() {
assert_eq!(core.voice_channel_id(), None);
assert!(core.say("아무도 못 듣는 말", false).is_none());
// 9. The history store: the speaker's finals under its name, its chat with the edit and without
// the deleted message, Jarvis's own messages, and presence closed now that Jarvis left.
tokio::time::sleep(Duration::from_millis(500)).await;
let check = r#"
import json, sys
from jarvis.memory.history import HistoryStore
s = HistoryStore(sys.argv[1]); sp, jv = sys.argv[2], sys.argv[3]
own = s.records_of(sp)
q = lambda sql, *a: s._conn.execute(sql, a).fetchone()[0]
print(json.dumps({"voice": [[r.author_name, r.channel_id, r.text] for r in own if r.kind == "voice"],
"chat": [r.text for r in own if r.kind == "chat"], "jarvis_chat": [r.text for r in s.records_of(jv) if r.kind == "chat"],
"presence": q("select count(*) from presence where user_id = ?", sp), "open": q("select count(*) from presence where left_at is null")},
ensure_ascii=False))
"#;
let out = std::process::Command::new(env("JARVIS_VOICE_PYTHON")).current_dir(root.join("../src"))
.args(["-c", check, &history_db.to_string_lossy(), &speaker_id.to_string(), &jarvis.to_string()])
.output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let h: Value = serde_json::from_slice(&out.stdout).unwrap();
let voice_recs = h["voice"].as_array().unwrap();
let speaker_name = s_cache.user(UserId::new(speaker_id)).map(|u| u.display_name().to_owned()).unwrap_or_default();
report.insert("history".into(), json!({"voice_records": voice_recs.len(), "presence_intervals": h["presence"],
"open_presence": h["open"], "chat": h["chat"], "jarvis_chat": h["jarvis_chat"].as_array().map(|a| a.len())}));
assert!(voice_recs.len() >= 8, "finals not stored: {h}");
assert!(voice_recs.iter().all(|r| r[0].as_str() != Some(&speaker_id.to_string()) && !r[2].as_str().unwrap().is_empty()),
"a final without the speaker's name: {h}");
assert!(voice_recs.iter().any(|r| r[0].as_str() == Some(speaker_name.as_str())), "{speaker_name} not in {h}");
assert!(voice_recs.iter().any(|r| r[1] == voice.to_string()), "{h}");
let chat: Vec<&str> = h["chat"].as_array().unwrap().iter().filter_map(|v| v.as_str()).collect();
assert_eq!(chat, [edited.as_str()], "speaker chat in the history");
let jarvis_chat: Vec<&str> = h["jarvis_chat"].as_array().unwrap().iter().filter_map(|v| v.as_str()).collect();
assert!(jarvis_chat.contains(&reply.as_str()) && jarvis_chat.iter().any(|t| t.contains("받아 적습니다")), "{h}");
assert!(h["presence"].as_u64().unwrap() >= 4, "joins and rejoins open presence: {h}");
assert_eq!(h["open"], 0, "presence left open after Jarvis left: {h}");
println!("live report {}", serde_json::to_string_pretty(&Value::Object(report.clone())).unwrap());
})).await;

View File

@@ -228,3 +228,34 @@ async fn tts_while_disconnected_fails_at_once() {
let e = next_matching(&mut rx, |_| true).await;
assert_eq!(e, WorkerEvent::TtsDone(TtsDone { id: "r1".into(), chunks: 0, cancelled: false, failed: true }));
}
#[tokio::test]
async fn history_messages_follow_the_worker_protocol() {
let w = FakeWorker::start(0).await;
let (c, _rx) = client(&w.url(), json!({}));
c.start();
c.wait_ready(Duration::from_secs(2)).await.expect("ready");
c.voice_join(42);
c.member_join(7, "Alice");
c.member_leave(7);
c.chat_message(9, 100, 7, "Alice", "hi there", 1_800_000_000.5, None);
c.chat_message(9, 101, 1, "Jarvis", "hello", 1_800_000_001.0, Some(7));
c.chat_edit(9, 100, "hi, edited");
c.chat_delete(9, 100);
c.voice_leave();
until(|| w.got().len() >= 9).await;
let got: Vec<Value> = w.got()[1..].iter().map(|g| match g { Got::Json(v) => v.clone(), Got::Bin(_) => json!(null) }).collect();
assert_eq!(got, vec![
json!({"type": "voice_join", "channel": "42"}),
json!({"type": "member_join", "user": "7", "name": "Alice"}),
json!({"type": "member_leave", "user": "7"}),
json!({"type": "chat_message", "channel": "9", "message_id": "100", "author": "7", "name": "Alice",
"text": "hi there", "ts": 1_800_000_000.5}),
json!({"type": "chat_message", "channel": "9", "message_id": "101", "author": "1", "name": "Jarvis",
"text": "hello", "ts": 1_800_000_001.0, "to": "7"}),
json!({"type": "chat_edit", "channel": "9", "message_id": "100", "text": "hi, edited"}),
json!({"type": "chat_delete", "channel": "9", "message_id": "100"}),
json!({"type": "voice_leave"}),
]);
c.close();
}