memoryd: the crate, memoryd.toml, and listening on a socket

Implemented-By: OpenCode session (model recorded in docs/implementer-log.md)
This commit is contained in:
2026-09-25 16:41:44 -07:00
committed by kyle
parent 964bd99b12
commit b84b9af540
14 changed files with 657 additions and 2 deletions
+140
View File
@@ -0,0 +1,140 @@
//! `memoryd` configuration: read `memoryd.toml` into a typed `Config` (M5a spec, section 11).
//!
//! Unknown keys are errors in every table, as in the other roles: a misspelt key that silently
//! fell back to its default would be a setting the owner believes is set and is not.
use std::path::{Path, PathBuf};
use proto::DataClass;
use serde::Deserialize;
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct Paths {
pub home: PathBuf,
}
impl Default for Paths {
fn default() -> Self {
Self {
home: std::env::var_os("BOXMAKER_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("/var/lib/boxmaker")),
}
}
}
/// `[memory]`: the starter `soul.md`, and whether identity writes wait for the owner.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct Memory {
/// A relative path is resolved next to the config file by `Config::load`.
pub soul_starter: PathBuf,
pub review: bool,
}
impl Default for Memory {
fn default() -> Self {
Self {
soul_starter: PathBuf::from("soul.md"),
review: false,
}
}
}
/// `[index]`: records above `max_class` are not indexed.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct Index {
pub max_class: DataClass,
}
impl Default for Index {
fn default() -> Self {
Self {
max_class: DataClass::Private,
}
}
}
/// An empty path means "the default under `home`".
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(deny_unknown_fields, default)]
pub struct Sockets {
#[serde(rename = "loop")]
pub loopd: PathBuf,
pub broker: PathBuf,
pub admin: PathBuf,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(deny_unknown_fields, default)]
pub struct Config {
pub paths: Paths,
pub memory: Memory,
pub index: Index,
pub sockets: Sockets,
}
#[derive(Debug)]
pub enum ConfigError {
Read(PathBuf, std::io::Error),
Parse(PathBuf, toml::de::Error),
}
impl std::fmt::Display for ConfigError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
ConfigError::Read(path, err) => write!(f, "{}: {err}", path.display()),
ConfigError::Parse(path, err) => write!(f, "{}: {err}", path.display()),
}
}
}
impl std::error::Error for ConfigError {}
impl Config {
pub fn parse(text: &str) -> Result<Config, toml::de::Error> {
toml::from_str(text)
}
/// Read and parse `path`; a relative `soul_starter` is taken to be next to it.
pub fn load(path: &Path) -> Result<Config, ConfigError> {
let text =
std::fs::read_to_string(path).map_err(|e| ConfigError::Read(path.to_path_buf(), e))?;
let mut config =
Config::parse(&text).map_err(|e| ConfigError::Parse(path.to_path_buf(), e))?;
if config.memory.soul_starter.is_relative() {
let base = path.parent().unwrap_or_else(|| Path::new("."));
config.memory.soul_starter = base.join(&config.memory.soul_starter);
}
Ok(config)
}
fn socket(&self, set: &Path, default: &str) -> PathBuf {
if set.as_os_str().is_empty() {
self.paths.home.join(default)
} else {
set.to_path_buf()
}
}
pub fn loop_socket(&self) -> PathBuf {
self.socket(&self.sockets.loopd, "run/loop-memory/memory.sock")
}
pub fn broker_socket(&self) -> PathBuf {
self.socket(&self.sockets.broker, "run/broker-memory/memory.sock")
}
pub fn admin_socket(&self) -> PathBuf {
self.socket(&self.sockets.admin, "run/owner-memory/admin.sock")
}
pub fn memory_dir(&self) -> PathBuf {
self.paths.home.join("memory")
}
pub fn index_path(&self) -> PathBuf {
self.paths.home.join("index/memory.sqlite3")
}
pub fn sessions_dir(&self) -> PathBuf {
self.paths.home.join("sessions")
}
}
+4
View File
@@ -0,0 +1,4 @@
//! The memory role: the memory files, their index, and every memory tool call (M5a spec).
pub mod config;
pub mod socket;
+33
View File
@@ -0,0 +1,33 @@
//! `memoryd serve --config <path>`.
use std::ffi::OsString;
use std::path::PathBuf;
use std::process::ExitCode;
const USAGE: &str = "usage: memoryd serve --config <path>";
fn main() -> ExitCode {
let args: Vec<OsString> = std::env::args_os().skip(1).collect();
let Some(config) = parse(&args) else {
eprintln!("{USAGE}");
return ExitCode::from(2);
};
match memoryd::config::Config::load(&config) {
Ok(_) => {
eprintln!("memoryd: not implemented");
ExitCode::from(2)
}
Err(e) => {
eprintln!("memoryd: {e}\nsee docs/runbook.md#memoryd-start-failed");
ExitCode::from(1)
}
}
}
/// The config path of `serve --config <path>`, or `None` for any other list.
fn parse(args: &[OsString]) -> Option<PathBuf> {
match args {
[serve, flag, path] if serve == "serve" && flag == "--config" => Some(PathBuf::from(path)),
_ => None,
}
}
+60
View File
@@ -0,0 +1,60 @@
//! Listening on a Unix socket: the directory at 0700, a stale socket removed, the socket at 0600
//! (M5a spec, section 7). The same steps as `brokerd`'s; no crate depends on another role's.
use std::fs::{DirBuilder, Permissions};
use std::io;
use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
use std::os::unix::net::UnixListener;
use std::path::Path;
/// Bind one socket: prepare its directory at 0700, make it private, remove any stale socket,
/// bind, then make the socket itself private at 0600. The error names the path.
pub fn listen(socket: &Path) -> Result<UnixListener, String> {
// A socket needs a directory of its own: step 2 makes that directory 0700, which must never
// be `/` or a shared directory reached through a symbolic link.
let dir = match socket.parent() {
Some(parent) if parent.parent().is_some() && !parent.as_os_str().is_empty() => {
parent.to_path_buf()
}
_ => {
return Err(format!(
"{}: a socket needs a directory of its own, not / or none",
socket.display()
));
}
};
// 1. The directory, at 0700.
DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(&dir)
.map_err(|e| format!("{}: {e}", dir.display()))?;
// `set_permissions` follows a symbolic link, so a link would make the directory it points to
// private instead: refuse it.
let kind = std::fs::symlink_metadata(&dir)
.map_err(|e| format!("{}: {e}", dir.display()))?
.file_type();
if !kind.is_dir() {
return Err(format!(
"{}: is a symbolic link or not a directory; memoryd will not change its mode",
dir.display()
));
}
// 2. Make it private, always, even when it was already there at 0755.
std::fs::set_permissions(&dir, Permissions::from_mode(0o700))
.map_err(|e| format!("{}: {e}", dir.display()))?;
// 3. A stale socket is removed; a missing one is fine.
match std::fs::remove_file(socket) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(format!("{}: {e}", socket.display())),
}
// 4. Bind, then 5. make the socket private.
let listener = UnixListener::bind(socket).map_err(|e| format!("{}: {e}", socket.display()))?;
std::fs::set_permissions(socket, Permissions::from_mode(0o600))
.map_err(|e| format!("{}: {e}", socket.display()))?;
Ok(listener)
}