Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion .claude/rules/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,34 @@ paths:
---
# Database Rules

Dual-backend persistence: PostgreSQL + libSQL/Turso. **All new persistence features must support both backends.**
## Status & Direction

The repo is migrating off per-crate `Store`/`Repository` traits onto a
single universal `RootFilesystem` mount table (`crates/ironclaw_filesystem/`).
Under the new model, every persistence concern is a mount path
(`/system/secrets`, `/system/processes`, `/engine/threads`, …) backed by
exactly one `RootFilesystem` implementation — typed stores become thin
wrappers around `ScopedFilesystem` and own no backend dispatch of their
own. See `crates/ironclaw_filesystem/CLAUDE.md` and the
`2026-05-14-universal-fs-dispatch.md` plan/ADR.

**New persistence features go on `ScopedFilesystem`, not into `src/db/`.**
The rules below cover the *legacy* per-crate dual-backend pattern that
still exists in `src/db/`, `src/history/`, and `migrations/`. Touch them
only when fixing or extending code that already lives there; do not add
new sub-traits or per-domain backends.

This file is `paths`-scoped to those legacy directories so the rule
loads when (and only when) you're inside them. New code under
`crates/ironclaw_filesystem/`, consumer crates routing through it, or
any new mount-backed store should follow the unified-surface contract
in `crates/ironclaw_filesystem/CLAUDE.md` instead.

---

## Legacy: Dual-Backend Per-Crate Pattern

Dual-backend persistence: PostgreSQL + libSQL/Turso. **All new persistence features must support both backends.** *(Applies only inside the legacy directories scoped above. For new crates, mount through `RootFilesystem` and let the wiring layer pick the backend.)*

See `src/db/CLAUDE.md` for full schema, dialect differences, and libSQL limitations.

