Wire Void Discord memory organs

This commit is contained in:
Meta Vens 2026-05-07 00:38:57 +01:00
commit 118e727ca9
10 changed files with 1037 additions and 29 deletions

View file

@ -22,6 +22,9 @@ struct FaceConfig {
allowed_channel_id: Option<String>,
allowed_channel_id_env: Option<String>,
bot_token_env: Option<String>,
persona_name: Option<String>,
persona_avatar_url: Option<String>,
webhook_cache_path: Option<PathBuf>,
}
fn main() -> Result<()> {
@ -37,6 +40,9 @@ fn main() -> Result<()> {
let mut status = "ready".to_string();
let mut mood = "attentive".to_string();
let mut limit = 8_usize;
let mut persona_name: Option<String> = None;
let mut persona_avatar_url: Option<String> = None;
let mut reply_to_message_id: Option<String> = None;
while let Some(arg) = args.next() {
match arg.as_str() {
@ -48,6 +54,13 @@ fn main() -> Result<()> {
"--status" => status = next_value(&mut args, "--status")?,
"--mood" => mood = next_value(&mut args, "--mood")?,
"--limit" => limit = next_value(&mut args, "--limit")?.parse()?,
"--persona-name" => persona_name = Some(next_value(&mut args, "--persona-name")?),
"--persona-avatar-url" => {
persona_avatar_url = Some(next_value(&mut args, "--persona-avatar-url")?)
}
"--reply-to-message-id" => {
reply_to_message_id = Some(next_value(&mut args, "--reply-to-message-id")?)
}
_ => return Err(anyhow!("unknown argument {arg:?}")),
}
}
@ -71,7 +84,15 @@ fn main() -> Result<()> {
"post" => {
let config = load_config(&config_path)?;
let content = read_content(content)?;
run_post(&content, &config, &artifact_dir, channel_id)?
run_post(
&content,
&config,
&artifact_dir,
channel_id,
persona_name,
persona_avatar_url,
reply_to_message_id,
)?
}
"latest" => serde_json::json!({
"ok": true,
@ -129,6 +150,9 @@ fn run_post(
config: &FaceConfig,
artifact_dir: &Path,
channel_id: Option<String>,
persona_name: Option<String>,
persona_avatar_url: Option<String>,
reply_to_message_id: Option<String>,
) -> Result<Value> {
ensure_content(content, "Face chat")?;
let configured_channel_id = allowed_channel_id(config);
@ -178,44 +202,247 @@ fn run_post(
"draftPath": path,
}));
};
let response = Client::new()
.post(format!(
"{DISCORD_API}/channels/{configured_channel_id}/messages"
))
.header("Authorization", format!("Bot {token}"))
.header("User-Agent", "EpiphanyFace/0.1")
.json(&serde_json::json!({ "content": content.trim() }))
.send()
.context("Discord post failed")?;
if !response.status().is_success() {
return Err(anyhow!(
"Discord post failed with HTTP {}: {}",
response.status(),
response.text().unwrap_or_default()
));
}
let payload: Value = response.json().context("Discord response was not JSON")?;
let persona = resolve_persona(config, persona_name, persona_avatar_url)?;
let posted = post_discord_message(
&token,
&configured_channel_id,
content.trim(),
reply_to_message_id.as_deref(),
persona.as_ref(),
config,
artifact_dir,
)?;
let path = write_draft(
content,
config,
artifact_dir,
"posted",
&format!(
"posted message {}",
payload
.get("id")
.and_then(Value::as_str)
.unwrap_or("unknown")
"posted message {} via {}",
posted.message_id, posted.transport
),
)?;
Ok(serde_json::json!({
"ok": true,
"posted": true,
"messageId": payload.get("id"),
"messageId": posted.message_id,
"transport": posted.transport,
"persona": persona.map(|persona| serde_json::json!({
"name": persona.name,
"avatarUrl": persona.avatar_url,
})),
"draftPath": path,
}))
}
#[derive(Clone, Debug)]
struct FacePersona {
name: String,
avatar_url: Option<String>,
}
#[derive(Clone, Debug)]
struct PostedDiscordMessage {
message_id: String,
transport: &'static str,
}
fn resolve_persona(
config: &FaceConfig,
persona_name: Option<String>,
persona_avatar_url: Option<String>,
) -> Result<Option<FacePersona>> {
let name = trim_optional(persona_name).or_else(|| trim_optional(config.persona_name.clone()));
let avatar_url = trim_optional(persona_avatar_url)
.or_else(|| trim_optional(config.persona_avatar_url.clone()));
if name.is_none() && avatar_url.is_none() {
return Ok(None);
}
let Some(name) = name else {
return Err(anyhow!(
"persona-name is required when posting with a persona avatar"
));
};
Ok(Some(FacePersona {
name: name.chars().take(80).collect(),
avatar_url,
}))
}
fn post_discord_message(
token: &str,
channel_id: &str,
content: &str,
reply_to_message_id: Option<&str>,
persona: Option<&FacePersona>,
config: &FaceConfig,
artifact_dir: &Path,
) -> Result<PostedDiscordMessage> {
if let Some(persona) = persona {
return post_discord_persona_message(
token,
channel_id,
content,
reply_to_message_id,
persona,
config,
artifact_dir,
);
}
let response = Client::new()
.post(format!("{DISCORD_API}/channels/{channel_id}/messages"))
.header("Authorization", format!("Bot {token}"))
.header("User-Agent", "EpiphanyFace/0.1")
.json(&serde_json::json!({
"content": content,
"message_reference": reply_to_message_id.map(|message_id| serde_json::json!({
"message_id": message_id,
"fail_if_not_exists": false,
})),
"allowed_mentions": {"parse": []},
}))
.send()
.context("Discord post failed")?;
let payload = decode_discord_json(response, "Discord message post")?;
Ok(PostedDiscordMessage {
message_id: required_discord_id(&payload, "Discord message post")?,
transport: "bot",
})
}
fn post_discord_persona_message(
token: &str,
channel_id: &str,
content: &str,
reply_to_message_id: Option<&str>,
persona: &FacePersona,
config: &FaceConfig,
artifact_dir: &Path,
) -> Result<PostedDiscordMessage> {
let target = resolve_webhook_target(token, channel_id)?;
let cache_path = persona_webhook_cache_path(config, artifact_dir);
let mut webhook = cached_persona_webhook(&cache_path, &target.webhook_channel_id)?;
if webhook.is_none() {
let created = create_persona_webhook(token, &target.webhook_channel_id)?;
write_cached_persona_webhook(&cache_path, &target.webhook_channel_id, &created)?;
webhook = Some(created);
}
let webhook = webhook.context("persona webhook should exist")?;
match execute_persona_webhook(&webhook, &target, content, reply_to_message_id, persona) {
Ok(posted) => Ok(posted),
Err(error) if is_stale_webhook_error(&error) => {
clear_cached_persona_webhook(&cache_path, &target.webhook_channel_id)?;
let refreshed = create_persona_webhook(token, &target.webhook_channel_id)?;
write_cached_persona_webhook(&cache_path, &target.webhook_channel_id, &refreshed)?;
execute_persona_webhook(&refreshed, &target, content, reply_to_message_id, persona)
}
Err(error) => Err(error),
}
}
#[derive(Clone, Debug)]
struct WebhookTarget {
webhook_channel_id: String,
thread_id: Option<String>,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct CachedWebhookRecord {
id: String,
token: String,
channel_id: String,
name: String,
created_at: String,
}
fn resolve_webhook_target(token: &str, channel_id: &str) -> Result<WebhookTarget> {
let response = Client::new()
.get(format!("{DISCORD_API}/channels/{channel_id}"))
.header("Authorization", format!("Bot {token}"))
.header("User-Agent", "EpiphanyFace/0.1")
.send()
.context("Discord channel lookup failed")?;
let payload = decode_discord_json(response, "Discord channel lookup")?;
let channel_type = payload["type"]
.as_i64()
.ok_or_else(|| anyhow!("Discord channel lookup returned no numeric type"))?;
let id = required_discord_id(&payload, "Discord channel lookup")?;
if matches!(channel_type, 10 | 11 | 12) {
let parent_id = payload["parent_id"].as_str().ok_or_else(|| {
anyhow!("Discord thread {id} has no parent channel for webhook routing")
})?;
return Ok(WebhookTarget {
webhook_channel_id: parent_id.to_string(),
thread_id: Some(id),
});
}
Ok(WebhookTarget {
webhook_channel_id: id,
thread_id: None,
})
}
fn create_persona_webhook(token: &str, channel_id: &str) -> Result<CachedWebhookRecord> {
let response = Client::new()
.post(format!("{DISCORD_API}/channels/{channel_id}/webhooks"))
.header("Authorization", format!("Bot {token}"))
.header("User-Agent", "EpiphanyFace/0.1")
.json(&serde_json::json!({"name": "Epiphany Persona Pipe"}))
.send()
.context("Discord webhook creation failed")?;
let payload = decode_discord_json(response, "Discord webhook creation")?;
let id = required_discord_id(&payload, "Discord webhook creation")?;
let token = payload["token"]
.as_str()
.ok_or_else(|| anyhow!("Discord webhook creation returned no executable token"))?;
Ok(CachedWebhookRecord {
id,
token: token.to_string(),
channel_id: channel_id.to_string(),
name: "Epiphany Persona Pipe".to_string(),
created_at: now_iso(),
})
}
fn execute_persona_webhook(
webhook: &CachedWebhookRecord,
target: &WebhookTarget,
content: &str,
reply_to_message_id: Option<&str>,
persona: &FacePersona,
) -> Result<PostedDiscordMessage> {
let mut url = format!(
"{DISCORD_API}/webhooks/{}/{}?wait=true",
webhook.id, webhook.token
);
if let Some(thread_id) = &target.thread_id {
url.push_str("&thread_id=");
url.push_str(thread_id);
}
let response = Client::new()
.post(url)
.header("User-Agent", "EpiphanyFace/0.1")
.json(&serde_json::json!({
"content": content,
"username": persona.name,
"avatar_url": persona.avatar_url,
"message_reference": reply_to_message_id.map(|message_id| serde_json::json!({
"message_id": message_id,
"fail_if_not_exists": false,
})),
"allowed_mentions": {"parse": []},
}))
.send()
.context("Discord webhook execution failed")?;
let payload = decode_discord_json(response, "Discord webhook execution")?;
Ok(PostedDiscordMessage {
message_id: required_discord_id(&payload, "Discord webhook execution")?,
transport: "webhook",
})
}
fn run_smoke() -> Result<Value> {
let temp_dir = scoped_temp_dir("epiphany-face-discord-smoke")?;
let config = FaceConfig {
@ -223,6 +450,9 @@ fn run_smoke() -> Result<Value> {
allowed_channel_id: None,
allowed_channel_id_env: Some("EPIPHANY_FACE_AQUARIUM_CHANNEL_ID_TEST".to_string()),
bot_token_env: Some("DISCORD_BOT_TOKEN_TEST".to_string()),
persona_name: Some("Smoke Face".to_string()),
persona_avatar_url: Some("https://example.invalid/face.png".to_string()),
webhook_cache_path: Some(temp_dir.join("webhook-cache.json")),
};
unsafe {
env::remove_var("EPIPHANY_FACE_AQUARIUM_CHANNEL_ID_TEST");
@ -246,6 +476,9 @@ fn run_smoke() -> Result<Value> {
&config,
&temp_dir,
None,
None,
None,
None,
)?;
unsafe {
env::set_var("EPIPHANY_FACE_AQUARIUM_CHANNEL_ID_TEST", "123");
@ -255,6 +488,9 @@ fn run_smoke() -> Result<Value> {
&config,
&temp_dir,
Some("456".to_string()),
Some("Wrong Face".to_string()),
None,
None,
)?;
let ok = draft["ok"] == true
&& bubble["ok"] == true
@ -289,6 +525,8 @@ fn write_draft(
"reason": reason,
"allowed_channel_name": if config.allowed_channel_name.is_empty() { "#aquarium" } else { &config.allowed_channel_name },
"allowed_channel_id": allowed_channel_id(config),
"persona_name": config.persona_name,
"persona_avatar_url": config.persona_avatar_url,
"content": content.trim(),
});
let path = artifact_dir.join(format!("face-chat-{}-{}.json", now_stamp(), short_id()));
@ -354,6 +592,87 @@ fn latest_face_artifacts(artifact_dir: &Path, limit: usize) -> Vec<Value> {
.collect()
}
fn persona_webhook_cache_path(config: &FaceConfig, artifact_dir: &Path) -> PathBuf {
config
.webhook_cache_path
.clone()
.unwrap_or_else(|| artifact_dir.join("discord-webhook-cache.json"))
}
fn cached_persona_webhook(path: &Path, channel_id: &str) -> Result<Option<CachedWebhookRecord>> {
let cache = read_persona_webhook_cache(path)?;
let Some(value) = cache.get(channel_id) else {
return Ok(None);
};
let record: CachedWebhookRecord = serde_json::from_value(value.clone())
.with_context(|| format!("cached persona webhook for channel {channel_id} is malformed"))?;
Ok((record.channel_id == channel_id).then_some(record))
}
fn read_persona_webhook_cache(path: &Path) -> Result<serde_json::Map<String, Value>> {
match fs::read_to_string(path) {
Ok(raw) => {
let value: Value = serde_json::from_str(strip_bom(&raw))
.with_context(|| format!("failed to decode {}", path.display()))?;
Ok(value.as_object().cloned().unwrap_or_default())
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(serde_json::Map::new()),
Err(error) => Err(error).with_context(|| format!("failed to read {}", path.display())),
}
}
fn write_cached_persona_webhook(
path: &Path,
channel_id: &str,
webhook: &CachedWebhookRecord,
) -> Result<()> {
let mut cache = read_persona_webhook_cache(path)?;
cache.insert(channel_id.to_string(), serde_json::to_value(webhook)?);
write_json(path, &Value::Object(cache))
}
fn clear_cached_persona_webhook(path: &Path, channel_id: &str) -> Result<()> {
let mut cache = read_persona_webhook_cache(path)?;
if cache.remove(channel_id).is_some() {
write_json(path, &Value::Object(cache))?;
}
Ok(())
}
fn decode_discord_json(response: reqwest::blocking::Response, context: &str) -> Result<Value> {
let status = response.status();
let body = response
.text()
.with_context(|| format!("{context} response body read failed"))?;
if !status.is_success() {
return Err(anyhow!("{context} failed with HTTP {status}: {body}"));
}
serde_json::from_str(&body).with_context(|| format!("{context} response was not JSON"))
}
fn required_discord_id(payload: &Value, context: &str) -> Result<String> {
payload["id"]
.as_str()
.map(str::to_string)
.ok_or_else(|| anyhow!("{context} returned no id"))
}
fn is_stale_webhook_error(error: &anyhow::Error) -> bool {
let message = error.to_string();
message.contains("Discord webhook execution failed with HTTP 401")
|| message.contains("Discord webhook execution failed with HTTP 404")
}
fn trim_optional(value: Option<String>) -> Option<String> {
value
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
}
fn strip_bom(value: &str) -> &str {
value.strip_prefix('\u{feff}').unwrap_or(value)
}
fn load_config(path: &Path) -> Result<FaceConfig> {
let raw =
fs::read_to_string(path).with_context(|| format!("failed to read {}", path.display()))?;
@ -377,6 +696,9 @@ fn load_config(path: &Path) -> Result<FaceConfig> {
.as_str()
.map(str::to_string),
bot_token_env: payload["bot_token_env"].as_str().map(str::to_string),
persona_name: payload["persona_name"].as_str().map(str::to_string),
persona_avatar_url: payload["persona_avatar_url"].as_str().map(str::to_string),
webhook_cache_path: payload["webhook_cache_path"].as_str().map(PathBuf::from),
});
}
Ok(FaceConfig {
@ -385,6 +707,9 @@ fn load_config(path: &Path) -> Result<FaceConfig> {
allowed_channel_id: toml_string(&raw, "allowed_channel_id"),
allowed_channel_id_env: toml_string(&raw, "allowed_channel_id_env"),
bot_token_env: toml_string(&raw, "bot_token_env"),
persona_name: toml_string(&raw, "persona_name"),
persona_avatar_url: toml_string(&raw, "persona_avatar_url"),
webhook_cache_path: toml_string(&raw, "webhook_cache_path").map(PathBuf::from),
})
}

View file

@ -241,8 +241,13 @@ fn run_status(args: &Args) -> Result<Value> {
"status": "ready",
"artifactDir": face_dir,
"latestArtifacts": latest_face.get("latestArtifacts").cloned().unwrap_or_else(|| json!([])),
"availableActions": ["faceBubble", "characterTurn"],
"availableActions": ["faceBubble", "characterTurn", "discordPersonaPost"],
});
let void_memory = native_json(
"epiphany-void-memory",
&["status", "--config", "state/void-memory.toml"],
)
.unwrap_or_else(|error| json!({"ok": false, "error": error.to_string()}));
let status = json!({
"threadId": thread_id,
"read": read,
@ -258,6 +263,7 @@ fn run_status(args: &Args) -> Result<Value> {
"coordinator": coordinator,
"heartbeat": heartbeat,
"face": face,
"voidMemory": void_memory,
});
Ok(sanitize_for_operator(status))
}

View file

@ -0,0 +1,620 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use postgres::NoTls;
use reqwest::blocking::Client;
use reqwest::blocking::ClientBuilder;
use reqwest::header::HeaderMap;
use reqwest::header::HeaderValue;
use serde::Deserialize;
use serde_json::Value;
use serde_json::json;
use std::env;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
const STATUS_SCHEMA_VERSION: &str = "epiphany.void_memory_status.v0";
const SEARCH_SCHEMA_VERSION: &str = "epiphany.void_memory_search.v0";
const CONTEXT_SCHEMA_VERSION: &str = "epiphany.void_message_context.v0";
const DEFAULT_CONFIG: &str = "state/void-memory.toml";
const MAX_LIMIT: usize = 20;
fn main() -> Result<()> {
let mut args = env::args().skip(1);
let Some(command) = args.next() else {
return usage();
};
let mut config_path = PathBuf::from(DEFAULT_CONFIG);
let mut query: Option<String> = None;
let mut message_id: Option<String> = None;
let mut limit = 5_usize;
let mut before = 4_usize;
let mut after = 4_usize;
let mut guild_id: Option<String> = None;
let mut channel_id: Option<String> = None;
let mut author_id: Option<String> = None;
let mut repo_name: Option<String> = None;
let mut path_prefix: Option<String> = None;
let mut language: Option<String> = None;
while let Some(arg) = args.next() {
match arg.as_str() {
"--config" => config_path = PathBuf::from(take(&mut args, "--config")?),
"--query" => query = Some(take(&mut args, "--query")?),
"--message-id" => message_id = Some(take(&mut args, "--message-id")?),
"--limit" => limit = take(&mut args, "--limit")?.parse()?,
"--before" => before = take(&mut args, "--before")?.parse()?,
"--after" => after = take(&mut args, "--after")?.parse()?,
"--guild-id" => guild_id = Some(take(&mut args, "--guild-id")?),
"--channel-id" => channel_id = Some(take(&mut args, "--channel-id")?),
"--author-id" => author_id = Some(take(&mut args, "--author-id")?),
"--repo-name" => repo_name = Some(take(&mut args, "--repo-name")?),
"--path-prefix" => path_prefix = Some(take(&mut args, "--path-prefix")?),
"--language" => language = Some(take(&mut args, "--language")?),
other => return Err(anyhow!("unknown argument {other:?}")),
}
}
limit = limit.clamp(1, MAX_LIMIT);
before = before.min(MAX_LIMIT);
after = after.min(MAX_LIMIT);
let config = BridgeConfig::load(&config_path)?;
let output = match command.as_str() {
"status" => run_status(&config),
"search-history" => run_search(
&config,
query.context("missing --query")?,
limit,
SearchCorpus::History {
guild_id,
channel_id,
author_id,
},
),
"search-sources" => run_search(
&config,
query.context("missing --query")?,
limit,
SearchCorpus::Source {
repo_name,
path_prefix,
language,
},
),
"message-context" => run_message_context(
&config,
message_id.context("missing --message-id")?,
before,
after,
),
"smoke" => run_smoke(),
_ => return usage(),
}?;
println!("{}", serde_json::to_string_pretty(&output)?);
Ok(())
}
#[derive(Clone, Debug)]
struct BridgeConfig {
database_dsn_env: Option<String>,
database_dsn: String,
qdrant_url: String,
qdrant_api_key_env: Option<String>,
qdrant_history_collection: String,
qdrant_source_collection: String,
qdrant_timeout_ms: u64,
ollama_base_url: String,
ollama_model: String,
ollama_timeout_ms: u64,
history_query_instruction: String,
source_query_instruction: String,
archive_path: PathBuf,
}
impl BridgeConfig {
fn load(path: &Path) -> Result<Self> {
let raw = fs::read_to_string(path)
.with_context(|| format!("failed to read {}", path.display()))?;
Ok(Self {
database_dsn_env: toml_string(&raw, "database_dsn_env"),
database_dsn: toml_string(&raw, "database_dsn")
.unwrap_or_else(|| "postgres://voidbot:voidbot@localhost:5432/voidbot".to_string()),
qdrant_url: normalize_base_url(
&toml_string(&raw, "qdrant_url")
.unwrap_or_else(|| "http://127.0.0.1:6333".to_string()),
),
qdrant_api_key_env: toml_string(&raw, "qdrant_api_key_env"),
qdrant_history_collection: toml_string(&raw, "qdrant_history_collection")
.unwrap_or_else(|| "voidbot_discord_history_chunks".to_string()),
qdrant_source_collection: toml_string(&raw, "qdrant_source_collection")
.unwrap_or_else(|| "voidbot_repository_source_chunks".to_string()),
qdrant_timeout_ms: toml_number(&raw, "qdrant_timeout_ms").unwrap_or(30000),
ollama_base_url: normalize_base_url(
&toml_string(&raw, "ollama_base_url")
.unwrap_or_else(|| "http://127.0.0.1:11434".to_string()),
),
ollama_model: toml_string(&raw, "ollama_model")
.unwrap_or_else(|| "qwen3-embedding:0.6b".to_string()),
ollama_timeout_ms: toml_number(&raw, "ollama_timeout_ms").unwrap_or(30000),
history_query_instruction: toml_string(&raw, "history_query_instruction")
.unwrap_or_else(|| "Given a Discord history question, retrieve relevant messages and discussion snippets that answer it.".to_string()),
source_query_instruction: toml_string(&raw, "source_query_instruction")
.unwrap_or_else(|| "Given a source-tree, codebase, or lore question, retrieve relevant files, code snippets, and lore passages that answer it.".to_string()),
archive_path: PathBuf::from(
toml_string(&raw, "archive_path")
.unwrap_or_else(|| r"E:\Projects\VoidBot\.voidbot\rag\messages.json".to_string()),
),
})
}
fn database_dsn(&self) -> String {
self.database_dsn_env
.as_ref()
.and_then(|name| env::var(name).ok())
.filter(|value| !value.trim().is_empty())
.unwrap_or_else(|| self.database_dsn.clone())
}
fn qdrant_api_key(&self) -> Option<String> {
self.qdrant_api_key_env
.as_ref()
.and_then(|name| env::var(name).ok())
.filter(|value| !value.trim().is_empty())
}
}
enum SearchCorpus {
History {
guild_id: Option<String>,
channel_id: Option<String>,
author_id: Option<String>,
},
Source {
repo_name: Option<String>,
path_prefix: Option<String>,
language: Option<String>,
},
}
fn run_status(config: &BridgeConfig) -> Result<Value> {
let postgres = postgres_status(config);
let qdrant = qdrant_status(config);
let archive = archive_status(&config.archive_path);
Ok(json!({
"schemaVersion": STATUS_SCHEMA_VERSION,
"ok": postgres["ok"].as_bool().unwrap_or(false)
|| qdrant["history"]["ok"].as_bool().unwrap_or(false)
|| archive["ok"].as_bool().unwrap_or(false),
"postgres": postgres,
"qdrant": qdrant,
"archive": archive,
"notes": [
"Void currently keeps raw Discord archives file-backed under .voidbot while Qdrant owns semantic history/source vectors.",
"Postgres is checked for live Void state organs: jobs, audit events, interaction memory, identity profiles, and rate limits."
],
}))
}
fn run_search(
config: &BridgeConfig,
query: String,
limit: usize,
corpus: SearchCorpus,
) -> Result<Value> {
let (collection, instruction, filter, corpus_name) = match corpus {
SearchCorpus::History {
guild_id,
channel_id,
author_id,
} => (
config.qdrant_history_collection.as_str(),
config.history_query_instruction.as_str(),
qdrant_filter([
("corpusKind", Some("discord_history".to_string())),
("guildId", guild_id),
("channelId", channel_id),
("authorId", author_id),
]),
"discord_history",
),
SearchCorpus::Source {
repo_name,
path_prefix,
language,
} => (
config.qdrant_source_collection.as_str(),
config.source_query_instruction.as_str(),
qdrant_filter([
("corpusKind", Some("repository_source".to_string())),
("repoName", repo_name),
("pathPrefixes", path_prefix.map(normalize_path_prefix)),
("language", language),
]),
"repository_source",
),
};
let vector = embed_query(config, instruction, &query)?;
let hits = query_qdrant(config, collection, &vector, limit, filter)?;
Ok(json!({
"schemaVersion": SEARCH_SCHEMA_VERSION,
"ok": true,
"corpus": corpus_name,
"query": query,
"collection": collection,
"results": hits,
}))
}
fn run_message_context(
config: &BridgeConfig,
message_id: String,
before: usize,
after: usize,
) -> Result<Value> {
let archive = load_archive(&config.archive_path)?;
let Some(anchor) = archive
.messages
.iter()
.find(|message| message.id == message_id)
else {
return Ok(json!({
"schemaVersion": CONTEXT_SCHEMA_VERSION,
"ok": false,
"reason": "message-not-found",
"messageId": message_id,
}));
};
let mut messages = archive
.messages
.iter()
.filter(|message| !message.deleted())
.filter(|message| belongs_to_same_conversation(message, anchor))
.cloned()
.collect::<Vec<_>>();
messages.sort_by(|left, right| left.timestamp.cmp(&right.timestamp));
let anchor_index = messages
.iter()
.position(|message| message.id == message_id)
.context("anchor disappeared from context set")?;
let start = anchor_index.saturating_sub(before);
let end = (anchor_index + after + 1).min(messages.len());
Ok(json!({
"schemaVersion": CONTEXT_SCHEMA_VERSION,
"ok": true,
"messageId": message_id,
"archivePath": config.archive_path,
"messages": messages[start..end].iter().map(format_message).collect::<Vec<_>>(),
}))
}
fn postgres_status(config: &BridgeConfig) -> Value {
match postgres::Client::connect(&config.database_dsn(), NoTls) {
Ok(mut client) => {
let tables = [
"jobs",
"audit_events",
"interaction_memory_events",
"interaction_identity_profiles",
"void_usage_rate_limit_state",
];
let counts = tables
.into_iter()
.map(|table| {
let count = client
.query_one(&format!("select count(*)::bigint from {table}"), &[])
.map(|row| row.get::<_, i64>(0));
(table, count)
})
.map(|(table, count)| match count {
Ok(count) => json!({"table": table, "ok": true, "count": count}),
Err(error) => json!({"table": table, "ok": false, "error": error.to_string()}),
})
.collect::<Vec<_>>();
json!({"ok": true, "dsn": redact_dsn(&config.database_dsn()), "tables": counts})
}
Err(error) => json!({
"ok": false,
"dsn": redact_dsn(&config.database_dsn()),
"error": error.to_string(),
}),
}
}
fn qdrant_status(config: &BridgeConfig) -> Value {
json!({
"url": config.qdrant_url,
"history": qdrant_collection_status(config, &config.qdrant_history_collection),
"source": qdrant_collection_status(config, &config.qdrant_source_collection),
})
}
fn qdrant_collection_status(config: &BridgeConfig, collection: &str) -> Value {
let client = qdrant_client(config);
match client
.get(format!("{}/collections/{collection}", config.qdrant_url))
.send()
{
Ok(response) => match decode_json(response) {
Ok(payload) => json!({
"ok": true,
"collection": collection,
"pointsCount": payload.pointer("/result/points_count"),
"vectorsCount": payload.pointer("/result/vectors_count"),
"status": payload.pointer("/result/status"),
}),
Err(error) => {
json!({"ok": false, "collection": collection, "error": error.to_string()})
}
},
Err(error) => json!({"ok": false, "collection": collection, "error": error.to_string()}),
}
}
fn archive_status(path: &Path) -> Value {
match load_archive(path) {
Ok(archive) => json!({
"ok": true,
"path": path,
"messageCount": archive.messages.len(),
"activeMessageCount": archive.messages.iter().filter(|message| !message.deleted()).count(),
}),
Err(error) => json!({"ok": false, "path": path, "error": error.to_string()}),
}
}
fn embed_query(config: &BridgeConfig, instruction: &str, query: &str) -> Result<Vec<f32>> {
let client = ClientBuilder::new()
.timeout(Duration::from_millis(config.ollama_timeout_ms))
.build()
.context("failed to build Ollama client")?;
let formatted = format!("Instruct: {instruction}\nQuery: {query}");
let response = client
.post(format!("{}/api/embed", config.ollama_base_url))
.json(&json!({"model": config.ollama_model, "input": [formatted]}))
.send()
.context("failed to contact Ollama embedding backend")?;
let payload = decode_json(response).context("failed to decode Ollama embedding response")?;
let embedding = payload["embeddings"]
.as_array()
.and_then(|items| items.first())
.and_then(Value::as_array)
.ok_or_else(|| anyhow!("Ollama embedding response did not include embeddings[0]"))?;
embedding
.iter()
.map(|value| {
value
.as_f64()
.map(|value| value as f32)
.ok_or_else(|| anyhow!("Ollama embedding included a non-number"))
})
.collect()
}
fn query_qdrant(
config: &BridgeConfig,
collection: &str,
vector: &[f32],
limit: usize,
filter: Option<Value>,
) -> Result<Vec<Value>> {
let response = qdrant_client(config)
.post(format!(
"{}/collections/{collection}/points/query",
config.qdrant_url
))
.json(&json!({
"query": vector,
"limit": limit,
"with_payload": true,
"with_vector": false,
"filter": filter,
}))
.send()
.with_context(|| format!("failed to query Qdrant collection {collection}"))?;
let payload = decode_json(response)?;
let points = payload
.pointer("/result/points")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
Ok(points.into_iter().filter_map(format_qdrant_point).collect())
}
fn format_qdrant_point(point: Value) -> Option<Value> {
let payload = point.get("payload")?;
Some(json!({
"score": point.get("score"),
"chunkId": payload.get("chunkId"),
"sourceId": payload.get("sourceId"),
"sourceKind": payload.get("sourceKind"),
"text": payload.get("text"),
"metadata": payload.get("metadata"),
}))
}
fn qdrant_client(config: &BridgeConfig) -> Client {
let mut headers = HeaderMap::new();
if let Some(api_key) = config.qdrant_api_key() {
if let Ok(value) = HeaderValue::from_str(&api_key) {
headers.insert("api-key", value);
}
}
ClientBuilder::new()
.timeout(Duration::from_millis(config.qdrant_timeout_ms))
.default_headers(headers)
.build()
.expect("Qdrant client should build")
}
fn qdrant_filter<const N: usize>(fields: [(&str, Option<String>); N]) -> Option<Value> {
let must = fields
.into_iter()
.filter_map(|(key, value)| {
let value = value?.trim().to_string();
(!value.is_empty()).then(|| json!({"key": key, "match": {"value": value}}))
})
.collect::<Vec<_>>();
(!must.is_empty()).then(|| json!({"must": must}))
}
#[derive(Clone, Debug, Deserialize)]
struct ArchiveStore {
messages: Vec<ArchivedMessage>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ArchivedMessage {
id: String,
guild_id: Option<String>,
channel_id: String,
author_id: String,
author_name: String,
content: String,
timestamp: String,
deleted_at: Option<String>,
thread_id: Option<String>,
metadata: Option<Value>,
}
impl ArchivedMessage {
fn deleted(&self) -> bool {
self.deleted_at
.as_deref()
.is_some_and(|value| !value.is_empty())
}
}
fn load_archive(path: &Path) -> Result<ArchiveStore> {
let raw =
fs::read_to_string(path).with_context(|| format!("failed to read {}", path.display()))?;
serde_json::from_str(&raw).with_context(|| format!("failed to decode {}", path.display()))
}
fn belongs_to_same_conversation(message: &ArchivedMessage, anchor: &ArchivedMessage) -> bool {
message.channel_id == anchor.channel_id && message.thread_id == anchor.thread_id
}
fn format_message(message: &ArchivedMessage) -> Value {
json!({
"id": message.id,
"timestamp": message.timestamp,
"authorId": message.author_id,
"authorName": message.author_name,
"guildId": message.guild_id,
"channelId": message.channel_id,
"threadId": message.thread_id,
"content": message.content,
"jumpUrl": message.metadata.as_ref().and_then(|metadata| metadata.get("jumpUrl")),
})
}
fn run_smoke() -> Result<Value> {
let dir = env::temp_dir().join(format!(
"epiphany-void-memory-smoke-{}",
uuid::Uuid::new_v4()
));
fs::create_dir_all(&dir)?;
let archive_path = dir.join("messages.json");
fs::write(
&archive_path,
serde_json::to_string_pretty(&json!({
"version": 1,
"messages": [
{"id":"1","guildId":"g","channelId":"c","authorId":"a","authorName":"A","content":"before","timestamp":"2026-05-06T00:00:00Z","threadId":"t","metadata":{"jumpUrl":"https://discord.invalid/1"}},
{"id":"2","guildId":"g","channelId":"c","authorId":"b","authorName":"B","content":"anchor","timestamp":"2026-05-06T00:01:00Z","threadId":"t","metadata":{"jumpUrl":"https://discord.invalid/2"}},
{"id":"3","guildId":"g","channelId":"c","authorId":"a","authorName":"A","content":"after","timestamp":"2026-05-06T00:02:00Z","threadId":"t","metadata":{"jumpUrl":"https://discord.invalid/3"}}
]
}))?,
)?;
let config = BridgeConfig {
database_dsn_env: None,
database_dsn: "postgres://voidbot:voidbot@localhost:5432/voidbot".to_string(),
qdrant_url: "http://127.0.0.1:1".to_string(),
qdrant_api_key_env: None,
qdrant_history_collection: "history".to_string(),
qdrant_source_collection: "source".to_string(),
qdrant_timeout_ms: 50,
ollama_base_url: "http://127.0.0.1:1".to_string(),
ollama_model: "qwen3-embedding:0.6b".to_string(),
ollama_timeout_ms: 50,
history_query_instruction: "history".to_string(),
source_query_instruction: "source".to_string(),
archive_path,
};
let context = run_message_context(&config, "2".to_string(), 1, 1)?;
let status = run_status(&config)?;
let _ = fs::remove_dir_all(&dir);
Ok(json!({
"ok": context["ok"] == true
&& context["messages"].as_array().is_some_and(|messages| messages.len() == 3),
"context": context,
"status": status,
}))
}
fn decode_json(response: reqwest::blocking::Response) -> Result<Value> {
let status = response.status();
let body = response.text().context("failed to read response body")?;
if !status.is_success() {
return Err(anyhow!("HTTP {status}: {body}"));
}
serde_json::from_str(&body).context("response was not JSON")
}
fn toml_string(raw: &str, key: &str) -> Option<String> {
raw.lines()
.map(str::trim)
.filter(|line| !line.starts_with('#'))
.find_map(|line| {
let (left, right) = line.split_once('=')?;
(left.trim() == key).then(|| parse_toml_string(right.trim()))?
})
}
fn parse_toml_string(value: &str) -> Option<String> {
value
.strip_prefix('"')
.and_then(|value| value.strip_suffix('"'))
.map(|value| value.replace("\\\\", "\\"))
}
fn toml_number(raw: &str, key: &str) -> Option<u64> {
raw.lines()
.map(str::trim)
.filter(|line| !line.starts_with('#'))
.find_map(|line| {
let (left, right) = line.split_once('=')?;
(left.trim() == key).then(|| right.trim().parse().ok())?
})
}
fn normalize_base_url(value: &str) -> String {
value.trim_end_matches('/').to_string()
}
fn normalize_path_prefix(value: String) -> String {
value.replace('\\', "/").trim_start_matches('/').to_string()
}
fn redact_dsn(dsn: &str) -> String {
if let Some((prefix, rest)) = dsn.split_once("://") {
if let Some(at) = rest.find('@') {
return format!("{prefix}://***@{}", &rest[at + 1..]);
}
}
dsn.to_string()
}
fn take(args: &mut impl Iterator<Item = String>, name: &str) -> Result<String> {
args.next()
.ok_or_else(|| anyhow!("{name} requires a value"))
}
fn usage() -> Result<()> {
Err(anyhow!(
"usage: epiphany-void-memory <status|search-history|search-sources|message-context|smoke> [--config <path>] [--query <text>] [--message-id <id>] [--limit <n>]"
))
}