Expand Down
13 changes: 0 additions & 13 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[workspace]
members = [".", "crates/ironclaw_common", "crates/ironclaw_host_api", "crates/ironclaw_storage", "crates/ironclaw_filesystem", "crates/ironclaw_memory", "crates/ironclaw_events", "crates/ironclaw_event_projections", "crates/ironclaw_reborn_event_store", "crates/ironclaw_extensions", "crates/ironclaw_processes", "crates/ironclaw_dispatcher", "crates/ironclaw_scripts", "crates/ironclaw_mcp", "crates/ironclaw_wasm", "crates/ironclaw_capabilities", "crates/ironclaw_secrets", "crates/ironclaw_network", "crates/ironclaw_host_runtime", "crates/ironclaw_runtime_policy", "crates/ironclaw_authorization", "crates/ironclaw_run_state", "crates/ironclaw_approvals", "crates/ironclaw_resources", "crates/ironclaw_trust", "crates/ironclaw_turns", "crates/ironclaw_agent_loop", "crates/ironclaw_threads", "crates/ironclaw_loop_support", "crates/ironclaw_reborn", "crates/ironclaw_reborn_config", "crates/ironclaw_reborn_composition", "crates/ironclaw_reborn_cli", "crates/ironclaw_conversations", "crates/ironclaw_product_adapters", "crates/ironclaw_product_workflow", "crates/ironclaw_product_adapter_registry", "crates/ironclaw_wasm_product_adapters", "crates/ironclaw_telegram_v2_adapter", "crates/ironclaw_outbound", "crates/ironclaw_architecture", "crates/ironclaw_safety", "crates/ironclaw_skills", "crates/ironclaw_llm", "crates/ironclaw_engine", "crates/ironclaw_gateway", "crates/ironclaw_tui"]
members = [".", "crates/ironclaw_common", "crates/ironclaw_host_api", "crates/ironclaw_filesystem", "crates/ironclaw_memory", "crates/ironclaw_events", "crates/ironclaw_event_projections", "crates/ironclaw_reborn_event_store", "crates/ironclaw_extensions", "crates/ironclaw_processes", "crates/ironclaw_dispatcher", "crates/ironclaw_scripts", "crates/ironclaw_mcp", "crates/ironclaw_wasm", "crates/ironclaw_capabilities", "crates/ironclaw_secrets", "crates/ironclaw_network", "crates/ironclaw_host_runtime", "crates/ironclaw_runtime_policy", "crates/ironclaw_authorization", "crates/ironclaw_run_state", "crates/ironclaw_approvals", "crates/ironclaw_resources", "crates/ironclaw_trust", "crates/ironclaw_turns", "crates/ironclaw_agent_loop", "crates/ironclaw_threads", "crates/ironclaw_loop_support", "crates/ironclaw_reborn", "crates/ironclaw_reborn_config", "crates/ironclaw_reborn_composition", "crates/ironclaw_reborn_cli", "crates/ironclaw_conversations", "crates/ironclaw_product_adapters", "crates/ironclaw_product_workflow", "crates/ironclaw_product_adapter_registry", "crates/ironclaw_wasm_product_adapters", "crates/ironclaw_telegram_v2_adapter", "crates/ironclaw_outbound", "crates/ironclaw_architecture", "crates/ironclaw_safety", "crates/ironclaw_skills", "crates/ironclaw_llm", "crates/ironclaw_engine", "crates/ironclaw_gateway", "crates/ironclaw_tui"]
exclude = [
"channels-src/discord",
"channels-src/feishu",
Expand Down
50 changes: 4 additions & 46 deletions crates/ironclaw_architecture/tests/reborn_dependency_boundaries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -766,51 +766,6 @@ fn boundary_rules() -> Vec<BoundaryRule> {
"ironclaw_wasm_product_adapters",
],
},
BoundaryRule {
crate_name: "ironclaw_storage",
forbidden: vec![
"ironclaw",
"ironclaw_approvals",
"ironclaw_architecture",
"ironclaw_authorization",
"ironclaw_capabilities",
"ironclaw_common",
"ironclaw_conversations",
"ironclaw_dispatcher",
"ironclaw_engine",
"ironclaw_event_projections",
"ironclaw_events",
"ironclaw_extensions",
"ironclaw_filesystem",
"ironclaw_gateway",
"ironclaw_host_api",
"ironclaw_host_runtime",
"ironclaw_llm",
"ironclaw_loop_support",
"ironclaw_mcp",
"ironclaw_memory",
"ironclaw_network",
"ironclaw_outbound",
"ironclaw_processes",
"ironclaw_product_adapters",
"ironclaw_reborn",
"ironclaw_reborn_cli",
"ironclaw_reborn_config",
"ironclaw_reborn_event_store",
"ironclaw_resources",
"ironclaw_run_state",
"ironclaw_runtime_policy",
"ironclaw_safety",
"ironclaw_scripts",
"ironclaw_secrets",
"ironclaw_skills",
"ironclaw_threads",
"ironclaw_trust",
"ironclaw_tui",
"ironclaw_turns",
"ironclaw_wasm",
],
},
BoundaryRule {
crate_name: "ironclaw_reborn_config",
forbidden: vec![
Expand Down Expand Up @@ -1012,7 +967,10 @@ fn boundary_rules() -> Vec<BoundaryRule> {
"ironclaw_conversations",
"ironclaw_dispatcher",
"ironclaw_extensions",
"ironclaw_filesystem",
// ironclaw_filesystem is permitted: FilesystemOutboundStateStore
// routes outbound persistence through ScopedFilesystem under
// the universal-fs-dispatch rework (plan
// 2026-05-14-universal-fs-dispatch).
"ironclaw_gateway",
"ironclaw_host_runtime",
"ironclaw_mcp",
Expand Down
264 changes: 264 additions & 0 deletions crates/ironclaw_filesystem/src/hsm.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,264 @@
//! Placeholder HSM-style backend demonstrating the universal dispatch seam.
//!
//! `HsmBackend` is intentionally minimal: it shows what a backend looks like
//! when its storage primitives sit behind an external boundary (a hardware
//! security module, a TEE-resident KMS, an OS keychain). A production HSM
//! implementation would replace [`HsmBackend::new`] with constructors that
//! accept an HSM session handle and would route [`put`](RootFilesystem::put) /
//! [`get`](RootFilesystem::get) / [`delete`](RootFilesystem::delete) through
//! the HSM's encrypt/decrypt API.
//!
//! The point of having it in-tree is to prove that adding a new backend is a
//! single-file change. The seam this demonstrates:
//!
//! 1. **One trait.** `HsmBackend` implements `RootFilesystem` and nothing
//! else; the composite dispatcher routes through it like any other mount.
//! 2. **Declared capabilities.** The HSM exposes only the encrypted-bytes
//! surface (`Read` / `Write` / `Stat` / `Delete`) — no records, no query,
//! no index, no events, no transactions. `BackendCapabilities` advertises
//! that up front; `CompositeRootFilesystem::mount_dyn` then refuses any
//! `MountDescriptor` that claims more than the HSM delivers
//! (`FilesystemError::DescriptorOverclaims`). Consumers cannot accidentally
//! attach a query-requiring store onto an HSM mount.
//! 3. **Swap by wiring, not by consumer edits.** A consumer that holds a
//! `ScopedFilesystem` bound to `/system/secrets` does not change when the
//! mount swaps from `LibSqlRootFilesystem` to `HsmBackend` — only the
//! `mount()` call at startup changes.
//!
//! The placeholder stores ciphertext in process memory so the trait can be
//! exercised end-to-end in tests. It is not a security boundary. Real HSM
//! backends are sealed behind external infrastructure.

use async_trait::async_trait;
use ironclaw_host_api::VirtualPath;

use crate::in_memory::InMemoryBackend;
use crate::{
BackendCapabilities, Capability, CasExpectation, DirEntry, Entry, FileStat, FilesystemError,
FilesystemOperation, RecordVersion, RootFilesystem, TxnCapability, VersionedEntry,
};

/// Placeholder HSM-style backend. See the module-level docs.
pub struct HsmBackend {
inner: InMemoryBackend,
}

impl HsmBackend {
pub fn new() -> Self {
Self {
inner: InMemoryBackend::new(),
}
}

fn declared_capabilities() -> BackendCapabilities {
BackendCapabilities::empty()
.with(Capability::Read)
.with(Capability::Write)
.with(Capability::Stat)
.with(Capability::Delete)
.with_txn(TxnCapability::Cas)
}
Comment on lines +53 to +60

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The HsmBackend implements list_dir by delegating to the inner backend, but it does not declare Capability::List in its capabilities. While the legacy capability plane is currently descriptor-driven for validation, new backends should accurately advertise their supported operations for consistency and future-proofing.

    fn declared_capabilities() -> BackendCapabilities {
        BackendCapabilities::empty()
            .with(Capability::Read)
            .with(Capability::Write)
            .with(Capability::List)
            .with(Capability::Stat)
            .with(Capability::Delete)
            .with_txn(TxnCapability::Cas)
    }
References
  1. Capabilities should be handled consistently across all capability kinds and accurately advertised on all surfaces.

}

impl Default for HsmBackend {
fn default() -> Self {
Self::new()
}
}

#[async_trait]
impl RootFilesystem for HsmBackend {
fn capabilities(&self) -> BackendCapabilities {
Self::declared_capabilities()
}

async fn put(
&self,
path: &VirtualPath,
entry: Entry,
cas: CasExpectation,
) -> Result<RecordVersion, FilesystemError> {
if entry.kind.is_some() || !entry.indexed.is_empty() {
return Err(FilesystemError::Unsupported {
path: path.clone(),
operation: FilesystemOperation::WriteFile,
});
}
self.inner.put(path, entry, cas).await
}

async fn get(&self, path: &VirtualPath) -> Result<Option<VersionedEntry>, FilesystemError> {
self.inner.get(path).await
}

async fn list_dir(&self, path: &VirtualPath) -> Result<Vec<DirEntry>, FilesystemError> {
self.inner.list_dir(path).await
}

async fn stat(&self, path: &VirtualPath) -> Result<FileStat, FilesystemError> {
self.inner.stat(path).await
}

async fn delete(&self, path: &VirtualPath) -> Result<(), FilesystemError> {
self.inner.delete(path).await
}
}

#[cfg(test)]
mod tests {
use std::sync::Arc;

use ironclaw_host_api::VirtualPath;

use crate::{
BackendCapabilities, BackendId, BackendKind, Capability, CasExpectation,
CompositeRootFilesystem, ContentKind, Entry, FilesystemError, IndexKey, IndexKind,
IndexName, IndexPolicy, IndexSpec, IndexValue, MountDescriptor, RootFilesystem,
StorageClass, TxnCapability,
};

use super::HsmBackend;

fn vpath(value: &str) -> VirtualPath {
VirtualPath::new(value).unwrap()
}

fn hsm_descriptor(capabilities: BackendCapabilities) -> MountDescriptor {
MountDescriptor {
virtual_root: vpath("/secrets"),
backend_id: BackendId::new("hsm-secrets").unwrap(),
backend_kind: BackendKind::Custom("hsm".into()),
storage_class: StorageClass::FileContent,
content_kind: ContentKind::SystemState,
index_policy: IndexPolicy::NotIndexed,
capabilities,
}
}

#[tokio::test]
async fn hsm_supports_encrypted_bytes_round_trip() {
let hsm = HsmBackend::new();
let path = vpath("/secrets/account/api-key");

let version = hsm
.put(
&path,
Entry::bytes(b"ciphertext-blob".to_vec()),
CasExpectation::Absent,
)
.await
.unwrap();

let read_back = hsm.get(&path).await.unwrap().expect("entry present");
assert_eq!(read_back.entry.body, b"ciphertext-blob");
assert_eq!(read_back.version, version);
}

#[tokio::test]
async fn hsm_rejects_structured_records() {
let hsm = HsmBackend::new();
let path = vpath("/secrets/account/api-key");
let entry = Entry::record(
crate::RecordKind::new("credential_lease").unwrap(),
&serde_json::json!({"scope": "team"}),
)
.unwrap();

let err = hsm
.put(&path, entry, CasExpectation::Any)
.await
.unwrap_err();
assert!(matches!(err, FilesystemError::Unsupported { .. }));
}

#[tokio::test]
async fn hsm_rejects_query_and_index_ops() {
let hsm = HsmBackend::new();
let path = vpath("/secrets");

let query_err = hsm
.query(&path, &crate::Filter::All, crate::Page::new(0, 10))
.await
.unwrap_err();
assert!(matches!(query_err, FilesystemError::Unsupported { .. }));

let spec = IndexSpec::new(
IndexName::new("by_scope").unwrap(),
vec![IndexKey::new("scope").unwrap()],
IndexKind::Exact,
);
let index_err = hsm.ensure_index(&path, &spec).await.unwrap_err();
assert!(matches!(index_err, FilesystemError::Unsupported { .. }));
}

#[tokio::test]
async fn composite_rejects_overclaimed_hsm_descriptor() {
let mut composite = CompositeRootFilesystem::new();
let over_claimed = BackendCapabilities::empty()
.with(Capability::Read)
.with(Capability::Write)
.with(Capability::Stat)
.with(Capability::Delete)
.with(Capability::Query)
.with(Capability::IndexExact);

let err = composite
.mount_dyn(hsm_descriptor(over_claimed), Arc::new(HsmBackend::new()))
.unwrap_err();

match err {
FilesystemError::DescriptorOverclaims { missing, .. } => {
assert!(missing.contains(&Capability::Query));
assert!(missing.contains(&Capability::IndexExact));
}
other => panic!("expected DescriptorOverclaims, got {other:?}"),
}
}

#[tokio::test]
async fn composite_routes_to_hsm_under_secrets_mount() {
// Demonstrates the swap-by-wiring acceptance gate: a /secrets mount
// can point at HsmBackend with no consumer changes. Consumer code
// sees the same RootFilesystem trait — capability validation at
// mount time ensures the descriptor never over-claims.
let mut composite = CompositeRootFilesystem::new();
let honest_descriptor = hsm_descriptor(
BackendCapabilities::empty()
.with(Capability::Read)
.with(Capability::Write)
.with(Capability::Stat)
.with(Capability::Delete)
.with_txn(TxnCapability::Cas),
);
composite
.mount_dyn(honest_descriptor, Arc::new(HsmBackend::new()))
.unwrap();

let path = vpath("/secrets/account/key");
composite
.put(
&path,
Entry::bytes(b"ciphertext".to_vec()),
CasExpectation::Absent,
)
.await
.unwrap();

// Read back via the composite — same surface the consumer would use.
let read = composite.get(&path).await.unwrap().expect("entry present");
assert_eq!(read.entry.body, b"ciphertext");

// Indexed values are still rejected because the HSM declared no
// index/query capability — even though the consumer code path
// didn't change.
let with_index = Entry::bytes(b"more".to_vec()).with_indexed(
IndexKey::new("scope").unwrap(),
IndexValue::Text("team".into()),
);
let err = composite
.put(&path, with_index, CasExpectation::Any)
.await
.unwrap_err();
assert!(matches!(err, FilesystemError::Unsupported { .. }));
}
}
Loading
Loading