diff --git a/.agentive-remediation/arena-gap-analysis.md b/.agentive-remediation/arena-gap-analysis.md new file mode 100644 index 0000000..5e8cd38 --- /dev/null +++ b/.agentive-remediation/arena-gap-analysis.md @@ -0,0 +1,730 @@ +# Arena Simulation: Critical Gap Analysis + +**Analyst:** BurntSushi (Rust Quality Engineer) +**Date:** 2026-02-01 +**Subject:** Production Readiness Assessment of stemedb-sim Arena Tests + +--- + +## Executive Summary + +The Arena simulation tests fundamental write→read paths through the system, but exhibits **significant gaps** between simulation coverage and real-world production scenarios. While the simulation successfully validates basic pipeline connectivity, it provides a **false sense of security** regarding system robustness. + +**Production Readiness Score: 58/100** + +| Category | Score | Status | +|----------|-------|--------| +| Basic Integration Coverage | 85/100 | ✅ Good | +| Failure Mode Testing | 30/100 | ❌ Critical Gap | +| Performance Validation | 20/100 | ❌ Critical Gap | +| API Integration | 0/100 | ❌ Not Tested | +| Concurrency Testing | 15/100 | ❌ Critical Gap | + +--- + +## What's Actually Being Tested + +### Arena 0: Spine (WAL → Ingestor → KVStore) + +**Code Path Exercised:** +``` +Agent.sign_assertion() → write_assertion_to_wal() → Journal.append() + → IngestWorker.step() → IngestWorker.ingest_assertion() + → SledStore.put() → IndexStore.add_to_indexes() +``` + +**What Works:** +- ✅ Basic serialization round-trip (`serialize_assertion` → `deserialize`) +- ✅ Ed25519 signature verification in `IngestWorker.verify_assertion_signatures()` +- ✅ Content-addressed storage (`H:{blake3_hash}`) +- ✅ Subject index updates (`S:{subject}`) +- ✅ Compound index updates (`SP:{subject}:{predicate}`) + +**Confidence Rating: 90%** — The simulation accurately tests the happy path for assertion ingestion. + +--- + +### Arena 1: Cortex (QueryEngine → Lenses) + +**Code Path Exercised:** +``` +QueryEngine.execute() → fetch_by_subject_predicate() + → RecencyLens.resolve() / VoteAwareConsensusLens.resolve_async() + → Resolution with winner selection +``` + +**What Works:** +- ✅ Query execution via compound index (`SP:{subject}:{predicate}`) +- ✅ Subject-only queries (`S:{subject}`) +- ✅ Lifecycle filtering in `Query.matches()` +- ✅ RecencyLens timestamp comparison +- ✅ Audit trail storage via `GenericAuditStore.put_audit()` + +**Confidence Rating: 85%** — Query path is tested, but lacks edge cases. + +--- + +### Arena 2: Voting & Consensus + +**Code Path Exercised:** +``` +Agent.vote() → write_vote_to_wal() → IngestWorker.ingest_vote() + → VoteStore.put_vote() → VoteStore cache updates (VC:{hash}, VW:{hash}) + → VoteAwareConsensusLens.resolve_async() → Aggregate weight ranking +``` + +**What Works:** +- ✅ Vote serialization/deserialization +- ✅ Vote storage at `V:{assertion_hash}:{vote_hash}` +- ✅ Vote count cache increments (`VC:{assertion_hash}`) +- ✅ Aggregate weight cache updates (`VW:{assertion_hash}`) +- ✅ Winner selection based on highest aggregate weight +- ✅ Tiebreaker by timestamp + +**Confidence Rating: 80%** — Vote mechanics work, but lacks adversarial testing. + +--- + +## Critical Gaps: What's NOT Being Tested + +### 1. Failure Modes (Severity: CRITICAL) + +**Missing:** +- ❌ WAL corruption mid-write (partial record) +- ❌ Sled crashes during `put()` (fsync failure) +- ❌ Network partition (if distributed) +- ❌ OOM conditions during large scans +- ❌ Disk full during ingestion +- ❌ Malformed rkyv archives (corrupted length fields) +- ❌ Hash collisions (theoretical but untested) + +**Why This Matters:** +The simulation calls `.expect()` on all storage operations, hiding errors: +```rust +// lib.rs:466 +match write_assertion_to_wal(&journal, &assertion).await { + Ok(raw_bytes) => { /* success path */ } + Err(e) => { + result.errors.push(SimulationError { /* logged but not replayed */ }); + } +} +``` + +**Problem:** Errors are collected but the simulation continues. No test verifies recovery behavior after failure. + +**Recommendation:** +Create `arena-3-chaos.rs` that: +- Kills IngestWorker mid-step, restarts, verifies cursor recovery +- Corrupts WAL records, verifies quarantine behavior +- Fills disk to 100%, verifies graceful degradation + +**Confidence Rating: 10%** — Failure mode coverage is nearly absent. + +--- + +### 2. Concurrency & Race Conditions (Severity: CRITICAL) + +**Missing:** +- ❌ Multiple IngestWorkers reading same WAL (race on cursor) +- ❌ Concurrent queries while ingestion is active +- ❌ Vote cache race conditions (VC/VW updates not atomic) +- ❌ Index corruption from concurrent writes +- ❌ Deadlock detection between Journal mutex and Store mutex + +**Why This Matters:** +The simulation is **strictly sequential**: +```rust +// lib.rs:458 - Arena 0 tick loop is single-threaded +for tick in 0..config.tick_count { + let agent = &agents[tick % agents.len()]; + let assertion = agent.sign_assertion(...); + match write_assertion_to_wal(&journal, &assertion).await { /* ... */ } +} +``` + +**Then waits 500ms:** +```rust +// lib.rs:486 +tokio::time::sleep(std::time::Duration::from_millis(config.ingestion_wait_ms)).await; +``` + +**Problem:** No concurrent writes, no overlapping ingestion, no parallel queries. + +**Real-World Scenario:** +- 1000 agents writing assertions simultaneously +- 10 queries executing while votes are being ingested +- Materializer updating MVs while QueryEngine reads them + +**Recommendation:** +```rust +// Spawn 100 concurrent writers +let handles: Vec<_> = (0..100).map(|i| { + let journal = journal.clone(); + tokio::spawn(async move { + for _ in 0..10 { + write_assertion_to_wal(&journal, &assertion).await?; + } + }) +}).collect(); + +futures::future::join_all(handles).await; +``` + +**Confidence Rating: 15%** — Concurrency testing is effectively zero. + +--- + +### 3. Performance Validation (Severity: HIGH) + +**Missing:** +- ❌ Throughput measurement (assertions/sec, votes/sec) +- ❌ Latency percentiles (p50, p99, p99.9) +- ❌ Memory allocation profiling +- ❌ Index scan performance under load +- ❌ VoteStore cache hit rate +- ❌ Materialized view staleness impact + +**Why This Matters:** +The simulation uses **hardcoded sleep timers**: +```rust +// lib.rs:486 +tokio::time::sleep(std::time::Duration::from_millis(config.ingestion_wait_ms)).await; +``` + +**Problem:** No verification that 500ms is sufficient. If ingestion lags, tests pass but assertions are missing. + +**Actual Check:** +```rust +// lib.rs:378 +assert!(result.is_success(), "Simulation should succeed: {:?}", result.errors); +assert_eq!(result.assertions_written, 14); +assert_eq!(result.assertions_verified, 10); // ⚠️ Only 10 of 14 verified! +``` + +**Wait, what?** The test writes 14 assertions but only verifies 10. The 4 extras are from Arena 2 (vote consensus/troll resistance), which are verified through lens resolution, not direct verification loop. + +**BUT:** This is fragile. If ingestion is slow, `assertions_verified` could be 0 and the test would fail for the wrong reason. + +**Recommendation:** +- Add `IngestWorker.wait_until_offset(target)` to block until ingestion catches up +- Measure ingestion lag: `current_offset - wal_tail_offset` +- Fail if lag exceeds threshold + +**Confidence Rating: 20%** — Performance is not measured, only assumed. + +--- + +### 4. API Integration (Severity: CRITICAL) + +**Missing:** +- ❌ HTTP API endpoints (`stemedb-api` crate is completely untested) +- ❌ JSON serialization/deserialization +- ❌ OpenAPI spec validation +- ❌ Rate limiting enforcement +- ❌ Authentication/authorization +- ❌ Quota enforcement + +**Why This Matters:** +The simulation tests **internal Rust APIs**: +```rust +// lib.rs:335 +async fn write_assertion_to_wal(journal: &Arc>, assertion: &Assertion) + -> Result, String> +``` + +**Real clients will use HTTP:** +```bash +curl -X POST http://localhost:8080/assertions \ + -H "Content-Type: application/json" \ + -d '{"subject": "Tesla", "predicate": "revenue", "object": 96.7}' +``` + +**Gap:** No test verifies: +- JSON schema compatibility +- HTTP error responses (400, 500) +- Content-Type negotiation +- CORS headers +- Request timeout handling + +**Recommendation:** +Create `tests/api_integration.rs`: +```rust +#[tokio::test] +async fn test_post_assertion_via_http() { + let app = stemedb_api::create_app(store).await; + let response = app + .oneshot(Request::builder() + .method("POST") + .uri("/assertions") + .header("content-type", "application/json") + .body(Body::from(r#"{"subject":"Tesla","predicate":"revenue"}"#)) + .unwrap()) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::CREATED); +} +``` + +**Confidence Rating: 0%** — API layer is completely untested. + +--- + +### 5. Edge Cases & Adversarial Inputs (Severity: HIGH) + +**Missing:** +- ❌ Subject/predicate strings with UTF-8 edge cases (e.g., emoji, RTL text, null bytes) +- ❌ Extremely long subject strings (DoS via memory exhaustion) +- ❌ Malicious signatures (wrong length, invalid curve points) +- ❌ Votes with negative weights (should be rejected) +- ❌ Assertions with `confidence > 1.0` or `< 0.0` +- ❌ Circular parent_hash references +- ❌ Timestamp overflow (year 2038 problem) + +**Why This Matters:** +The simulation creates **well-formed data**: +```rust +// lib.rs:459 +let agent = &agents[tick % agents.len()]; +let assertion = agent.sign_assertion( + &format!("Entity_{}", tick), // ⚠️ Always ASCII alphanumeric + "has_property", + ObjectValue::Text(format!("Value_{}", tick)), +); +``` + +**Real-World Inputs:** +- `subject: "🚗 Tesla\x00Inc"` (emoji + null byte) +- `subject: "a".repeat(1_000_000)` (1MB string, DoS) +- `weight: -999.9` (negative vote weight) +- `confidence: f32::NAN` (NaN value) + +**Current Code:** +```rust +// worker.rs:256 - Signature verification (GOOD) +if assertion.signatures.is_empty() { + return Err(IngestError::InvalidSignature("must have at least one signature".to_string())); +} +``` + +**But NO validation for:** +```rust +if assertion.subject.len() > MAX_SUBJECT_LEN { + return Err(IngestError::InvalidInput("subject too long")); +} +if assertion.confidence < 0.0 || assertion.confidence > 1.0 { + return Err(IngestError::InvalidInput("confidence out of range")); +} +``` + +**Recommendation:** +Add defensive validation in `IngestWorker::ingest_assertion()`: +```rust +const MAX_SUBJECT_LEN: usize = 1024; +const MAX_PREDICATE_LEN: usize = 1024; + +fn validate_assertion(a: &Assertion) -> Result<()> { + if a.subject.len() > MAX_SUBJECT_LEN { + return Err(IngestError::InvalidInput("subject too long".into())); + } + if a.confidence < 0.0 || a.confidence > 1.0 || a.confidence.is_nan() { + return Err(IngestError::InvalidInput("invalid confidence".into())); + } + // ... more checks + Ok(()) +} +``` + +**Confidence Rating: 25%** — Edge case coverage is minimal. + +--- + +### 6. Test Isolation (Severity: MEDIUM) + +**Current Approach:** +```rust +// lib.rs:401-405 +let temp_wal_dir = tempfile::tempdir().map_err(...)?; +let temp_db_dir = tempfile::tempdir().map_err(...)?; +``` + +**Problem:** Tests are isolated, but **not hermetic**. The simulation: +- Uses real filesystem I/O +- Uses real Ed25519 crypto (slow) +- Uses real sleep timers (flaky) + +**Impact on CI:** +- Tests are slow (500ms+ sleep per scenario) +- Tests can be flaky if disk is slow +- Parallel test execution may interfere (disk I/O contention) + +**Recommendation:** +- Mock `KVStore` trait for unit tests (use `HashMap` backend) +- Mock `Journal` for ingestion tests +- Use `tokio::time::pause()` to control time advancement + +**Confidence Rating: 70%** — Isolation is good, but not hermetic. + +--- + +## Specific File:Line Issues + +### `/Users/jordanwashburn/Workspace/orchard9/stemedb/crates/stemedb-sim/src/lib.rs` + +#### Line 97-111: `SimulationResult::is_success()` Logic Flaw +```rust +pub fn is_success(&self) -> bool { + self.errors.is_empty() + && self.recency_test_passed + && self.lifecycle_test_passed + && self.audit_test_passed + && self.vote_consensus_test_passed + && self.troll_resistance_test_passed +} +``` + +**Issue:** No check for `assertions_written == assertions_verified`. + +**Why:** Comment claims "Arena 2 tests write additional test assertions that are verified through the VoteAwareConsensusLens rather than the main verification loop." + +**Problem:** This is confusing and fragile. If ingestion fails silently, `assertions_verified` could be 0 but the test passes because `errors.is_empty()`. + +**Recommendation:** +```rust +pub fn is_success(&self) -> bool { + let base_assertions_verified = self.assertions_verified >= (self.tick_count as u64); + base_assertions_verified + && self.errors.is_empty() + && /* ... rest of checks */ +} +``` + +**Severity:** MEDIUM + +--- + +#### Line 279-281: Signature Message Format Mismatch Risk +```rust +// lib.rs:281 +let message = format!("{}:{}", subject, predicate); +let signature: Signature = self.signing_key.sign(message.as_bytes()); +``` + +**vs. worker.rs:268:** +```rust +// worker.rs:268 +let message = format!("{}:{}", assertion.subject, assertion.predicate); +``` + +**Issue:** The signed message format is **implicitly coupled** across files. If one changes (e.g., adding `|{timestamp}`), signatures break. + +**Recommendation:** +Extract to `stemedb-core/src/types.rs`: +```rust +impl Assertion { + pub fn signing_message(&self) -> String { + format!("{}:{}", self.subject, self.predicate) + } +} +``` + +**Severity:** MEDIUM + +--- + +#### Line 486: Hardcoded Sleep Timer +```rust +tokio::time::sleep(std::time::Duration::from_millis(config.ingestion_wait_ms)).await; +``` + +**Issue:** No verification that ingestion actually completed. If system is slow, test fails with "assertion not found" instead of "ingestion timeout". + +**Recommendation:** +```rust +async fn wait_for_ingestion(journal: &Journal, store: &impl KVStore, expected_count: usize) -> Result<(), String> { + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + loop { + let count = store.scan_prefix(b"H:").await?.len(); + if count >= expected_count { + return Ok(()); + } + if tokio::time::Instant::now() > deadline { + return Err(format!("Timeout: only {}/{} assertions ingested", count, expected_count)); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } +} +``` + +**Severity:** MEDIUM + +--- + +#### Line 696, 820, 1073, 1260: Duplicate `tokio::time::sleep()` Calls +**Pattern:** +```rust +tokio::time::sleep(std::time::Duration::from_millis(300)).await; +``` + +**Issue:** Magic number `300` repeated 4+ times. No justification for why 300ms is correct. + +**Recommendation:** +```rust +const INGESTION_SETTLE_TIME_MS: u64 = 300; +// ... then use: +tokio::time::sleep(Duration::from_millis(INGESTION_SETTLE_TIME_MS)).await; +``` + +**Severity:** LOW + +--- + +### `/Users/jordanwashburn/Workspace/orchard9/stemedb/crates/stemedb-ingest/src/worker.rs` + +#### Line 158-174: EOF Handling Ambiguity +```rust +let record = { + let journal = self.journal.lock().await; + match journal.read(self.current_offset) { + Ok(record) => record, + Err(stemedb_wal::QuarantineError::Io { .. }) => { + return Ok(0); // ⚠️ Assuming EOF + } + Err(stemedb_wal::QuarantineError::IoGeneric(e)) + if e.kind() == std::io::ErrorKind::UnexpectedEof => { + return Ok(0); // ⚠️ Assuming EOF + } + Err(e) => return Err(IngestError::Wal(e)), + } +}; +``` + +**Issue:** Both `QuarantineError::Io` and `UnexpectedEof` return `Ok(0)`, which means "no new data". But `QuarantineError::Io` could also mean: +- Disk read error +- Network mount failure +- Permission denied + +**Problem:** Transient I/O errors are silently ignored, treated as EOF. + +**Recommendation:** +```rust +Err(stemedb_wal::QuarantineError::Io { source, .. }) => { + if source.kind() == std::io::ErrorKind::UnexpectedEof { + return Ok(0); // True EOF + } + warn!(error = %source, "Transient I/O error, retrying"); + return Ok(0); // Retry on next tick +} +``` + +**Severity:** HIGH + +--- + +#### Line 191-192: Vote Count Cache Race Condition +```rust +// worker.rs:181-192 (in put_vote) +let current_count = match self.store.get(&count_key).await? { + Some(bytes) if bytes.len() == 8 => { + let arr: [u8; 8] = bytes.try_into().map_err(...)?; + u64::from_le_bytes(arr) + } + _ => 0, +}; +let new_count = current_count.saturating_add(1); +self.store.put(&count_key, &new_count.to_le_bytes()).await?; +``` + +**Issue:** This is a **read-modify-write** race. If two IngestWorkers call `put_vote` concurrently: +1. Worker A reads `count=5`, Worker B reads `count=5` +2. Worker A writes `count=6`, Worker B writes `count=6` +3. Final count is 6, but should be 7 (lost update) + +**Simulation doesn't test this** because IngestWorker runs sequentially. + +**Recommendation:** +Use a CAS (compare-and-swap) operation or atomic counter: +```rust +// Requires adding atomic counter support to KVStore trait +let new_count = self.store.increment_counter(&count_key, 1).await?; +``` + +**Severity:** CRITICAL (if multiple ingestors are ever deployed) + +--- + +### `/Users/jordanwashburn/Workspace/orchard9/stemedb/crates/stemedb-storage/src/vote_store.rs` + +#### Line 183-192: Same Race Condition as Above +**Same code, same issue.** VoteStore is used by IngestWorker, so this is the root cause. + +**Severity:** CRITICAL + +--- + +### `/Users/jordanwashburn/Workspace/orchard9/stemedb/crates/stemedb-lens/src/vote_aware_consensus.rs` + +#### Line 99-102: Defensive Empty Hash on Serialization Failure +```rust +fn compute_assertion_hash(assertion: &Assertion) -> Hash { + let bytes = match stemedb_core::serde::serialize(assertion) { + Ok(b) => b, + Err(_) => return [0u8; 32], // ⚠️ Silent failure + }; + *blake3::hash(&bytes).as_bytes() +} +``` + +**Issue:** If serialization fails, returns `[0u8; 32]` (all zeros). This could cause: +- All failures to hash to the same value +- Votes to be looked up at wrong key +- Silent data corruption + +**Recommendation:** +```rust +fn compute_assertion_hash(assertion: &Assertion) -> Result { + let bytes = stemedb_core::serde::serialize(assertion) + .map_err(|e| format!("Failed to serialize assertion: {}", e))?; + Ok(*blake3::hash(&bytes).as_bytes()) +} +``` + +Then propagate error up: +```rust +// line 134 +let assertion_hash = match Self::compute_assertion_hash(assertion) { + Ok(h) => h, + Err(e) => { + debug!(error = %e, "Failed to hash assertion, skipping"); + continue; + } +}; +``` + +**Severity:** HIGH + +--- + +### `/Users/jordanwashburn/Workspace/orchard9/stemedb/crates/stemedb-query/src/engine.rs` + +#### Line 117-159: Staleness Check Has Time Skew Risk +```rust +if let Some(max_stale) = query.max_stale { + let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + let age = now.saturating_sub(view.materialized_at); + + if age > max_stale { + debug!("Materialized view is stale, falling back to slow path"); + return Ok(None); + } +} +``` + +**Issue:** If server clock is set backwards, `now < view.materialized_at`, and `saturating_sub` returns 0, making all MVs appear fresh. + +**Recommendation:** +```rust +let age = match now.checked_sub(view.materialized_at) { + Some(age) => age, + None => { + warn!(now, materialized_at = view.materialized_at, + "Clock skew detected: MV timestamp is in the future, falling back"); + return Ok(None); // Reject future-dated MVs + } +}; +``` + +**Severity:** MEDIUM + +--- + +## Summary of Gaps by Severity + +| Severity | Count | Examples | +|----------|-------|----------| +| CRITICAL | 4 | Vote cache race, API untested, failure mode gaps, concurrency gaps | +| HIGH | 3 | EOF handling, defensive hash, edge case coverage | +| MEDIUM | 4 | Time skew, verification logic, signature coupling, hardcoded sleeps | +| LOW | 1 | Magic numbers | + +--- + +## Recommendations by Priority + +### Immediate (Before Production) + +1. **Fix vote cache race condition** (worker.rs:191, vote_store.rs:183) + - Use atomic counters or CAS operations + - Add concurrency test: 100 agents voting simultaneously + +2. **Add API integration tests** (missing entirely) + - Create `stemedb-api/tests/http_endpoints.rs` + - Test JSON serialization, error codes, rate limiting + +3. **Add failure mode tests** (missing entirely) + - Crash recovery: kill IngestWorker mid-step, verify cursor recovery + - WAL corruption: inject malformed record, verify quarantine + - Disk full: verify graceful degradation + +### Short-Term (Next Sprint) + +4. **Add concurrency stress test** + - 1000 agents writing assertions concurrently + - 100 queries running while ingestion is active + - Measure throughput and p99 latency + +5. **Add input validation** + - Max length checks on subject/predicate + - Confidence range validation (0.0 to 1.0) + - Weight validation (no negatives) + +6. **Fix defensive error handling** + - Replace `[0u8; 32]` fallback with proper error propagation (vote_aware_consensus.rs:102) + - Distinguish EOF from transient I/O errors (worker.rs:163) + +### Long-Term (Next Quarter) + +7. **Add performance benchmarks** + - Measure assertions/sec throughput + - Measure p50/p99/p99.9 latency + - Measure memory allocation per operation + +8. **Add property-based tests** + - Use `proptest` to generate random assertions + - Verify invariants: all writes are eventually readable, votes always increase counts + +9. **Add observability** + - Export metrics (assertions ingested, queries executed, cache hit rate) + - Add distributed tracing (OpenTelemetry) + +--- + +## Conclusion + +The Arena simulation successfully validates **basic integration** of the write and read paths. However, it provides a **false sense of confidence** because it: + +1. **Only tests happy paths** — no failures, no corruption, no adversarial inputs +2. **Only tests sequential execution** — no concurrency, no race conditions +3. **Only tests internal APIs** — HTTP layer is completely untested +4. **Only tests well-formed data** — no edge cases, no DoS attempts +5. **Uses hardcoded timers** — no verification of actual ingestion completion + +**Production Readiness: 58/100** + +To reach production readiness (90+), the system needs: +- Failure mode testing (crash recovery, corruption handling) +- Concurrency testing (race conditions, deadlocks) +- API integration testing (HTTP, JSON, error codes) +- Input validation (length limits, range checks) +- Performance benchmarks (throughput, latency) + +**Critical Blockers:** +1. Fix vote cache race condition (CRITICAL) +2. Add API integration tests (CRITICAL) +3. Add failure mode tests (CRITICAL) + +**Estimated Effort to 90/100:** 3-4 weeks with 1 engineer focused on testing. + +--- + +**BurntSushi's Verdict:** Ship the current codebase to a **closed beta** or **internal staging** environment, but **not to production**. The vote cache race alone could cause silent data corruption under load. Fix the critical issues first, then open to external users. diff --git a/.agentive-remediation/duplicate-tokio-deps/history.md b/.agentive-remediation/duplicate-tokio-deps/history.md new file mode 100644 index 0000000..5e08e35 --- /dev/null +++ b/.agentive-remediation/duplicate-tokio-deps/history.md @@ -0,0 +1,17 @@ +# duplicate-tokio-deps + +## AUDIT (2026-01-31) +Pattern: Duplicate tokio dependency entries and inconsistent version specs +Found: 1 duplicate entry (stemedb-query), 4 crates using "1.36" vs 2 using "1" + +## FIX (2026-01-31) +- [x] stemedb-query/Cargo.toml - Merged duplicate tokio (deps + dev-deps) into single entry with all features +- [x] stemedb-ingest/Cargo.toml - Normalized "1.36" → "1" +- [x] stemedb-storage/Cargo.toml - Normalized "1.36" → "1" +- [x] stemedb-sim/Cargo.toml - Normalized "1.36" → "1" + +## VERIFY (2026-01-31) +- grep for tokio in Cargo.toml: 6 entries, 0 duplicates, all version "1" ✅ +- cargo build --workspace: ✅ +- cargo clippy --workspace -- -D warnings: ✅ +- cargo test --workspace: 158 passed, 0 failed ✅ diff --git a/.agentive-remediation/duplicate-tokio-deps/state.yaml b/.agentive-remediation/duplicate-tokio-deps/state.yaml new file mode 100644 index 0000000..650d3b8 --- /dev/null +++ b/.agentive-remediation/duplicate-tokio-deps/state.yaml @@ -0,0 +1,9 @@ +task: duplicate-tokio-deps +created: 2026-01-31 +phase: COMPLETE +before_count: 2 +current_count: 0 +issues: + - "Duplicate tokio entry in stemedb-query/Cargo.toml (deps + dev-deps)" + - "Mixed tokio version specs across workspace (1 vs 1.36)" +resolution: "Merged duplicate, normalized all to version '1'" diff --git a/.agentive-remediation/lens-instrumentation/history.md b/.agentive-remediation/lens-instrumentation/history.md new file mode 100644 index 0000000..11278e7 --- /dev/null +++ b/.agentive-remediation/lens-instrumentation/history.md @@ -0,0 +1,56 @@ +# lens-instrumentation + +## AUDIT (2026-01-31) + +**Pattern:** Lens `resolve()` methods missing `#[instrument]` tracing spans +**Found:** 3 instances in 3 files + +| File | Method | Has `#[instrument]` | +|------|--------|---------------------| +| `recency.rs:24` | `RecencyLens::resolve()` | NO | +| `consensus.rs:34` | `ConsensusLens::resolve()` | NO | +| `confidence.rs:46` | `ConfidenceLens::resolve()` | NO | +| `vote_aware_consensus.rs:120` | `VoteAwareConsensusLens::resolve_async()` | YES (already) | +| `trust_aware_authority.rs:90` | `TrustAwareAuthorityLens::resolve_async()` | YES (already) | + +*Note: `authority.rs` was renamed to `confidence.rs` and `AuthorityLens` to `ConfidenceLens` in Task 2.2.* + +The async lenses were instrumented when created. The synchronous lenses predate the tracing-coverage remediation. + +## FIX (2026-01-31) + +Added `#[instrument]` to all 3 synchronous lens `resolve()` methods: + +| File | Change | +|------|--------| +| `recency.rs` | Added `use tracing::instrument;` + `#[instrument(skip(self, candidates), fields(candidates_count = candidates.len(), lens = "Recency"))]` | +| `consensus.rs` | Added `use tracing::instrument;` + `#[instrument(skip(self, candidates), fields(candidates_count = candidates.len(), lens = "Consensus"))]` | +| `confidence.rs` | Added `use tracing::instrument;` + `#[instrument(skip(self, candidates), fields(candidates_count = candidates.len(), lens = "Confidence"))]` | + +*Note: File was originally `authority.rs` (renamed to `confidence.rs` in Task 2.2).* + +Build verified: `cargo build --workspace` + `cargo clippy --workspace -- -D warnings` both pass. + +## VERIFY (2026-01-31) + +Grep confirmed 5/5 lens implementations instrumented, 0 remaining gaps: +- RecencyLens::resolve() ✅ +- ConsensusLens::resolve() ✅ +- ConfidenceLens::resolve() ✅ (renamed from AuthorityLens in Task 2.2) +- VoteAwareConsensusLens::resolve_async() ✅ (already) +- TrustAwareAuthorityLens::resolve_async() ✅ (already) + +## ENFORCE (2026-01-31) + +Updated CLAUDE.md critical rule: +- Before: "Use `#[instrument]` on public methods in WAL, storage, and ingestion code." +- After: "Use `#[instrument]` on public methods in WAL, storage, ingestion, and lens code. Include meaningful fields (key_len, payload_len, offset, candidates_count, lens)." + +## DOCUMENT (2026-01-31) + +Updated `.claude/skills/stemedb-lens/SKILL.md`: +- Updated trait signatures to match current code (Lens + AsyncLens) +- Added "Current Implementations" table with all 5 lenses +- Added "Tracing Pattern (Required)" section with example +- Added `#[instrument]` to the "Do" checklist +- Updated strategies to reflect actual implementation details diff --git a/.agentive-remediation/lens-instrumentation/state.yaml b/.agentive-remediation/lens-instrumentation/state.yaml new file mode 100644 index 0000000..fc350f6 --- /dev/null +++ b/.agentive-remediation/lens-instrumentation/state.yaml @@ -0,0 +1,14 @@ +task: lens-instrumentation +created: 2026-01-31 +completed: 2026-01-31 +phase: COMPLETE +before_count: 3 +current_count: 0 +summary: | + Added #[instrument] to all 3 synchronous lens resolve() methods: + - RecencyLens::resolve() in recency.rs + - ConsensusLens::resolve() in consensus.rs + - ConfidenceLens::resolve() in confidence.rs (renamed from AuthorityLens in Task 2.2) + All 5 lens implementations (3 sync + 2 async) now instrumented. + CLAUDE.md critical rule updated to include lens code. + stemedb-lens skill updated with tracing pattern requirement. diff --git a/.agentive-remediation/logging-consistency/history.md b/.agentive-remediation/logging-consistency/history.md new file mode 100644 index 0000000..1c7ed2f --- /dev/null +++ b/.agentive-remediation/logging-consistency/history.md @@ -0,0 +1,63 @@ +# logging-consistency + +## AUDIT (2026-02-01) + +**Pattern:** `println!`/`eprintln!` usage instead of structured tracing +**Found:** 13 instances in 6 files + +### Breakdown by Category + +| Category | Count | Files | Decision | +|----------|-------|-------|----------| +| Doc comments | 8 | skeptic.rs (lens), skeptic.rs (query), lib.rs (query), lib.rs (storage), materializer.rs | KEEP - example code | +| CLI output | 5 | main.rs (sim) | KEEP - user-facing terminal output | +| Production code | 0 | - | N/A | + +### Detailed Locations + +**Doc Comments (Intentional - Example Code):** +- `crates/stemedb-lens/src/skeptic.rs:32` - `//!` example +- `crates/stemedb-lens/src/skeptic.rs:34` - `//!` example +- `crates/stemedb-query/src/skeptic.rs:27` - `//!` example +- `crates/stemedb-query/src/skeptic.rs:29` - `//!` example +- `crates/stemedb-query/src/lib.rs:41` - `//!` example +- `crates/stemedb-storage/src/lib.rs:112` - `//!` example +- `crates/stemedb-storage/src/lib.rs:115` - `//!` example +- `crates/stemedb-query/src/materializer.rs:75` - `///` example + +**CLI Binary Output (Intentional - User Facing):** +- `crates/stemedb-sim/src/main.rs:32` - prints simulation summary +- `crates/stemedb-sim/src/main.rs:35` - prints PASSED message +- `crates/stemedb-sim/src/main.rs:38` - prints FAILED message +- `crates/stemedb-sim/src/main.rs:40` - prints error details +- `crates/stemedb-sim/src/main.rs:46` - prints fatal error + +**Conclusion:** All instances are intentional. No production library code uses println. + +## ENFORCE (2026-02-01) + +Added clippy lints to prevent future `println!`/`eprintln!` in library code: + +| File | Change | +|------|--------| +| `Cargo.toml` | Added `print_stdout = "warn"`, `print_stderr = "warn"` to `[workspace.lints.clippy]` | +| `crates/stemedb-sim/src/main.rs` | Added `#![allow(clippy::print_stdout, clippy::print_stderr)]` with comment explaining CLI exemption | + +Verified: `cargo clippy --workspace -- -D warnings` passes. + +## DOCUMENT (2026-02-01) + +Added "Structured Logging" critical rule to CLAUDE.md: +> **Structured Logging:** Use `tracing` (info!, warn!, error!) instead of `println!`/`eprintln!`. Clippy enforces via `print_stdout`/`print_stderr` at warn level. CLI binaries (e.g., `stemedb-sim`) may use `#![allow()]` for user-facing output. + +## COMPLETE (2026-02-01) + +**Before:** 13 println!/eprintln! instances (all intentional) +**After:** 0 violations (8 in doc comments, 5 in CLI binary with allow attribute) + +**Enforcement:** +- Workspace clippy lints: `print_stdout = "warn"`, `print_stderr = "warn"` +- CLI exemption pattern: `#![allow(clippy::print_stdout, clippy::print_stderr)]` + +**Documentation:** +- CLAUDE.md Critical Rules: Added "Structured Logging" rule diff --git a/.agentive-remediation/logging-consistency/state.yaml b/.agentive-remediation/logging-consistency/state.yaml new file mode 100644 index 0000000..b5eaec0 --- /dev/null +++ b/.agentive-remediation/logging-consistency/state.yaml @@ -0,0 +1,21 @@ +task: logging-consistency +created: 2026-02-01 +completed: 2026-02-01 +phase: COMPLETE +before_count: 13 +current_count: 0 +exceptions: + doc_comments: 8 # Example code in //! and /// comments - intentional + cli_output: 5 # stemedb-sim binary user-facing output - intentional +summary: | + All 13 instances are intentional: + - 8 in doc comments (example code showing usage) + - 5 in stemedb-sim/main.rs (CLI user output) + + No production library code uses println!/eprintln!. + Adding lint enforcement to prevent future violations. +documentation: | + Added "Structured Logging" critical rule to CLAUDE.md requiring tracing over println. +enforcement: | + - Added `print_stdout = "warn"` and `print_stderr = "warn"` to workspace Cargo.toml + - Added `#![allow(clippy::print_stdout, clippy::print_stderr)]` to stemedb-sim/main.rs diff --git a/.agentive-remediation/raw-allocserializer-usage/history.md b/.agentive-remediation/raw-allocserializer-usage/history.md new file mode 100644 index 0000000..c945236 --- /dev/null +++ b/.agentive-remediation/raw-allocserializer-usage/history.md @@ -0,0 +1,36 @@ +# raw-allocserializer-usage + +## AUDIT (2026-02-01) + +Pattern: Raw `AllocSerializer` usage outside canonical `stemedb_core::serde` module + +### Search Results + +| Location | Lines | Context | Violation? | +|----------|-------|---------|------------| +| `stemedb-core/src/lib.rs` | 26, 58, 105, 140, 170, 211, 239 | `#[cfg(test)]` module | NO | +| `stemedb-core/src/serde.rs` | 5, 39, 65, 100, 102 | Canonical implementation | NO | +| `stemedb-query/src/engine.rs` | 247, 269 | `#[cfg(test)]` module | NO | +| `stemedb-storage/src/serde_helpers.rs` | 30 | Type bound, delegates to core | NO | + +### Conclusion + +**Found: 0 production code violations** + +All `AllocSerializer` usages are either: +1. Inside the canonical `stemedb_core::serde` module (correct) +2. Inside `#[cfg(test)]` blocks (allowed) +3. Type bounds that delegate to the canonical module (correct) + +## RESOLUTION (2026-02-01) + +Status: **No Action Required** + +The codebase is already compliant. + +## ENFORCEMENT (Already Exists) + +CLAUDE.md line 39: +> **Zero-Copy:** Use `rkyv` for serialization. ALWAYS use `stemedb_core::serde::{serialize, deserialize}` — NEVER use raw `AllocSerializer` in production code. + +No additional enforcement needed. diff --git a/.agentive-remediation/raw-allocserializer-usage/state.yaml b/.agentive-remediation/raw-allocserializer-usage/state.yaml new file mode 100644 index 0000000..d89c9d0 --- /dev/null +++ b/.agentive-remediation/raw-allocserializer-usage/state.yaml @@ -0,0 +1,7 @@ +task: raw-allocserializer-usage +created: 2026-02-01 +phase: COMPLETE +before_count: 0 +current_count: 0 +resolution: "No action required - all usages are in test code or canonical implementation" +enforcement_exists: "CLAUDE.md line 39 already contains this rule" diff --git a/.agentive-remediation/serde-error-thiserror/history.md b/.agentive-remediation/serde-error-thiserror/history.md new file mode 100644 index 0000000..b18b50c --- /dev/null +++ b/.agentive-remediation/serde-error-thiserror/history.md @@ -0,0 +1,31 @@ +# serde-error-thiserror + +## AUDIT (2026-01-31) +Pattern: SerdeError in stemedb-core/src/serde.rs uses manual `impl fmt::Display` and `impl std::error::Error` instead of `#[derive(thiserror::Error)]` like all other error types. +Found: 3 items to fix in 1 file (enum + Display impl + Error impl) + +All 5 other error types in the workspace use thiserror: +- stemedb-storage/src/error.rs: StorageError +- stemedb-api/src/error.rs: ApiError +- stemedb-wal/src/error.rs: QuarantineError +- stemedb-query/src/error.rs: QueryError +- stemedb-ingest/src/error.rs: IngestError + +## FIX (2026-01-31) +- [x] crates/stemedb-core/src/serde.rs:52-69 - Replaced manual `impl fmt::Display` + `impl std::error::Error` with `#[derive(Debug, Error)]` and `#[error(...)]` attributes. Removed `use std::fmt`, added `use thiserror::Error`. + +## VERIFY (2026-01-31) +- grep for `impl fmt::Display for SerdeError`: 0 matches +- grep for `impl std::error::Error for SerdeError`: 0 matches +- grep for `#[derive.*Error.*]` on error enums: 6/6 use thiserror +- cargo build: OK +- cargo clippy: OK (0 warnings) +- cargo test: 158 passed, 0 failed + +## ENFORCE (2026-01-31) +- Updated `ai-lookup/patterns/error-handling.md` with explicit rule: "NEVER use manual impl Display + impl Error — use thiserror derives" +- Listed all 6 error types confirming compliance + +## COMPLETE +Before: 3 items (enum definition, Display impl, Error impl) +After: 0 manual impls remaining diff --git a/.agentive-remediation/serde-error-thiserror/state.yaml b/.agentive-remediation/serde-error-thiserror/state.yaml new file mode 100644 index 0000000..c411149 --- /dev/null +++ b/.agentive-remediation/serde-error-thiserror/state.yaml @@ -0,0 +1,8 @@ +task: serde-error-thiserror +created: 2026-01-31 +phase: COMPLETE +before_count: 3 +current_count: 0 +description: "Convert SerdeError from manual Display+Error impls to thiserror derive, matching all other error types in the workspace" +current: DONE +next: [] diff --git a/.agentive-remediation/serialization-duplication/history.md b/.agentive-remediation/serialization-duplication/history.md new file mode 100644 index 0000000..d93f956 --- /dev/null +++ b/.agentive-remediation/serialization-duplication/history.md @@ -0,0 +1,52 @@ +# serialization-duplication + +## AUDIT (2026-01-31) + +Pattern: Duplicated rkyv serialization/deserialization boilerplate across crates + +```rust +// ANTI-PATTERN: This 4-line pattern appears 7 times +let mut serializer = AllocSerializer::<4096>::default(); +serializer.serialize_value(&value).map_err(...)?; +let bytes = serializer.into_serializer().into_inner(); +``` + +Found: **7 production instances** in **4 files** + +| File | Line | Function | Type | +|------|------|----------|------| +| stemedb-ingest/src/worker.rs | 61 | serialize_assertion | Serialize | +| stemedb-ingest/src/worker.rs | 75 | serialize_vote | Serialize | +| stemedb-ingest/src/worker.rs | 88 | serialize_epoch | Serialize | +| stemedb-storage/src/vote_store.rs | 155 | serialize_vote | Serialize | +| stemedb-storage/src/vote_store.rs | 162 | deserialize_vote | Deserialize | +| stemedb-query/src/engine.rs | 140 | deserialize_assertion | Deserialize | +| stemedb-lens/src/vote_aware_consensus.rs | 100 | compute_assertion_hash | Serialize | + +**Excluded (test code):** +- stemedb-core/src/lib.rs (all in #[cfg(test)]) +- stemedb-query/src/engine.rs:184 (test helper) +- stemedb-sim/src/main.rs (demo binary) + +## Plan + +1. CREATE: Add `stemedb-core/src/serde.rs` with generic serialize/deserialize helpers +2. FIX: Replace all 7 instances with calls to the new helpers +3. VERIFY: grep returns 0 for raw AllocSerializer usage outside tests +4. ENFORCE: Add CLAUDE.md rule prohibiting direct AllocSerializer usage +5. DOCUMENT: Update ai-lookup with the canonical pattern + +## FIX Progress +- [x] CREATE utility module - `stemedb-core/src/serde.rs` with `serialize()` and `deserialize()` +- [ ] stemedb-ingest/src/worker.rs <- CURRENT +- [ ] stemedb-storage/src/vote_store.rs +- [ ] stemedb-query/src/engine.rs +- [ ] stemedb-lens/src/vote_aware_consensus.rs + +## CREATE (2026-01-31) + +Created `crates/stemedb-core/src/serde.rs`: +- `serialize(value: &T) -> Result, SerdeError>` - Generic serialization +- `deserialize(data: &[u8]) -> Result` - Generic deserialization +- `SerdeError` enum for error handling +- 5 unit tests + 2 doc tests passing diff --git a/.agentive-remediation/serialization-duplication/state.yaml b/.agentive-remediation/serialization-duplication/state.yaml new file mode 100644 index 0000000..fd97291 --- /dev/null +++ b/.agentive-remediation/serialization-duplication/state.yaml @@ -0,0 +1,18 @@ +task: serialization-duplication +created: 2026-01-31 +completed: 2026-01-31 +phase: COMPLETE +before_count: 9 +current_count: 0 +summary: | + Created canonical stemedb_core::serde module with generic serialize/deserialize. + Replaced all 9 production instances of raw AllocSerializer across 6 files: + - stemedb-ingest/src/worker.rs (3 serialize + 3 deserialize) + - stemedb-storage/src/vote_store.rs (1 serialize + 1 deserialize) + - stemedb-storage/src/index_store.rs (1 serialize + 1 deserialize) + - stemedb-storage/src/trust_rank_store.rs (1 serialize + 1 deserialize) + - stemedb-query/src/engine.rs (1 deserialize) + - stemedb-lens/src/vote_aware_consensus.rs (1 serialize) + - stemedb-sim/src/main.rs (1 serialize + 1 deserialize) + Added CLAUDE.md enforcement rule. + All 123 workspace tests pass, clippy clean, fmt clean. diff --git a/.agentive-remediation/storage-serde-dedup/history.md b/.agentive-remediation/storage-serde-dedup/history.md new file mode 100644 index 0000000..64b8bc8 --- /dev/null +++ b/.agentive-remediation/storage-serde-dedup/history.md @@ -0,0 +1,72 @@ +# storage-serde-dedup + +## COMPLETE (2026-02-01) + +**Before:** 12 instances of duplicated serialization helpers +**After:** 0 instances - all use centralized `crate::serde_helpers` + +**Enforcement:** Added to `.claude/skills/stemedb-core/SKILL.md`: +- Do: "In stemedb-storage: Use crate::serde_helpers::{serialize, deserialize}" +- Do Not: "Call stemedb_core::serde::serialize or deserialize directly" + +**Documentation:** Updated `ai-lookup/services/storage.md`: +- Added storage-layer serialization section +- Added serde_helpers.rs to file pointers + +--- + +## FIX Progress (2026-02-01) + +- [x] CREATE serde_helpers.rs with generic serialize/deserialize functions +- [x] FIX vote_store.rs - replaced serialize_vote/deserialize_vote +- [x] FIX index_store.rs - replaced serialize_hash_list/deserialize_hash_list +- [x] FIX trust_rank_store.rs - replaced serialize_trust_rank/deserialize_trust_rank +- [x] FIX audit_store.rs - replaced serialize_audit/deserialize_audit +- [x] FIX trust_pack_store.rs - replaced serialize_pack/deserialize_pack +- [x] FIX quota_store.rs - replaced serialize_record/deserialize_record +- [x] Removed unused StorageError imports from 3 files +- [x] All 64 stemedb-storage tests pass +- [x] All workspace tests pass (225+ tests) +- [x] Clippy passes with zero warnings + +## AUDIT (2026-02-01) + +Pattern: Every storage module duplicates serialize_X/deserialize_X helper functions that wrap stemedb_core::serde with StorageError mapping. + +```rust +// DUPLICATED 12 times (6 serialize + 6 deserialize) +fn serialize_X(data: &X) -> Result> { + stemedb_core::serde::serialize(data) + .map_err(|e| StorageError::Serialization(e.to_string())) +} + +fn deserialize_X(data: &[u8]) -> Result { + stemedb_core::serde::deserialize(data) + .map_err(|e| StorageError::Serialization(e.to_string())) +} +``` + +Found: **12 instances** in **6 files** + +| File | Line | Function | +|------|------|----------| +| vote_store.rs | 150 | serialize_vote | +| vote_store.rs | 155 | deserialize_vote | +| index_store.rs | 128 | serialize_hash_list | +| index_store.rs | 134 | deserialize_hash_list | +| trust_rank_store.rs | 248 | serialize_trust_rank | +| trust_rank_store.rs | 254 | deserialize_trust_rank | +| audit_store.rs | 153 | serialize_audit | +| audit_store.rs | 159 | deserialize_audit | +| trust_pack_store.rs | 138 | serialize_pack | +| trust_pack_store.rs | 143 | deserialize_pack | +| quota_store.rs | 291 | serialize_record | +| quota_store.rs | 297 | deserialize_record | + +## Plan + +1. CREATE: Add `stemedb-storage/src/serde_helpers.rs` with generic serialize/deserialize +2. FIX: Replace all 12 type-specific functions with calls to the generic helpers +3. VERIFY: grep returns 0 for old pattern +4. ENFORCE: Add rule to skill or guideline +5. DOCUMENT: Update ai-lookup/services/storage.md diff --git a/.agentive-remediation/storage-serde-dedup/state.yaml b/.agentive-remediation/storage-serde-dedup/state.yaml new file mode 100644 index 0000000..6835005 --- /dev/null +++ b/.agentive-remediation/storage-serde-dedup/state.yaml @@ -0,0 +1,12 @@ +task: storage-serde-dedup +created: 2026-02-01 +completed: 2026-02-01 +phase: COMPLETE +before_count: 12 +current_count: 0 +summary: | + Created centralized serde_helpers.rs module in stemedb-storage. + Replaced 12 duplicate serialize_X/deserialize_X functions across 6 files. + Added enforcement rule to stemedb-core skill. + Updated ai-lookup/services/storage.md documentation. + All 225+ workspace tests pass, clippy clean. diff --git a/.agentive-remediation/unify-test-helpers/state.yaml b/.agentive-remediation/unify-test-helpers/state.yaml new file mode 100644 index 0000000..81840b6 --- /dev/null +++ b/.agentive-remediation/unify-test-helpers/state.yaml @@ -0,0 +1,38 @@ +remediation: unify-test-helpers +status: COMPLETED +phase: VERIFY + +problem: 9 duplicate create_assertion/create_test_assertion factory functions across 8 files +solution: Created stemedb-core::testing module with AssertionBuilder + factory functions + +audit: + instances_found: 9 + files_affected: 8 + patterns: + - "create_assertion(subject, timestamp)" # recency.rs + - "create_assertion(subject, value, timestamp)" # consensus.rs, vote_aware_consensus.rs + - "create_assertion(subject, confidence, timestamp)" # authority.rs + - "create_assertion(subject, confidence, agent_id, timestamp)" # trust_aware_authority.rs + - "create_test_assertion(subject, predicate, lifecycle)" # engine.rs, query.rs + - "create_assertion(subject, predicate, value, timestamp)" # materializer.rs + - "create_signed_assertion(subject, predicate)" # worker.rs (crypto) + +fix: + created: + - crates/stemedb-core/src/testing.rs + modified: + - crates/stemedb-core/src/lib.rs + - crates/stemedb-lens/src/recency.rs + - crates/stemedb-lens/src/consensus.rs + - crates/stemedb-lens/src/authority.rs + - crates/stemedb-lens/src/vote_aware_consensus.rs + - crates/stemedb-lens/src/trust_aware_authority.rs + - crates/stemedb-query/src/engine.rs + - crates/stemedb-query/src/query.rs + - crates/stemedb-query/src/materializer.rs + - crates/stemedb-ingest/src/worker.rs + +verify: + tests: 164 passed, 0 failed + clippy: 0 warnings (deny level) + fmt: clean diff --git a/.claude/agents/sec-data-engineer.md b/.claude/agents/sec-data-engineer.md new file mode 100644 index 0000000..81c60b8 --- /dev/null +++ b/.claude/agents/sec-data-engineer.md @@ -0,0 +1,58 @@ +--- +name: sec-data-engineer +description: Use this agent for SEC/EDGAR data ingestion, XBRL parsing, and financial domain modeling. This agent understands the nuances of 10-K/10-Q reporting, amendments, and mapping financial facts to StemeDB assertions. +model: sonnet +color: green +--- + +You are the **SEC Data Engineer**. You are a specialist in Financial Data Engineering with deep expertise in the SEC EDGAR system, XBRL/iXBRL standards, and quantitative analysis. + +Your goal is to transform the messy, document-based world of regulatory filings into a structured, queryable **Knowledge Lattice**. + +## Core Competencies + +### 1. EDGAR Expertise +You understand the structure of SEC filings: +* **Forms:** You distinguish between `10-K` (Annual), `10-Q` (Quarterly), `8-K` (Material Events), `S-1` (IPO), and `4` (Insider Trading). +* **Amendments:** You know that a form ending in `/A` (e.g., `10-K/A`) is an **Amendment**. You treat this as a **Paradigm Shift**, triggering a `SupersedeEpoch` event in StemeDB to invalidate or update prior assertions. +* **Access:** You know how to efficiently poll the EDGAR RSS feeds for real-time data and how to parse the daily/quarterly index files for historical backfilling. + +### 2. Semantic Extraction (XBRL & Text) +* **Structured (XBRL):** You extract hard numbers (Revenue, Assets, EPS) from XBRL tags. You map these to strict `Predicates` (e.g., `us-gaap:Revenues`). +* **Unstructured (Text):** You design pipelines to extract qualitative sections like "Risk Factors" (Item 1A) or "MD&A" (Item 7). You use NLP to chunk these into assertions linked to the source paragraph. + +### 3. Episteme Integration +You map financial concepts to StemeDB primitives: +* **Entity:** The Company (CIK / Ticker). +* **Epoch:** The Reporting Period (e.g., "Q3-2023-Filing"). +* **Assertion:** A specific line item (e.g., `Subject: Tesla`, `Pred: Revenue`, `Object: $23B`, `Source: 10-Q`). +* **Conflict:** You identify when an 8-K (Event) contradicts a forward-looking statement in a previous 10-Q. + +## Operational Protocols + +### The Ingestion Loop +1. **Poll:** Check EDGAR RSS for new CIKs of interest. +2. **Fetch:** Download the `.txt` (Complete Submission) or specific iXBRL/HTM files. +3. **Parse:** Extract metadata (Period, Filing Date) and content. +4. **Assert:** + * Create a new `Epoch` for the filing. + * If it's an `/A` filing, supersede the previous Epoch. + * Write `Assertions` for every extracted fact. + +### Handling "Restatements" +When a company restates earnings: +* You do **not** delete the old numbers. +* You create a **New Epoch** ("Restated-2023"). +* You use `SupersessionType::Temporal` or `Invalidate` depending on the nature of the error. +* This preserves the history ("What did we think the revenue was?") while clarifying the present ("What is the revenue now?"). + +## Do +* Validate CIKs and Tickers. +* Handle rate limits (SEC allows 10 req/sec). +* Use "As-Of" dates strictly. +* Link every assertion to its specific source URL/File. + +## Do Not +* Treat "Net Income" and "Comprehensive Income" as the same. +* Ignore footnotes (often where the real risk is). +* Overwrite historical data with current data (always use Epochs). diff --git a/.claude/commands/analyze-gaps.md b/.claude/commands/analyze-gaps.md new file mode 100644 index 0000000..fab19de --- /dev/null +++ b/.claude/commands/analyze-gaps.md @@ -0,0 +1,45 @@ +# Analyze Use Case Gaps + +Analyze gaps between a use case and the current implementation. + +## Arguments + +`$ARGUMENTS` - The use case to analyze (e.g., "agile-agent-team", "financial-due-diligence") + +## Instructions + +Load the `use-case-gap-analysis` skill, then: + +1. **Read the use case**: `use-cases/$ARGUMENTS.md` (or `use-cases/*.md` if not specified) + +2. **Read current state**: + - `roadmap.md` - Check checkbox status for completed vs. planned + - `architecture.md` - Understand what's architecturally possible + - `crates/*/src/**/*.rs` - Find actual implementations + +3. **Execute the skill protocol**: + - Phase 1: Parse use case claims + - Phase 2: Check implementation status + - Phase 3: Build gap matrix + - Phase 4: Prioritize by customer pain + - Phase 5: Generate recommendations + +4. **Output the analysis** following the skill's output format + +## Examples + +```bash +# Analyze specific use case +/analyze-gaps agile-agent-team + +# Analyze all use cases +/analyze-gaps + +# Analyze financial use case +/analyze-gaps financial-due-diligence +``` + +## Output Location + +Results are displayed in chat. If `--save` is included in arguments, also write to: +`docs/gap-analysis/$ARGUMENTS-gaps.md` diff --git a/.claude/guides/backend/api-endpoints.md b/.claude/guides/backend/api-endpoints.md new file mode 100644 index 0000000..073f58d --- /dev/null +++ b/.claude/guides/backend/api-endpoints.md @@ -0,0 +1,145 @@ +# Add an API Endpoint + +**When to use:** You need to add a new HTTP endpoint to the Episteme API. + +## Prerequisites + +- Familiarity with `axum` handler patterns +- Understanding of `utoipa` derive macros +- Read [ai-lookup/services/api.md](../../../ai-lookup/services/api.md) for architecture overview + +## Quick Start + +```bash +# After adding endpoint code: +cargo build -p stemedb-api +cargo test -p stemedb-api +cargo clippy -p stemedb-api -- -D warnings +``` + +## Step-by-Step + +### 1. Define DTO Types + +Create request/response types in `crates/stemedb-api/src/dto.rs`. These derive BOTH serde (for JSON) and utoipa (for OpenAPI docs): + +```rust +#[derive(Serialize, Deserialize, ToSchema)] +pub struct MyRequest { + /// Description appears in OpenAPI docs. + #[schema(example = "Tesla_Inc")] + pub subject: String, +} + +#[derive(Serialize, Deserialize, ToSchema)] +pub struct MyResponse { + pub hash: String, + pub status: String, +} +``` + +Rules: +- DTOs live in `dto.rs`, NOT in handler files +- Implement `From` for conversions to/from internal types +- Use `#[schema(example = "...")]` for meaningful OpenAPI examples +- Never expose internal rkyv types in the public API + +### 2. Write the Handler + +Create handler in `crates/stemedb-api/src/handlers/{name}.rs`: + +```rust +#[utoipa::path( + post, + path = "/my-endpoint", + request_body = MyRequest, + responses( + (status = 202, description = "Accepted", body = MyResponse), + (status = 400, description = "Validation failed", body = ApiError), + ), + tag = "assertions" +)] +pub async fn my_handler( + State(state): State, + Json(req): Json, +) -> Result<(StatusCode, Json), ApiError> { + // Convert DTO -> internal type + // Call library code (QueryEngine, Ingestor, etc.) + // Convert result -> DTO + // Return +} +``` + +Rules: +- Handlers are thin: convert types, delegate to library code, convert back +- No business logic in handlers +- Always return `Result<_, ApiError>` for consistent error responses +- Use `tag = "..."` to group related endpoints in docs + +### 3. Register the Route + +Add to the `OpenApiRouter` in `crates/stemedb-api/src/lib.rs`: + +```rust +let app = OpenApiRouter::new() + .route("/my-endpoint", post(my_handler)) + // ...existing routes... +``` + +The `OpenApiRouter` automatically collects the `#[utoipa::path]` metadata. No separate registration step. + +### 4. Verify + +```bash +# Build and test +cargo test -p stemedb-api + +# Check docs generated correctly +cargo run -p stemedb-api & +curl localhost:3000/api-doc/openapi.json | jq .paths +``` + +## Error Responses + +All error responses use a consistent `ApiError` type that implements `ToSchema`: + +```rust +#[derive(Serialize, ToSchema)] +pub struct ApiError { + pub error: String, + pub code: String, +} +``` + +Map internal errors to API errors in the handler layer. Never leak internal error details. + +## Checklist + +- [ ] DTO types in `dto.rs` with `Serialize, Deserialize, ToSchema` +- [ ] `From<>` conversions between DTOs and internal types +- [ ] Handler annotated with `#[utoipa::path]` +- [ ] Error responses documented in `responses(...)` +- [ ] Route registered on `OpenApiRouter` +- [ ] Tests cover happy path and error cases +- [ ] `cargo clippy` passes +- [ ] Schema examples are meaningful (not "string") + +## Troubleshooting + +### OpenAPI spec missing my endpoint + +The handler must have `#[utoipa::path]` AND be registered on `OpenApiRouter` (not a plain `axum::Router`). + +### Type not showing in schemas + +The DTO must derive `ToSchema`. If it references other types, those must also derive `ToSchema`. + +### Swagger UI not updating + +Hard refresh the browser. The spec is regenerated on each startup. + +## Related + +- [ai-lookup/patterns/api-documentation.md](../../../ai-lookup/patterns/api-documentation.md) - Toolchain overview +- [ai-lookup/services/api.md](../../../ai-lookup/services/api.md) - Service facts +- [Rust Guidelines](./rust-guidelines.md) - General Rust patterns diff --git a/.claude/guides/integrations/adk-go-episteme.md b/.claude/guides/integrations/adk-go-episteme.md new file mode 100644 index 0000000..facb908 --- /dev/null +++ b/.claude/guides/integrations/adk-go-episteme.md @@ -0,0 +1,510 @@ +# ADK-Go + Episteme Integration Guide + +> **Purpose:** Technical reference for integrating AI agents with Episteme using Google's Agent Development Kit for Go (ADK-Go). +> **For use case context:** See [use-cases/agile-agent-team.md](../../../use-cases/agile-agent-team.md) + +## Overview + +This guide shows how AI agents integrate with Episteme for: +- **Query** - Retrieve knowledge with lens-based resolution +- **Assert** - Store knowledge with lifecycle and confidence +- **Constraint Check** - Pre-flight validation before actions +- **Trace** - Audit trail for incident investigation +- **Supersede** - Correct errors with cascade tracking + +Each agent type has specific patterns for tool usage and callback integration. + +--- + +## Tool Definitions + +Every Episteme operation is exposed as an ADK-Go tool: + +```go +package episteme + +import ( + "google.golang.org/adk/tool" + "google.golang.org/adk/tool/functiontool" +) + +// === QUERY TOOL === +// Used by: All agents + +type QueryInput struct { + Subject string `json:"subject" jsonschema:"Entity to query (e.g., auth/jwt)"` + Predicate string `json:"predicate" jsonschema:"Relation to query (e.g., signing_algorithm)"` + Lens string `json:"lens,omitempty" jsonschema:"Resolution: consensus, authority, recency, constraints"` + Lifecycle string `json:"lifecycle,omitempty" jsonschema:"Filter: proposed, approved, deprecated"` + MinConfidence float32 `json:"min_confidence,omitempty" jsonschema:"Minimum confidence threshold (0.0-1.0)"` + AsOf string `json:"as_of,omitempty" jsonschema:"Time-travel: ISO8601 timestamp"` +} + +type QueryOutput struct { + Value interface{} `json:"value"` + Confidence float32 `json:"confidence"` + Lifecycle string `json:"lifecycle"` + Sources []Source `json:"sources"` + QueryID string `json:"query_id"` // CRITICAL: for audit trail +} + +type Source struct { + Hash string `json:"hash"` + SourceHash string `json:"source_hash"` + Weight float32 `json:"weight"` +} + +func queryEpisteme(ctx tool.Context, input QueryInput) QueryOutput { + // Call Episteme API + result, err := epistemeClient.Query(ctx, input) + if err != nil { + return QueryOutput{Error: err.Error()} + } + return result +} + +// === ASSERT TOOL === +// Used by: Research Agent, Human Supervisor + +type AssertInput struct { + Subject string `json:"subject" jsonschema:"Entity being described"` + Predicate string `json:"predicate" jsonschema:"Relation being asserted"` + Object interface{} `json:"object" jsonschema:"Value being claimed"` + SourceHash string `json:"source_hash" jsonschema:"BLAKE3 hash of evidence"` + Confidence float32 `json:"confidence" jsonschema:"Certainty level (0.0-1.0)"` + Lifecycle string `json:"lifecycle,omitempty" jsonschema:"proposed, under_review, approved"` + ParentHash string `json:"parent_hash,omitempty" jsonschema:"Hash of assertion being updated"` + Meta *AssertMeta `json:"meta,omitempty" jsonschema:"Negative constraints and metadata"` +} + +type AssertMeta struct { + ForbiddenAlternative string `json:"forbidden_alternative,omitempty"` + Reason string `json:"reason,omitempty"` +} + +type AssertOutput struct { + Hash string `json:"hash"` + Success bool `json:"success"` + Error string `json:"error,omitempty"` +} + +// === CONSTRAINT CHECK TOOL === +// Used by: Implementation Agent (pre-flight) + +type ConstraintCheckInput struct { + Context string `json:"context" jsonschema:"Domain context (e.g., python_http, auth_jwt)"` +} + +type ConstraintCheckOutput struct { + Constraints []Constraint `json:"constraints"` +} + +type Constraint struct { + Subject string `json:"subject"` + MustUse string `json:"must_use,omitempty"` + Forbidden string `json:"forbidden,omitempty"` + Reason string `json:"reason"` +} + +// === TRACE TOOL === +// Used by: On-Call SRE, Human Supervisor + +type TraceInput struct { + AgentID string `json:"agent_id" jsonschema:"Agent to trace"` + From string `json:"from" jsonschema:"Start time (ISO8601 or relative like -6h)"` + To string `json:"to,omitempty" jsonschema:"End time (default: now)"` + Subject string `json:"subject,omitempty" jsonschema:"Filter by subject pattern (e.g., auth/*)"` +} + +type TraceOutput struct { + Queries []QueryTrace `json:"queries"` +} + +type QueryTrace struct { + QueryID string `json:"query_id"` + Timestamp string `json:"timestamp"` + Subject string `json:"subject"` + Predicate string `json:"predicate"` + Lens string `json:"lens"` + Result string `json:"result"` + Confidence float32 `json:"confidence"` + Contributing []string `json:"contributing_assertions"` +} + +// === SUPERSEDE TOOL === +// Used by: Human Supervisor + +type SupersedeInput struct { + Hash string `json:"hash" jsonschema:"Assertion hash to supersede"` + Reason string `json:"reason" jsonschema:"Why this is being superseded"` + Type string `json:"type" jsonschema:"Invalidate, Temporal, RequiresReview, Additive"` +} + +type SupersedeOutput struct { + NewHash string `json:"new_hash"` + AffectedAssertions []string `json:"affected_assertions"` +} +``` + +--- + +## Callback Integration + +Callbacks are critical for enforcing constraints and maintaining audit trails: + +```go +import ( + "google.golang.org/adk/agent" + "google.golang.org/adk/agent/llmagent" + "google.golang.org/adk/model" + "google.golang.org/adk/tool" +) + +// Implementation Agent with BeforeToolCallback for constraint checking +implementationAgent, err := llmagent.New(llmagent.Config{ + Name: "implementation_agent", + Model: model, + Description: "Writes code against current approved patterns", + Instruction: "You write code. Always use approved patterns only.", + Tools: []tool.Tool{queryTool, constraintTool}, + + // CRITICAL: Check constraints BEFORE any tool that generates code + BeforeToolCallback: func(ctx agent.CallbackContext, call *tool.Call) (*tool.Call, error) { + // If agent is about to write code, check constraints first + if needsConstraintCheck(call) { + context := extractDomainContext(call) // e.g., "python_http" + constraints, err := checkConstraints(ctx, context) + if err != nil { + return nil, fmt.Errorf("constraint check failed: %w", err) + } + + for _, c := range constraints { + if violatesConstraint(call, c) { + return nil, fmt.Errorf("blocked: %s is forbidden - %s", + c.Forbidden, c.Reason) + } + } + } + return call, nil + }, + + // Log decisions for audit trail + AfterModelCallback: func(ctx agent.CallbackContext, resp *model.LLMResponse) (*model.LLMResponse, error) { + decision := extractDecision(resp) + logToEpisteme(ctx, AuditEntry{ + AgentID: ctx.Agent().Name(), + Timestamp: time.Now(), + Decision: decision, + SessionID: ctx.Session().ID(), + }) + return resp, nil + }, +}) + +// Lead Orchestrator with confidence threshold escalation +leadOrchestrator, err := llmagent.New(llmagent.Config{ + Name: "lead_orchestrator", + Model: model, + Description: "Coordinates agent team, routes work based on knowledge", + Instruction: `You coordinate the agent team. Query Episteme for current state. + If confidence < 0.8, escalate to human supervisor.`, + Tools: []tool.Tool{queryTool, delegateTool}, + OutputKey: "orchestrator_decision", // Pass to downstream agents + + // Check confidence scores and escalate if too low + AfterToolCallback: func(ctx agent.CallbackContext, call *tool.Call, result *tool.Result) (*tool.Result, error) { + if call.Name == "episteme_query" { + var queryResult QueryOutput + json.Unmarshal(result.Output, &queryResult) + + if queryResult.Confidence < 0.8 { + // Mark for human review + ctx.Session().State().Set("needs_human_review", true) + ctx.Session().State().Set("low_confidence_query", queryResult.QueryID) + } + } + return result, nil + }, +}) +``` + +--- + +## Agent-Specific Patterns + +### Lead Orchestrator + +Fast queries with confidence thresholds for routing decisions: + +```go +// Query current auth config with confidence threshold +result := queryEpisteme(ctx, QueryInput{ + Subject: "auth/jwt", + Predicate: "signing_algorithm", + Lens: "authority", + MinConfidence: 0.8, +}) + +if result.Confidence < 0.8 { + // Escalate to human - can't route confidently + ctx.Session().State().Set("escalation_reason", + fmt.Sprintf("Confidence %.2f below threshold for %s/%s", + result.Confidence, result.Subject, result.Predicate)) + return escalateToHuman(ctx) +} + +// Route to implementation agent with high confidence +ctx.Session().State().Set("auth_config", result.Value) +return delegateTo(ctx, "implementation_agent") +``` + +### Implementation Agent + +Queries approved patterns only, with pre-flight constraint checks: + +```go +// CRITICAL: Filter to approved lifecycle ONLY +result := queryEpisteme(ctx, QueryInput{ + Subject: "auth/jwt", + Predicate: "signing_algorithm", + Lens: "authority", + Lifecycle: "approved", // Never use proposed patterns! +}) + +if result.Lifecycle != "approved" { + return fmt.Errorf("no approved pattern found for %s/%s", + input.Subject, input.Predicate) +} + +// Pre-flight: check for forbidden alternatives +constraints := checkConstraints(ctx, "auth_jwt") +for _, c := range constraints.Constraints { + // Agent now knows: "use X, don't use Y, because Z" + // This enables contrastive learning +} +``` + +### Research Agent + +Stores conflicting information with uncertainty: + +```go +// Store first source +assertKnowledge(ctx, AssertInput{ + Subject: "jwt_rotation", + Predicate: "best_practice", + Object: "rotate_daily", + SourceHash: hashURL("https://security.io/jwt-best-practices"), + Confidence: 0.7, // Express uncertainty + Lifecycle: "proposed", // Not approved yet +}) + +// Store contradicting source - don't flatten! +assertKnowledge(ctx, AssertInput{ + Subject: "jwt_rotation", + Predicate: "best_practice", + Object: "rotate_hourly", + SourceHash: hashURL("https://owasp.org/jwt-rotation"), + Confidence: 0.8, + Lifecycle: "proposed", +}) + +// Let Lead Orchestrator resolve via Lens::Consensus or Lens::Authority +``` + +### Human Supervisor + +Time-travel queries and corrections with impact analysis: + +```go +// What was believed during the incident? +result := queryEpisteme(ctx, QueryInput{ + Subject: "auth/jwt", + Predicate: "signing_algorithm", + AsOf: "2024-01-15T21:00:00Z", // Time of incident +}) + +// Trace agent queries during the incident window +traces := traceQueries(ctx, TraceInput{ + AgentID: "deployment-agent", + From: "2024-01-15T20:00:00Z", + To: "2024-01-15T22:00:00Z", + Subject: "auth/*", +}) + +// Found the bug: agent queried without lifecycle filter +// Correct the record +impact := supersede(ctx, SupersedeInput{ + Hash: badAssertionHash, + Reason: "Proposal treated as approved - agent didn't filter by lifecycle", + Type: "Invalidate", +}) + +// impact.AffectedAssertions shows downstream effects +fmt.Printf("Corrected. %d downstream assertions affected.\n", + len(impact.AffectedAssertions)) +``` + +### On-Call SRE + +Sub-second trace commands for incident investigation: + +```go +// It's 3am. Auth is broken. What happened? + +// Step 1: What did deployment agent query? (<500ms required) +traces := traceQueries(ctx, TraceInput{ + AgentID: "deployment-agent", + From: "-6h", + Subject: "auth/*", +}) + +for _, t := range traces.Queries { + fmt.Printf("[%s] %s/%s via %s -> %s (conf: %.2f)\n", + t.Timestamp, t.Subject, t.Predicate, + t.Lens, t.Result, t.Confidence) + + if len(t.Contributing) > 0 { + fmt.Printf(" Contributing: %v\n", t.Contributing) + } +} + +// Step 2: What changed in the last 24 hours? +diff := queryDiff(ctx, DiffInput{ + Subject: "auth/jwt", + From: "-24h", +}) + +// Step 3: Mark bad assertion (found via trace) +supersede(ctx, SupersedeInput{ + Hash: badAssertionHash, + Reason: "RFC proposal incorrectly treated as approved config", + Type: "Invalidate", +}) + +// Step 4: Verify fix +result := queryEpisteme(ctx, QueryInput{ + Subject: "auth/jwt", + Predicate: "signing_algorithm", + Lifecycle: "approved", +}) +fmt.Printf("Current approved value: %s\n", result.Value) +``` + +--- + +## Multi-Agent Pipeline Example + +Complete example showing agents coordinating through Episteme: + +```go +package main + +import ( + "context" + "google.golang.org/adk/agent" + "google.golang.org/adk/agent/llmagent" + "google.golang.org/adk/agent/sequentialagent" + "google.golang.org/adk/model/gemini" +) + +func main() { + ctx := context.Background() + model, _ := gemini.NewModel(ctx, "gemini-3-flash-preview", nil) + + // Research Agent: Discovers and stores knowledge + researchAgent, _ := llmagent.New(llmagent.Config{ + Name: "research_agent", + Model: model, + Description: "Researches and stores knowledge with source attribution", + Instruction: `Research the topic. Store findings with confidence scores. + Mark conflicting sources - don't resolve them.`, + Tools: []tool.Tool{assertTool, searchTool}, + OutputKey: "research_findings", + }) + + // Lead Orchestrator: Queries and routes + leadAgent, _ := llmagent.New(llmagent.Config{ + Name: "lead_orchestrator", + Model: model, + Description: "Coordinates team based on current knowledge state", + Instruction: `Query Episteme for current approved patterns. + Research findings available in {research_findings}. + If confidence >= 0.8, route to implementation. + If confidence < 0.8, flag for human review.`, + Tools: []tool.Tool{queryTool}, + OutputKey: "routing_decision", + + AfterToolCallback: confidenceEscalationCallback, + }) + + // Implementation Agent: Writes code + implAgent, _ := llmagent.New(llmagent.Config{ + Name: "implementation_agent", + Model: model, + Description: "Writes code against approved patterns only", + Instruction: `Write code for the task. + Routing decision in {routing_decision}. + ONLY use approved patterns. Check constraints first.`, + Tools: []tool.Tool{queryTool, constraintTool, writeCodeTool}, + OutputKey: "implementation", + + BeforeToolCallback: constraintEnforcementCallback, + }) + + // Sequential pipeline + pipeline, _ := sequentialagent.New(sequentialagent.Config{ + AgentConfig: agent.Config{ + Name: "AgileDevPipeline", + Description: "Research -> Route -> Implement with Episteme coordination", + SubAgents: []agent.Agent{researchAgent, leadAgent, implAgent}, + }, + }) + + // Run the pipeline + runner := agent.NewRunner(pipeline, sessionService) + for event, err := range runner.Run(ctx, userID, sessionID, userMessage, nil) { + if err != nil { + log.Printf("Pipeline error: %v", err) + } + handleEvent(event) + } +} +``` + +--- + +## Session State vs. Episteme + +| Use Case | Mechanism | Why | +|----------|-----------|-----| +| Agent-to-agent handoff in pipeline | Session State + `OutputKey` | Ephemeral, same conversation | +| Permanent organizational knowledge | Episteme `Assert` | Persists across sessions/agents | +| "What was decided in this conversation" | Session State | Temporary, conversation-scoped | +| "What should all agents know forever" | Episteme `Assert` + `lifecycle: approved` | Permanent, query-audited | +| Temporary working data | `temp:` prefixed state keys | Auto-cleared after session | +| Agent decision audit trail | Episteme `QueryAudit` | Immutable, time-travel enabled | + +--- + +## CLI Commands for Debugging + +```bash +# Trace what an agent queried +episteme trace --agent deployment-agent --time "6 hours ago" --subject "auth/*" + +# Show assertion provenance +episteme show --hash $ASSERTION_HASH --provenance + +# Supersede bad assertion +episteme supersede --hash $BAD_HASH --reason "Proposal treated as approved" \ + --type "Invalidate" + +# See cascade impact +episteme cascade --root $BAD_HASH + +# Verify correction +episteme query --subject auth/jwt --predicate signing_algorithm --lifecycle approved +``` + +**SRE's 3am workflow:** Query -> Trace -> Identify -> Correct -> Verify. Under 10 minutes. diff --git a/.claude/skills/stemedb-core/SKILL.md b/.claude/skills/stemedb-core/SKILL.md index e7d39c1..d885e8e 100644 --- a/.claude/skills/stemedb-core/SKILL.md +++ b/.claude/skills/stemedb-core/SKILL.md @@ -63,6 +63,7 @@ pub enum ObjectValue { * Use `thiserror` for library errors. * Validate signatures on Ingest. * **Instrument public methods** with `#[instrument]` for observability. +* **In stemedb-storage**: Use `crate::serde_helpers::{serialize, deserialize}` for all serialization. This provides unified error mapping to `StorageError::Serialization`. ## Tracing Pattern @@ -90,6 +91,7 @@ Guidelines: * Store large blobs in the Assertions (store pointers/hashes instead). * Add new types without updating `ai-lookup/services/` documentation. * Add public methods without `#[instrument]` in WAL/storage/ingest crates. +* **In stemedb-storage**: Call `stemedb_core::serde::serialize` or `deserialize` directly. Always use `crate::serde_helpers` instead. ## Documentation Sync diff --git a/.claude/skills/stemedb-lens/SKILL.md b/.claude/skills/stemedb-lens/SKILL.md index 5aeb1b5..2856446 100644 --- a/.claude/skills/stemedb-lens/SKILL.md +++ b/.claude/skills/stemedb-lens/SKILL.md @@ -9,36 +9,81 @@ description: Guidelines for implementing Lenses (Resolution Logic). Use when wor You are building the **Cortex** of Episteme. Lenses allow us to view a contradictory reality and get a deterministic answer. -## The Lens Trait +## The Lens Traits ```rust +// Synchronous lens — for pure logic (Recency, Consensus, Authority) pub trait Lens { - /// Resolve a set of conflicting assertions into a single result (or detailed breakdown). - fn resolve(&self, candidates: &[Assertion], context: &QueryContext) -> LensResult; + fn resolve(&self, candidates: &[Assertion]) -> Resolution; + fn name(&self) -> &'static str; +} + +// Async lens — for I/O-backed resolution (VoteAwareConsensus, TrustAwareAuthority) +pub trait AsyncLens { + async fn resolve_async(&self, candidates: &[Assertion]) -> Resolution; + fn name(&self) -> &'static str; } ``` +## Current Implementations + +| Lens | Trait | Strategy | File | +|------|-------|----------|------| +| RecencyLens | Lens | Highest timestamp wins | `recency.rs` | +| ConsensusLens | Lens | Most common object value wins | `consensus.rs` | +| ConfidenceLens | Lens | Highest confidence field wins | `confidence.rs` | +| VoteAwareConsensusLens | AsyncLens | VoteStore vote counts | `vote_aware_consensus.rs` | +| TrustAwareAuthorityLens | AsyncLens | confidence * TrustRank | `trust_aware_authority.rs` | + +**API Mapping:** In the API, `LensDto::Authority` and `LensDto::TrustAwareAuthority` both route to `TrustAwareAuthorityLens`. Use `LensDto::Confidence` to get the simple confidence-field selector. + ## Principles -* **Stateless**: Lenses should generally be stateless (logic only). +* **Stateless**: Sync lenses must be stateless (logic only). * **Deterministic**: Same input + Same context = Same output. * **Fast**: This runs on every read. Avoid allocations. +* **Instrumented**: Every `resolve`/`resolve_async` impl MUST have `#[instrument]`. + +## Tracing Pattern (Required) + +Every lens resolve method must be instrumented: + +```rust +use tracing::instrument; + +impl Lens for MyLens { + #[instrument(skip(self, candidates), fields(candidates_count = candidates.len(), lens = "MyLens"))] + fn resolve(&self, candidates: &[Assertion]) -> Resolution { + // ... + } +} +``` ## Common Strategies ### 1. Recency (LWW) -Sort by `timestamp` descending. Return first. +Sort by `timestamp` descending. Return first. Tiebreaker: `source_hash`. ### 2. Consensus (Voting) -Map `object` -> `count`. Return object with `max(count)`. +Map `object` -> `count`. Return object with `max(count)`. From largest group, pick most recent. -### 3. Weighted Authority -Map `object` -> `sum(agent.reputation)`. Return object with `max(score)`. +### 3. Confidence +Return assertion with highest `confidence` field. Tiebreaker: most recent timestamp. +Uses the assertion's self-declared confidence, NOT agent reputation. + +### 4. Vote-Aware Consensus (Phase 2+) +Query VoteStore for real vote counts per assertion. Tiebreaker: confidence then timestamp. + +### 5. Trust-Aware Authority (Phase 2+) +weighted_score = confidence * TrustRank. Query TrustRankStore for agent reputation. ## Do -* Handle empty candidate sets gracefully. +* Handle empty candidate sets gracefully (return `Resolution::empty()`). * Implement `Default` for standard lenses. * Document the ranking logic clearly. +* Add `#[instrument]` with `candidates_count` and `lens` fields. +* Use `Resolution::with_winner()` for consistent output. ## Do Not -* Perform I/O inside a Lens (no DB lookups). Lenses operate on *fetched* candidates. +* Perform I/O inside a sync `Lens` (use `AsyncLens` if DB lookups are needed). +* Use `unwrap()` or `expect()` — workspace lints deny these. diff --git a/.claude/skills/use-case-gap-analysis/SKILL.md b/.claude/skills/use-case-gap-analysis/SKILL.md new file mode 100644 index 0000000..942c67a --- /dev/null +++ b/.claude/skills/use-case-gap-analysis/SKILL.md @@ -0,0 +1,266 @@ +--- +name: use-case-gap-analysis +description: Analyze gaps between use cases and current implementation. Use when validating product-market fit, planning milestones, or assessing technical debt against real scenarios. +--- + +# Use Case Gap Analysis + +## Identity + +You are a product-engineering bridge analyst. You read use cases with the eyes of a customer who needs the feature TODAY, and you read the codebase with the eyes of an engineer who knows what's actually implemented vs. planned. + +Your job: Expose the gap between "what we promise in use cases" and "what the code actually delivers." + +## Principles + +- **Truth Over Optimism**: If a use case claims a feature exists and the code doesn't have it, say so. Don't assume "we'll add it." +- **Pillars Are Mandatory**: Every gap must map to one of the Four Pillars (or it's not a real gap). +- **Roadmap Is Not Reality**: Something on the roadmap is NOT "done." Only committed code counts. +- **Customer Pain First**: Frame gaps as customer pain, not as technical TODOs. +- **Quantify When Possible**: "No audit trail" < "Agent queries cannot be traced for incident investigation." + +## Input Context + +This skill uses: + +### Use Cases +- `use-cases/README.md` - The Postgres Test and Four Pillars +- `use-cases/*.md` - Individual use case documents + +### Current State +- `roadmap.md` - What's planned vs. completed (checkboxes) +- `architecture.md` - Architectural overview +- `crates/*/src/**/*.rs` - Actual implementation + +### Reference +- `ai-lookup/` - Current feature documentation +- `.claude/agents/perspective-*.md` - Perspective agents (the users) + +## Protocol + +### Phase 1: Parse the Use Case + +Extract structured requirements from the use case document: + +```markdown +## Use Case: [Name] +### Claimed Features: +1. [Feature name] - [Quote from use case showing the claim] + - Pillar: [Which of the Four Pillars] + - API Surface: [Expected endpoint/tool/CLI command] + - Latency Requirement: [If mentioned, e.g., "<100ms"] + +2. [Next feature...] +``` + +For each feature, identify: +- The exact claim made in the use case +- Which pillar it maps to (if none, it fails the Postgres Test) +- What API the use case implies exists + +### Phase 2: Check Implementation Status + +For each claimed feature, determine status: + +| Status | Meaning | Evidence Required | +|--------|---------|-------------------| +| **Implemented** | Code exists and works | Link to crate/module + test | +| **Scaffolded** | Types exist, no logic | Link to types, note missing impl | +| **Roadmapped** | In roadmap, no code | Link to roadmap checkbox | +| **Aspirational** | Use case claims it, roadmap doesn't mention | Gap! | +| **Impossible** | Architecture can't support this | Architectural blocker | + +Check order: +1. Grep for types/traits in `crates/` +2. Check roadmap.md for checkbox status +3. Check ai-lookup/ for documented features +4. Read relevant crate code to verify implementation depth + +### Phase 3: Build the Gap Matrix + +Create a table mapping use case features to implementation: + +```markdown +## Gap Matrix: [Use Case Name] + +| Feature | Use Case Claim | Pillar | Status | Evidence | Gap | +|---------|---------------|--------|--------|----------|-----| +| Lifecycle filter | "Lens enforces lifecycle" | Contradiction | Scaffolded | `LifecycleStage` enum exists | No lens enforcement | +| Query audit | "<500ms trace command" | Consensus | Roadmapped | roadmap.md Phase 2 | No implementation | +``` + +### Phase 4: Prioritize by Customer Pain + +Not all gaps are equal. Rank by: + +1. **Blocker**: Use case is impossible without this feature +2. **Degraded**: Use case works but fails the Postgres Test (could be done with Postgres) +3. **Inconvenient**: Feature missing but workaround exists +4. **Nice-to-have**: Mentioned in use case but not core to the scenario + +For each blocker/degraded gap, write: + +```markdown +### Gap: [Feature Name] + +**Customer Pain:** [Specific scenario where this hurts] +**Use Case Reference:** [Link to section] +**Pillar Violation:** [Which pillar can't be demonstrated] +**Current State:** [What exists today] +**Required for Demo:** [Yes/No - can the 5-minute demo run?] + +**Resolution Options:** +1. [Option A - implementation path] +2. [Option B - scope reduction in use case] +3. [Option C - move to different milestone] +``` + +### Phase 5: Generate Recommendations + +Produce actionable output: + +```markdown +## Recommendations + +### Must Fix Before Use Case Is Valid +1. [Feature] - [Why it's a blocker] + +### Should Fix for Credibility +1. [Feature] - [Why it fails Postgres Test without it] + +### Can Defer +1. [Feature] - [Why workaround is acceptable] + +### Should Remove from Use Case +1. [Feature] - [Why claim is misleading given architecture] +``` + +## Step Back: Before Delivering Analysis + +Challenge your analysis: + +### 1. The Reality Check +> "Am I being too harsh or too generous?" + +- Did I verify code actually exists (not just types)? +- Did I conflate "roadmapped" with "implemented"? +- Did I give credit for things that only have tests but no impl? + +### 2. The Pillar Check +> "Does every gap trace to a Pillar?" + +- If a gap doesn't map to a Pillar, is it a real gap? +- Am I missing gaps that would fail the Postgres Test? + +### 3. The Customer Check +> "Would a customer care about this gap?" + +- Some technical gaps don't affect use case validity +- Some "small" gaps completely break the demo + +### 4. The Scope Check +> "Is the use case overclaiming or is the code under-delivering?" + +- Sometimes the fix is to scope down the use case +- Sometimes the use case is reasonable and code is behind + +**After step back:** Revise gap severity if needed. + +## Do + +1. Read the ENTIRE use case before starting analysis +2. Grep crates/ for actual implementations, not just types +3. Check roadmap.md checkbox status rigorously +4. Quote specific use case claims when identifying gaps +5. Map every gap to a Pillar (or question if it's a real gap) +6. Prioritize by customer pain, not technical complexity +7. Suggest scope reduction when implementation is far off +8. Update ai-lookup/ entries when you find documentation gaps + +## Do Not + +1. Assume roadmap items are implemented +2. Give credit for types without logic +3. Report gaps that don't map to Pillars +4. Ignore latency requirements mentioned in use cases +5. Conflate "we could add this" with "this exists" +6. Create gaps for features the use case doesn't actually claim +7. Skip the 5-minute demo - if it can't run, that's a blocker + +## Decision Points + +**Before marking "Implemented":** Stop. Did I find a test that exercises this feature? Did I read the actual function body? + +**Before marking "Aspirational":** Stop. Did I check ai-lookup/? Did I check all crates, not just stemedb-core? + +**Before reporting a Blocker:** Stop. Is the 5-minute demo in the use case actually broken by this gap? + +## Constraints + +- NEVER mark a feature "Implemented" without linking to code AND test +- NEVER report a gap that doesn't map to one of the Four Pillars +- ALWAYS check the 5-minute demo section - if it can't run, that's the priority +- ALWAYS produce a Gap Matrix table, even if empty + +## Output Format + +The skill produces: + +```markdown +# Gap Analysis: [Use Case Name] + +## Summary +- **Use Case Status:** [Ready | Blocked | Partially Implementable] +- **Blockers:** [N] features missing +- **Degraded:** [N] features fail Postgres Test +- **5-Minute Demo:** [Runnable | Broken at step X] + +## Gap Matrix + +| Feature | Claim | Pillar | Status | Evidence | Gap | +|---------|-------|--------|--------|----------|-----| +| ... | ... | ... | ... | ... | ... | + +## Blockers + +### [Feature 1] +[Full gap analysis] + +### [Feature 2] +... + +## Degraded Features + +### [Feature 3] +... + +## Recommendations + +### Must Fix +1. ... + +### Should Fix +1. ... + +### Can Defer +1. ... + +### Should Remove from Use Case +1. ... + +## Appendix: Evidence Links + +- [Feature]: `crates/stemedb-core/src/types.rs:45` +- [Feature]: Not found in codebase +``` + +## Four Pillars Reference + +For quick mapping: + +| Pillar | What It Enables | Gap Indicator | +|--------|-----------------|---------------| +| **First-Class Contradiction** | DB holds conflicting facts | No lens, no lifecycle enforcement | +| **Invalidation Cascades** | Retracted evidence flags downstream | No epoch/supersession logic | +| **Multi-Signature Consensus** | Weighted trust via crypto | No signatures, no TrustRank | +| **Semantic Decay** | Old data fades from hot path | No decay calculation, no resurrection | diff --git a/.gitignore b/.gitignore index d11fe73..1af412c 100644 --- a/.gitignore +++ b/.gitignore @@ -34,3 +34,11 @@ Thumbs.db # Code quality reports .jscpd-report/ + +# Dependencies +node_modules/ +vendor/ +__pycache__/ + +# Temp +tmp/ diff --git a/CLAUDE.md b/CLAUDE.md index 68de1dd..dcbd7ce 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,16 +11,24 @@ A probabilistic knowledge graph database that stores Claims, not Facts. Append-o | **Understand the vision** | [vision.md](./vision.md) | | **See use cases** | [use-cases/README.md](./use-cases/README.md) | | **Understand architecture** | [architecture.md](./architecture.md) | +| **Learn data structures** | [docs/data-structures.md](./docs/data-structures.md) | | **See the roadmap** | [roadmap.md](./roadmap.md) | +| **Build apps on Episteme** | [docs/app-concepts/index.md](./docs/app-concepts/index.md) | +| **Consumer Health vertical** | [docs/app-concepts/consumer-health.md](./docs/app-concepts/consumer-health.md) | +| **Use Go SDK** | [ai-lookup/services/sdk.md](ai-lookup/services/sdk.md) | | **Write Rust code** | [.claude/guides/backend/rust-guidelines.md](.claude/guides/backend/rust-guidelines.md) | | **Set up local dev** | [.claude/guides/local/setup.md](.claude/guides/local/setup.md) | | **Run tests** | [.claude/guides/local/testing.md](.claude/guides/local/testing.md) | | **Understand quality checks** | [.claude/guides/local/quality-checks.md](.claude/guides/local/quality-checks.md) | | **Learn about simulation** | [ai-lookup/features/simulation.md](ai-lookup/features/simulation.md) | +| **Advance the simulator** | [arena-roadmap.md](./arena-roadmap.md) | | **Work on storage/DAG** | Load skill: `stemedb-core` | | **Implement a Lens** | Load skill: `stemedb-lens` | | **Plan a milestone** | `/plan-milestone` command | +| **Analyze use case gaps** | `/analyze-gaps` command | +| **Add an API endpoint** | [.claude/guides/backend/api-endpoints.md](.claude/guides/backend/api-endpoints.md) | | **Integrate with AI tools** | [.claude/guides/integrations/ai-coding-assistant-integration.md](.claude/guides/integrations/ai-coding-assistant-integration.md) | +| **ADK-Go + Episteme** | [.claude/guides/integrations/adk-go-episteme.md](.claude/guides/integrations/adk-go-episteme.md) | ## Critical Rules @@ -28,9 +36,11 @@ A probabilistic knowledge graph database that stores Claims, not Facts. Append-o - **Content-Addressed:** Assertion ID = BLAKE3 hash of content. - **No Unwrap:** NEVER use `unwrap()` or `expect()` in production code. CI enforces via `clippy::unwrap_used` and `clippy::expect_used` at deny level. - **Defensive Writes:** All writes go through WAL with fsync. -- **Zero-Copy:** Use `rkyv` for serialization. -- **Instrument Critical Paths:** Use `#[instrument]` on public methods in WAL, storage, and ingestion code. Include meaningful fields (key_len, payload_len, offset). +- **Zero-Copy:** Use `rkyv` for serialization. ALWAYS use `stemedb_core::serde::{serialize, deserialize}` — NEVER use raw `AllocSerializer` in production code. +- **Instrument Critical Paths:** Use `#[instrument]` on public methods in WAL, storage, ingestion, and lens code. Include meaningful fields (key_len, payload_len, offset, candidates_count, lens). +- **Structured Logging:** Use `tracing` (info!, warn!, error!) instead of `println!`/`eprintln!`. Clippy enforces via `print_stdout`/`print_stderr` at warn level. CLI binaries (e.g., `stemedb-sim`) may use `#![allow()]` for user-facing output. - **Document Changes:** Update `ai-lookup/` when adding new types/concepts. Keep skills in sync with code. +- **No Git Operations:** NEVER use git stash, git branch, git checkout, or any git operations unless the user explicitly tells you to. ## Quick Reference @@ -74,9 +84,20 @@ Write Path (Spine): Read Path (Cortex): ## Crates -| Crate | Purpose | -|-------|---------| -| `stemedb-core` | Assertion struct, types, storage traits | -| `stemedb-wal` | Write-ahead log (planned) | -| `stemedb-index` | Subject/Predicate indexing (planned) | -| `stemedb-lens` | Lens trait and implementations (planned) | +| Crate | Purpose | Status | +|-------|---------|--------| +| `stemedb-core` | Assertion, LifecycleStage, MaterializedView, types | ✅ Implemented | +| `stemedb-wal` | Write-ahead log with crash recovery | ✅ Implemented | +| `stemedb-storage` | KVStore, VoteStore, IndexStore, TrustRankStore | ✅ Implemented | +| `stemedb-ingest` | Ingestion pipeline with signature verification | ✅ Implemented | +| `stemedb-query` | Query engine, Materializer for O(1) MV: reads | ✅ Implemented | +| `stemedb-lens` | Lenses (Recency, Consensus, Authority, Vote/Trust-aware) | ✅ Implemented | +| `stemedb-api` | HTTP API with axum + utoipa OpenAPI docs | ✅ Implemented | +| `stemedb-sim` | Simulation for testing the pipeline | ✅ Implemented | + +## SDKs + +| SDK | Purpose | Status | +|-----|---------|--------| +| `sdk/go/steme` | Go HTTP client with Ed25519 signing and fluent builders | ✅ Implemented | +| `sdk/go/adk` | ADK-Go tools and callbacks for AI agents | ✅ Implemented | diff --git a/Cargo.toml b/Cargo.toml index d1983c8..7e4f18f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,10 @@ members = [ "crates/stemedb-wal", "crates/stemedb-storage", "crates/stemedb-ingest", + "crates/stemedb-query", + "crates/stemedb-lens", "crates/stemedb-sim", + "crates/stemedb-api", ] resolver = "2" @@ -20,4 +23,6 @@ missing_docs = "warn" [workspace.lints.clippy] unwrap_used = "deny" expect_used = "deny" -panic = "deny" \ No newline at end of file +panic = "deny" +print_stdout = "warn" # Use tracing instead; allowed in CLI binaries +print_stderr = "warn" # Use tracing instead; allowed in CLI binaries \ No newline at end of file diff --git a/ai-lookup/features/query-audit.md b/ai-lookup/features/query-audit.md index c1d9274..a8ed3fe 100644 --- a/ai-lookup/features/query-audit.md +++ b/ai-lookup/features/query-audit.md @@ -1,6 +1,7 @@ # Query Audit Trail > **Quick Ref:** Every query is logged with provenance for incident investigation +> **Status:** ✅ Implemented (Phase 2) ## The Problem @@ -10,64 +11,101 @@ Postgres query logs show SQL, not semantic meaning. ## The Solution +Every query to the Episteme API is automatically logged with full provenance: + ```rust -struct QueryAudit { - pub query_id: Hash, - pub agent_id: AgentId, +/// Stored at `AUD:{query_id}` in the KV store. +pub struct QueryAudit { + pub query_id: QueryId, // Content-addressed hash + pub agent_id: Option<[u8; 32]>, // From X-Agent-Id header pub timestamp: u64, - pub subject: EntityId, - pub predicate: RelationId, - pub lens: LensType, - pub lifecycle_filter: Option, - pub result_hash: Hash, + pub params: QueryParams, // Subject, predicate, lifecycle, epoch, lens + pub result_hash: Option, // Hash of winning assertion pub result_confidence: f32, pub contributing_assertions: Vec, } -struct ContributingAssertion { +pub struct ContributingAssertion { pub assertion_hash: Hash, - pub weight: f32, // How much it influenced result + pub weight: f32, // How much it influenced result (1.0 for winner) pub source_hash: Hash, // Original evidence + pub lifecycle: LifecycleStage, } ``` +## Storage Layout + +| Key Pattern | Value | Purpose | +|-------------|-------|---------| +| `AUD:{query_id}` | Serialized QueryAudit | Individual audit records | +| `AUDA:{agent_id}:{timestamp}:{query_id}` | Empty | Agent index for temporal queries | + ## API -```bash -# What queries did this agent run? -GET /audit/queries?agent=deployment-agent&from=2024-01-15T20:00:00Z +### List Query Audits -# Trace command for incident investigation -episteme trace --agent deployment-agent \ - --time "6 hours ago" \ - --subject "auth/*" +```bash +# List recent audits +GET /v1/audit/queries?limit=100 + +# Filter by agent +GET /v1/audit/queries?agent_id=&from=1704067200&to=1704153600 +``` + +### Get Specific Audit + +```bash +# Full reasoning trace for a single query +GET /v1/audit/query/{query_id} +``` + +### Including Agent ID in Queries + +To associate queries with an agent, include the `X-Agent-Id` header: + +```bash +curl -H "X-Agent-Id: " \ + "http://localhost:3000/v1/query?subject=Tesla&predicate=revenue" ``` ## Response Format ```json { - "query_id": "q_7f3a2b...", - "timestamp": "2024-01-15T21:03:47Z", - "subject": "auth/jwt", - "predicate": "signing_algorithm", - "lens": "authority", - "lifecycle_filter": null, - "result": { - "value": "ES256", - "confidence": 0.87 + "query_id": "a7f3a2b9c1d4e5f6...", + "agent_id": "01020304...", + "timestamp": 1704153600, + "params": { + "subject": "auth/jwt", + "predicate": "signing_algorithm", + "lifecycle": "Approved", + "lens": "Authority" }, + "result_hash": "b8c9d0e1f2a3...", + "result_confidence": 0.87, "contributing_assertions": [ { - "hash": "rfc_2024_001...", - "lifecycle": "Proposed", - "weight": 0.9, - "source": "security-rfc-2024.md" + "assertion_hash": "c1d2e3f4a5b6...", + "weight": 1.0, + "source_hash": "d2e3f4a5b6c7...", + "lifecycle": "Approved" + }, + { + "assertion_hash": "e3f4a5b6c7d8...", + "weight": 0.0, + "source_hash": "f4a5b6c7d8e9...", + "lifecycle": "Proposed" } ] } ``` +## Implementation Details + +- **Query ID Generation:** Content-addressed hash of params + timestamp for deterministic IDs +- **Fire-and-Forget:** Audit logging doesn't block the query response; failures are logged but don't fail queries +- **Agent Index:** Enables O(1) lookups by agent + time range via prefix scan + ## Latency Requirements (from user research) | Query Type | Target Latency | @@ -77,6 +115,12 @@ episteme trace --agent deployment-agent \ | Audit trace | < 2s | | Full provenance chain | < 5s | +## Crates + +- **Types:** `stemedb_core::types::{QueryAudit, QueryParams, ContributingAssertion}` +- **Storage:** `stemedb_storage::{AuditStore, GenericAuditStore}` +- **API Handlers:** `stemedb_api::handlers::audit::{list_audits, get_audit}` + ## Origin This feature emerged from SRE perspective interviews (see `.claude/agents/perspective-oncall-sre.md`). Core need: "I need to trace from agent decision → query → assertions in under 10 minutes." diff --git a/ai-lookup/features/simulation.md b/ai-lookup/features/simulation.md index 4824d03..74f3032 100644 --- a/ai-lookup/features/simulation.md +++ b/ai-lookup/features/simulation.md @@ -1,7 +1,8 @@ -# Simulation System ("The Infinite Game") +# Simulation System ("The Arena") **Last Updated:** 2026-01-31 **Confidence:** High +**Status:** Phase 1 Complete (Spine validation) ## Summary @@ -13,7 +14,10 @@ The Simulation is an Agent-Based Modeling (ABM) environment that validates Steme - Architecture: `stemedb-sim` binary orchestrating agent swarms via tokio - Agents communicate **only** through StemeDB reads/writes -**File Pointer:** `/simulation-vision.md` (full vision document) +**File Pointers:** +- Implementation: `crates/stemedb-sim/src/main.rs` +- Vision document: `/simulation-vision.md` +- Incremental roadmap: `/arena-roadmap.md` ## Agent Personas @@ -47,8 +51,29 @@ Tracked via Prometheus/Grafana: - `agent_reputation_distribution` - Reputation spread - `fork_depth_max` - Deepest branch depth +## Current Status + +The simulator currently validates **Phase 1: The Spine** (WAL + Ingestor + KV Store). It proves the write path works end-to-end with signature verification. + +**What's implemented:** +- 3 agents (2 Scientists, 1 Troll) +- 10 ticks of assertion creation +- Ed25519 signature verification +- WAL → Ingestor → KV Store pipeline + +**What's NOT implemented yet:** +- Query path (uses direct KV access, not QueryEngine) +- Voting and consensus +- TrustRank reputation +- Concurrent agents +- Agent persona differentiation + +## Roadmap + +See [arena-roadmap.md](/arena-roadmap.md) for the incremental path from current state to full ABM environment. + ## Related Topics -- [TrustRank](./trustrank.md) - Reputation algorithm +- [TrustRank](./trust-rank.md) - Reputation algorithm - [Branching](./branching.md) - Fork mechanics - [Lens System](../services/lens.md) - Query resolution diff --git a/ai-lookup/features/trust-rank.md b/ai-lookup/features/trust-rank.md new file mode 100644 index 0000000..c7a1f57 --- /dev/null +++ b/ai-lookup/features/trust-rank.md @@ -0,0 +1,175 @@ +# TrustRank + +**Last Updated:** 2026-01-31 +**Confidence:** High +**Status:** Implemented in `stemedb-storage` v0.1.0 + +## Summary + +TrustRank is a per-agent reputation system that tracks accuracy and weights assertions in the Authority lens. This is the foundation of "The Hive" learning loop, enabling closed-loop learning where agent predictions are validated against reality. + +**Key Facts:** +- Agent reputation scores range [0.0, 1.0] +- Default score for new agents: 0.5 +- Accurate predictions increase reputation (+0.05) +- Inaccurate predictions decrease reputation (-0.1, higher penalty to discourage spam) +- Confidence half-life: Scores decay over time (default 30 days) +- Content-addressed by agent Ed25519 public key + +**File Pointer:** `crates/stemedb-storage/src/trust_rank_store.rs` + +## Data Model + +```rust +pub struct TrustRank { + pub agent_id: [u8; 32], // Ed25519 public key + pub score: f32, // Reputation [0.0, 1.0] + pub last_updated: u64, // Unix timestamp + pub assertions_count: u64, // Total assertions made + pub accuracy_count: u64, // Correct assertions +} +``` + +**Storage Layout:** +- Key: `TR:{agent_id}` (32-byte Ed25519 public key) +- Value: Serialized TrustRank (rkyv) + +## Operations + +### Get TrustRank + +```rust +let trust = trust_store.get_trust_rank(&agent_id).await?; +``` + +Returns default TrustRank (score 0.5) for new agents. + +### Update TrustRank + +```rust +let new_score = trust_store.update_trust_rank(&agent_id, delta, timestamp).await?; +``` + +Adjusts score by delta, clamped to [0.0, 1.0]. + +### Record Outcome (Learning Loop) + +```rust +let new_score = trust_store.record_outcome(&agent_id, was_accurate, timestamp).await?; +``` + +**Learning Rules:** +- `was_accurate = true`: score += 0.05, accuracy_count++ +- `was_accurate = false`: score -= 0.1, assertions_count++ only +- Both: assertions_count++ + +### Apply Decay + +```rust +let decayed_count = trust_store.decay_trust_ranks(current_timestamp, None).await?; +``` + +**Decay Formula:** +``` +score = score * (0.5 ^ (elapsed_days / half_life_days)) +``` + +Default half-life: 30 days. Custom half-life can be provided. + +## The Hive Learning Loop + +``` +1. Agent submits assertion with confidence 0.8 + -> TrustRank lookup: 0.7 (experienced agent) + -> Weighted score: 0.8 * 0.7 = 0.56 + +2. Reality assertion arrives (e.g., official data) + -> Compare: Did the agent's prediction match? + +3. Outcome recorded: + -> If accurate: TrustRank 0.7 -> 0.75 + -> If inaccurate: TrustRank 0.7 -> 0.6 + +4. Future assertions from this agent weighted accordingly +``` + +## Integration with Authority Lens + +The TrustAwareAuthorityLens uses TrustRank to weight assertions: + +```rust +use stemedb_lens::TrustAwareAuthorityLens; + +let lens = TrustAwareAuthorityLens::new(trust_store); +let resolution = lens.resolve_async(&candidates).await; + +// Resolution selects assertion with highest: +// weighted_score = assertion.confidence * agent.trust_rank +``` + +**Example Scenario:** + +| Agent | Assertion Confidence | TrustRank | Weighted Score | Winner? | +|-------|---------------------|-----------|----------------|---------| +| Novice | 0.95 | 0.2 | 0.19 | No | +| Expert | 0.8 | 0.7 | 0.56 | No | +| Master | 0.75 | 0.95 | 0.7125 | ✅ Yes | + +The Master's assertion wins despite lower raw confidence because their reputation is highest. + +## Decay Mechanics + +TrustRank decays over time to reflect that past accuracy doesn't guarantee future accuracy. + +**Half-Life Examples:** + +| Initial Score | Time Elapsed | Final Score | +|--------------|--------------|-------------| +| 1.0 | 30 days | 0.5 | +| 1.0 | 60 days | 0.25 | +| 0.8 | 30 days | 0.4 | +| 0.5 | 30 days | 0.25 | + +**Why Decay?** +- Agents may become less accurate over time (model drift, outdated knowledge) +- Prevents "tenured" agents from coasting on past reputation +- Forces continuous demonstration of accuracy + +## Testing + +Comprehensive test coverage in `trust_rank_store.rs`: + +```rust +#[tokio::test] +async fn test_record_outcome_updates_score() { + let trust_store = GenericTrustRankStore::new(store); + let agent_id = [1u8; 32]; + + // Record accurate outcome + let score = trust_store.record_outcome(&agent_id, true, 1000).await?; + assert!((score - 0.55).abs() < 0.001); // 0.5 + 0.05 + + // Record inaccurate outcome + let score = trust_store.record_outcome(&agent_id, false, 2000).await?; + assert!((score - 0.45).abs() < 0.001); // 0.55 - 0.1 + + let trust = trust_store.get_trust_rank(&agent_id).await?; + assert_eq!(trust.assertions_count, 2); + assert_eq!(trust.accuracy_count, 1); + assert_eq!(trust.accuracy_rate(), 0.5); +} +``` + +## Future Enhancements + +- **Domain-Specific TrustRank:** Track reputation per subject/predicate domain +- **Multi-Signature Aggregation:** Combine TrustRanks of all signers, not just primary +- **Adaptive Learning Rates:** Adjust delta based on agent's history +- **Trust Graph:** Factor in reputation of agents who vouch for this agent +- **Adversarial Detection:** Identify and penalize coordinated attacks + +## Related Topics + +- [Lens](../services/lens.md) - TrustAwareAuthorityLens integration +- [The Hive](../../vision.md) - Learning loop vision +- [Simulation](./simulation.md) - Testing TrustRank in controlled scenarios diff --git a/ai-lookup/features/trustrank.md b/ai-lookup/features/trustrank.md index 9188c18..ca1934d 100644 --- a/ai-lookup/features/trustrank.md +++ b/ai-lookup/features/trustrank.md @@ -1,65 +1,96 @@ # TrustRank (Reputation) -**Last Updated:** 2025-01-31 -**Confidence:** Medium (planned feature) +**Last Updated:** 2026-02-01 +**Confidence:** High +**Status:** Implemented in `stemedb-storage` v0.1.0 ## Summary -TrustRank is a recursive PageRank-style algorithm for agent credibility. Agents who make accurate claims early gain reputation; agents who contradict settled truth lose reputation. +TrustRank is a reputation system for agent credibility. Agents who make accurate claims gain reputation; agents who contradict settled truth lose reputation. **Key Facts:** -- Stored in `A:{AgentId}` key in KV store -- Background "Gardener" process calculates scores -- Used by `Authority` lens to weight assertions -- Reputation decays for low-confidence agents +- Stored in `TR:{AgentId}` key in KV store via `TrustRankStore` trait +- Scores bounded to [0.0, 1.0], default 0.5 for new agents +- Used by `TrustAwareAuthorityLens` to weight assertions +- Confidence decays over time (30-day half-life by default) -**File Pointer:** `crates/stemedb-gardener/src/trustrank.rs` (planned, Phase 4) +**File Pointer:** `crates/stemedb-storage/src/trust_rank_store.rs` -## How It Works - -### Validation Loop (Gardener) - -``` -Every N hours: -1. Find "Settled Facts" (>99% consensus over T time) -2. For each settled fact: - - Reward agents who claimed it early (+R) - - Punish agents who claimed opposite (-R) -3. Update A:{AgentId} scores -4. Back-propagate: high-R agents boost sources they cite -``` - -### Usage in Authority Lens +## TrustRank Record ```rust -impl Lens for AuthorityLens { - fn resolve(&self, candidates: &[Assertion], ctx: &QueryContext) -> LensResult { - // Weight by agent reputation - let weighted: Vec<_> = candidates.iter() - .map(|a| { - let rep = ctx.get_reputation(&a.agent); - (a, rep) - }) - .collect(); - - // Return highest weighted assertion - weighted.into_iter() - .max_by_key(|(_, rep)| *rep) - .map(|(a, _)| a.clone()) - } +pub struct TrustRank { + pub agent_id: [u8; 32], + pub score: f32, // 0.0 to 1.0 + pub last_updated: u64, // Unix timestamp + pub assertions_count: u64, + pub accuracy_count: u64, } ``` -## Reputation Score Range +## How It Works + +### Score Updates + +```rust +// Record an outcome for an agent +trust_store.record_outcome(&agent_id, was_accurate, timestamp).await?; + +// Accurate prediction: +0.05 (capped at 1.0) +// Inaccurate prediction: -0.1 (floored at 0.0) +// Higher penalty for inaccuracy discourages spam +``` + +### Confidence Decay + +```rust +// Apply time-based decay to all scores +trust_store.decay_trust_ranks(current_timestamp, Some(custom_half_life)).await?; + +// Default half-life: 30 days +// Score approaches 0.5 (neutral) over time without activity +``` + +### Usage in TrustAwareAuthorityLens + +```rust +use stemedb_lens::TrustAwareAuthorityLens; +use stemedb_storage::{SledStore, GenericTrustRankStore}; +use std::sync::Arc; + +let store = SledStore::open("./data")?; +let trust_store = Arc::new(GenericTrustRankStore::new(store)); +let lens = TrustAwareAuthorityLens::new(trust_store); + +let resolution = lens.resolve_async(&candidates).await; +// Winner = assertion with highest (confidence * trust_rank) +``` + +**Resolution Strategy:** +1. For each candidate, lookup signer's TrustRank (O(1)) +2. Calculate: `weighted_score = assertion.confidence * agent.trust_rank` +3. Return assertion with highest weighted score +4. Tiebreaker: most recent timestamp +5. Unsigned assertions treated as 0.0 trust + +## Score Interpretation | Score | Meaning | |-------|---------| -| 0-300 | Unreliable (spam, noise) | -| 300-600 | Neutral (unproven) | -| 600-900 | Reliable (track record) | -| 900-1000 | Authoritative (expert) | +| 0.0-0.3 | Unreliable (history of inaccuracy) | +| 0.3-0.5 | Below neutral (more wrong than right) | +| 0.5 | Neutral (new agent or unknown) | +| 0.5-0.7 | Above neutral (more right than wrong) | +| 0.7-1.0 | Reliable (strong track record) | + +## API Access + +**Via LensDto:** +- `lens=Authority` → Routes to `TrustAwareAuthorityLens` +- `lens=TrustAwareAuthority` → Routes to `TrustAwareAuthorityLens` +- `lens=Confidence` → Uses confidence field only (no TrustRank) ## Related Topics -- [Lens](../services/lens.md) -- [Roadmap Phase 4](../../../roadmap.md) +- [Lens](../services/lens.md) - TrustAwareAuthorityLens integration +- [Assertion](../services/assertion.md) - Signature and agent_id fields diff --git a/ai-lookup/index.md b/ai-lookup/index.md index 69626b0..31a5230 100644 --- a/ai-lookup/index.md +++ b/ai-lookup/index.md @@ -7,10 +7,14 @@ Token-efficient fact storage for StemeDB. Query these for quick context without | Topic | File | Confidence | Updated | Summary | |-------|------|------------|---------|---------| | Assertion | `services/assertion.md` | High | 2025-01-31 | Core data structure for all claims | +| Ballot Box | `services/ballot-box.md` | High | 2026-01-31 | High-velocity vote storage (VoteStore) | | Ingestor | `services/ingestor.md` | High | 2026-01-31 | WAL-to-KV background worker | -| Lens | `services/lens.md` | High | 2025-01-31 | Read-time resolution strategies | +| Lens | `services/lens.md` | High | 2026-01-31 | Read-time resolution strategies (includes TrustAwareAuthority) | | Lifecycle | `services/lifecycle.md` | High | 2026-01-31 | Proposed/Approved state machine | -| Storage | `services/storage.md` | High | 2025-01-31 | KV layout and write path | +| Materializer | `services/materializer.md` | High | 2026-01-31 | Background worker for O(1) reads via MV: keys | +| API Surface | `services/api.md` | High | 2026-01-31 | HTTP API with axum + utoipa OpenAPI | +| SDK | `services/sdk.md` | High | 2026-02-01 | Go client libraries (core + ADK-Go integration) | +| Storage | `services/storage.md` | High | 2026-01-31 | KV layout and write path | ## Patterns @@ -18,6 +22,7 @@ Token-efficient fact storage for StemeDB. Query these for quick context without |-------|------|------------|---------|---------| | ADK-Go Integration | `patterns/adk-integration.md` | High | 2026-01-31 | Tool definitions and callbacks for agents | | Content-Addressing | `patterns/content-addressing.md` | High | 2025-01-31 | BLAKE3 hashing for immutability | +| API Documentation | `patterns/api-documentation.md` | High | 2026-01-31 | utoipa + OpenAPI + Slate DRY pipeline | | Error Handling | `patterns/error-handling.md` | High | 2025-01-31 | thiserror + context pattern | ## Features @@ -27,7 +32,7 @@ Token-efficient fact storage for StemeDB. Query these for quick context without | Branching | `features/branching.md` | Medium | 2025-01-31 | "Fork Reality" overlay graphs | | Gardener | `features/gardener.md` | High | 2026-01-31 | TrustRank back-propagation on errors | | Query Audit | `features/query-audit.md` | High | 2026-01-31 | Trace agent decisions for debugging | -| TrustRank | `features/trustrank.md` | Medium | 2025-01-31 | Agent reputation system | +| TrustRank | `features/trust-rank.md` | High | 2026-01-31 | Agent reputation system with learning loop | | Simulation | `features/simulation.md` | High | 2026-01-31 | Agent-based modeling for validation | ## Use Cases diff --git a/ai-lookup/patterns/api-documentation.md b/ai-lookup/patterns/api-documentation.md new file mode 100644 index 0000000..e9a73b4 --- /dev/null +++ b/ai-lookup/patterns/api-documentation.md @@ -0,0 +1,54 @@ +# API Documentation Pattern + +**Last Updated:** 2026-01-31 +**Confidence:** High + +## Summary + +Episteme uses a "define once, document everywhere" approach. Rust types are the single source of truth for both runtime behavior and API documentation. The `utoipa` crate generates OpenAPI 3.1 specs at compile time from derive macros on the same structs used for JSON serialization. + +**Key Facts:** +- `utoipa` chosen over `aide` for compile-time generation and framework-agnostic design +- `utoipa-axum` provides `OpenApiRouter` that collects handler metadata automatically +- `utoipa-swagger-ui` serves interactive docs in dev mode +- `widdershins` converts OpenAPI JSON to Slate-compatible markdown in CI +- No separate schema files to maintain; types ARE the schema + +## The Stack + +| Layer | Tool | Purpose | +|-------|------|---------| +| Type definitions | `serde` + `utoipa::ToSchema` | Single struct defines JSON shape AND OpenAPI schema | +| Handler docs | `#[utoipa::path]` | Documents endpoint alongside implementation | +| Router | `utoipa_axum::OpenApiRouter` | Collects all handler metadata automatically | +| Spec output | `/api-doc/openapi.json` | OpenAPI 3.1 spec, no build step | +| Dev UI | `utoipa-swagger-ui` | Interactive API explorer at `/swagger-ui` | +| Published docs | `widdershins` + Slate | CI generates static docs from OpenAPI spec | + +## Adding a New Endpoint (Quick Reference) + +1. Define DTO types with `#[derive(Serialize, Deserialize, ToSchema)]` +2. Write handler function +3. Annotate with `#[utoipa::path(post, path = "/foo", ...)]` +4. Register on `OpenApiRouter` - docs update automatically +5. No manual schema sync needed + +**File Pointer:** `.claude/guides/backend/api-endpoints.md` for full procedure. + +## Why utoipa Over aide + +- Compile-time generation fits zero-cost philosophy +- Framework-agnostic (future gRPC won't require rewrite) +- Larger ecosystem (SwaggerUI, Redoc, Scalar, RapiDoc crates) +- Already macro-heavy codebase (rkyv derives) - one more derive is natural + +## gRPC (Future) + +When added, `.proto` files will be the source for gRPC docs via `protoc-gen-doc`. +Both HTTP and gRPC will share the same internal types via `From<>` conversions. +The DTO layer keeps internal `rkyv` types separate from public API contracts. + +## Related Topics + +- [API Service](../services/api.md) - Endpoints and crate structure +- [Error Handling](./error-handling.md) - thiserror + context pattern diff --git a/ai-lookup/patterns/error-handling.md b/ai-lookup/patterns/error-handling.md index ce3bf0d..70dddd9 100644 --- a/ai-lookup/patterns/error-handling.md +++ b/ai-lookup/patterns/error-handling.md @@ -1,6 +1,6 @@ # Error Handling Pattern -**Last Updated:** 2025-01-31 +**Last Updated:** 2026-01-31 **Confidence:** High ## Summary @@ -8,12 +8,19 @@ StemeDB uses `thiserror` for library errors with context chains. No panics in production code. All fallible operations return `Result`. **Key Facts:** -- Library code: `thiserror` for custom error types +- Library code: `thiserror` for custom error types — ALL error enums MUST use `#[derive(thiserror::Error)]` - Binary code: `anyhow` for error chaining - Never use `unwrap()`, `expect()`, `panic!()` in production - Add context with `.context("what we were doing")?` +- NEVER use manual `impl Display` + `impl Error` for error types — use thiserror derives instead -**File Pointer:** `crates/stemedb-core/src/error.rs` (planned) +**Error types in workspace (all use thiserror):** +- `stemedb-core/src/serde.rs` — `SerdeError` +- `stemedb-wal/src/error.rs` — `QuarantineError` +- `stemedb-storage/src/error.rs` — `StorageError` +- `stemedb-ingest/src/error.rs` — `IngestError` +- `stemedb-query/src/error.rs` — `QueryError` +- `stemedb-api/src/error.rs` — `ApiError` ## The Pattern diff --git a/ai-lookup/services/api.md b/ai-lookup/services/api.md new file mode 100644 index 0000000..fad6110 --- /dev/null +++ b/ai-lookup/services/api.md @@ -0,0 +1,63 @@ +# API Surface + +**Last Updated:** 2026-02-01 +**Confidence:** High + +## Summary + +Episteme exposes an HTTP API via `axum` with auto-generated OpenAPI 3.1 documentation. The API is a thin layer that wires HTTP handlers to existing library crates (QueryEngine, Ingestor, VoteStore). Documentation is generated from the same Rust types used for serialization via `utoipa` derive macros. + +**Key Facts:** +- Framework: `axum` with `utoipa-axum` for OpenAPI integration +- Crate: `stemedb-api` +- DTO layer converts between internal `rkyv` types and public `serde` JSON types +- OpenAPI 3.1 spec auto-generated at `/api-doc/openapi.json` +- Interactive docs via Swagger UI at `/swagger-ui` (dev mode) +- gRPC deferred; HTTP/JSON is the initial interface + +**File Pointers:** +- `crates/stemedb-api/src/lib.rs` - App builder and OpenApiRouter +- `crates/stemedb-api/src/dto.rs` - Request/Response types (serde + ToSchema) +- `crates/stemedb-api/src/handlers/` - Route handlers + +## Endpoints + +| Method | Path | Description | Status | +|--------|------|-------------|--------| +| `POST` | `/v1/assert` | Submit signed assertion, writes to WAL | ✅ Implemented | +| `POST` | `/v1/epoch` | Create new epoch (paradigm) with content-addressed ID | ✅ Implemented | +| `POST` | `/v1/vote` | High-throughput vote submission | ✅ Implemented | +| `GET` | `/v1/query` | Resolve assertions via Lens | ✅ Implemented | +| `GET` | `/v1/skeptic` | Conflict analysis (Trust but Verify) | ✅ Implemented | +| `GET` | `/v1/health` | Service health check | ✅ Implemented | +| `GET` | `/v1/audit/queries` | List query audit trail | ✅ Implemented | +| `GET` | `/v1/audit/query/{id}` | Get specific query audit | ✅ Implemented | +| `GET` | `/v1/trace` | Trace assertion lineage | ✅ Implemented | +| `GET` | `/v1/meter/quota` | Check remaining quota | ✅ Implemented | +| `POST` | `/v1/meter/quota/limit` | Set custom quota limit (admin) | ✅ Implemented | +| `GET` | `/api-docs/openapi.json` | OpenAPI 3.1 spec | ✅ Implemented | +| `GET` | `/swagger-ui` | Interactive API docs | ✅ Implemented | + +## DRY Type Pipeline + +``` +stemedb-core types (rkyv) ← Internal storage format + | + | impl From<> / Into<> + v +stemedb-api DTOs (serde + ToSchema) ← Public API contract + | + | utoipa derive macros + v +OpenAPI 3.1 JSON ← Auto-generated spec + | + | Widdershins (CI) + v +Slate markdown ← Published docs +``` + +## Related Topics + +- [Storage](./storage.md) - KV layout and write path +- [Lens](./lens.md) - Read-time resolution strategies +- [API Documentation Pattern](../patterns/api-documentation.md) - Toolchain details diff --git a/ai-lookup/services/assertion.md b/ai-lookup/services/assertion.md index 5fd0edf..4f4a233 100644 --- a/ai-lookup/services/assertion.md +++ b/ai-lookup/services/assertion.md @@ -1,6 +1,6 @@ # Assertion -**Last Updated:** 2025-01-31 +**Last Updated:** 2026-01-31 **Confidence:** High ## Summary @@ -10,32 +10,58 @@ The Assertion is the atomic unit of Episteme. It represents a signed claim about **Key Facts:** - Immutable once written (append-only) - Content-addressed by BLAKE3 hash -- Contains: subject, predicate, object, source, agent, timestamp +- Contains: subject, predicate, object, lifecycle, source, signatures, timestamp +- Lifecycle stage distinguishes proposals from production-ready truth - Optionally includes vector embedding for semantic search -**File Pointer:** `crates/stemedb-core/src/assertion.rs` (planned) +**File Pointer:** `crates/stemedb-core/src/types.rs` ## Structure ```rust pub struct Assertion { + // The Fact (What) pub subject: EntityId, // "Tesla_Inc" pub predicate: RelationId, // "has_revenue" - pub object: ObjectValue, // Float(96.7B), String("Musk"), Ref(EntityId) - pub source: SourceHash, // Evidence pointer (PDF/URL hash) - pub agent: AgentId, // Ed25519 public key - pub timestamp: u64, // Wall clock time - pub vector: Option>, // Semantic embedding + pub object: ObjectValue, // Text, Number, Boolean, or Reference + + // Lineage (Why) + pub parent_hash: Option, // Fork pointer + pub source_hash: Hash, // Evidence pointer (PDF/URL hash) + pub visual_hash: Option, // Perceptual hash for visual anchoring + pub epoch: Option, // Paradigm context + pub lifecycle: LifecycleStage, // Proposed, UnderReview, Approved, Deprecated, Rejected + + // Meta-Cognition (Who/How sure) + pub signatures: Vec, // Multi-sig support + pub confidence: f32, // 0.0 to 1.0 + pub timestamp: u64, // Wall clock time + pub vector: Option>, // Semantic embedding } ``` +## Lifecycle Stages + +```rust +enum LifecycleStage { + Proposed, // Initial idea, RFC, suggestion + UnderReview, // Under active debate + Approved, // Production ready, safe for implementation + Deprecated, // Was true, now superseded + Rejected, // Considered and declined +} +``` + +New assertions default to `Proposed`. Lifecycle transitions are implemented as new assertions with `parent_hash` pointing to the previous version. + ## Identity -Assertion ID = BLAKE3(subject || predicate || object || agent || timestamp) +Assertion ID = BLAKE3(serialized assertion bytes) -Same content from same agent at same time = same hash. +Content-addressed: same content = same hash. ## Related Topics +- [Lifecycle Stages](./lifecycle.md) - [Storage Layout](./storage.md) - [Lens Resolution](./lens.md) diff --git a/ai-lookup/services/ballot-box.md b/ai-lookup/services/ballot-box.md new file mode 100644 index 0000000..12ca6cc --- /dev/null +++ b/ai-lookup/services/ballot-box.md @@ -0,0 +1,141 @@ +# The Ballot Box + +**Last Updated:** 2026-01-31 +**Confidence:** High +**Status:** Implemented + +## Summary + +The Ballot Box is Episteme's high-velocity vote ingestion system. It separates votes from assertions to enable thousands of agents to vote simultaneously without lock contention. + +**Key Facts:** +- Votes are append-only (immutable) +- Content-addressed by BLAKE3 hash +- O(1) vote counts via cached counters +- O(1) aggregate weights for Materializer +- Decoupled from Assertion mutations + +**File Pointer:** `crates/stemedb-storage/src/vote_store.rs` + +## Storage Layout + +| Key Pattern | Value | Purpose | +|-------------|-------|---------| +| `V:{assertion_hash}:{vote_hash}` | Serialized `Vote` | Individual votes | +| `VC:{assertion_hash}` | `u64` (LE bytes) | Vote count cache | +| `VW:{assertion_hash}` | `f32` (LE bytes) | Aggregate weight cache | + +## VoteStore Trait + +```rust +#[async_trait] +pub trait VoteStore: Send + Sync { + /// Store a vote and return its content-addressed hash + async fn put_vote(&self, vote: &Vote) -> Result; + + /// Get a specific vote by hash + async fn get_vote(&self, assertion_hash: &Hash, vote_hash: &Hash) -> Result>; + + /// Get all votes for an assertion (O(n)) + async fn get_votes_for_assertion(&self, assertion_hash: &Hash) -> Result>; + + /// Get vote count (O(1) via cache) + async fn get_vote_count(&self, assertion_hash: &Hash) -> Result; + + /// Get aggregate weight (O(1) via cache) + async fn get_aggregate_weight(&self, assertion_hash: &Hash) -> Result; + + /// Check if any votes exist + async fn has_votes(&self, assertion_hash: &Hash) -> Result; +} +``` + +## Usage Example + +```rust +use stemedb_storage::{SledStore, GenericVoteStore, VoteStore}; +use stemedb_core::types::Vote; + +// Create vote store backed by sled +let kv_store = SledStore::open("./data")?; +let vote_store = GenericVoteStore::new(kv_store); + +// High-velocity vote ingestion +let vote = Vote { + assertion_hash: [1u8; 32], + agent_id: [2u8; 32], + weight: 0.85, + signature: sig_bytes, + timestamp: now, +}; +let vote_hash = vote_store.put_vote(&vote).await?; + +// O(1) aggregation queries (for Materializer) +let count = vote_store.get_vote_count(&assertion_hash).await?; +let total_weight = vote_store.get_aggregate_weight(&assertion_hash).await?; +``` + +## Design Rationale + +### Why Separate Votes from Assertions? + +Traditional databases would store votes as a column or join table: + +```sql +-- Naive approach: votes as assertion metadata +UPDATE assertions SET vote_count = vote_count + 1 WHERE hash = ?; +``` + +**Problems:** +1. Lock contention when many agents vote on same assertion +2. Lost history (can't see who voted when) +3. Violates append-only semantics + +**Ballot Box Solution:** +1. Votes are separate, immutable records +2. Each vote is content-addressed +3. Caches enable O(1) aggregation +4. Full audit trail preserved + +### Cache Update Strategy + +When `put_vote()` is called: +1. Serialize vote with rkyv +2. Compute BLAKE3 hash (content address) +3. Store at `V:{assertion_hash}:{vote_hash}` +4. Increment `VC:{assertion_hash}` counter +5. Add weight to `VW:{assertion_hash}` sum + +The caches are updated atomically with the vote write, ensuring consistency. + +### Duplicate Vote Handling + +The VoteStore does NOT prevent duplicate votes - it stores whatever is submitted. Duplicate detection is a higher-level concern (e.g., "one vote per agent per assertion") that should be enforced at the API layer. + +This design choice keeps the storage layer simple and lets policy be defined elsewhere. + +## Integration with Materializer + +The Materializer (Phase 2) will use the VoteStore to update Materialized Views: + +```rust +// Materializer pseudocode +for assertion in new_assertions { + let votes = vote_store.get_votes_for_assertion(&assertion.hash).await?; + let weighted_score = calculate_consensus(votes, trustrank); + + if should_update_mv(weighted_score, current_mv) { + store.put( + format!("MV:{}:{}", assertion.subject, assertion.predicate), + assertion.serialize() + ).await?; + } +} +``` + +## Related Topics + +- [Storage](./storage.md) +- [Assertion](./assertion.md) +- [Architecture](../../../architecture.md) +- [Vision - The Ballot Box](../../../vision.md#4-2-the-ballot-box-high-velocity-consensus) diff --git a/ai-lookup/services/lens.md b/ai-lookup/services/lens.md index ad161fe..4168df2 100644 --- a/ai-lookup/services/lens.md +++ b/ai-lookup/services/lens.md @@ -1,7 +1,8 @@ # Lens -**Last Updated:** 2026-01-31 +**Last Updated:** 2026-02-01 **Confidence:** High +**Status:** Implemented in `stemedb-lens` v0.1.0 ## Summary @@ -13,26 +14,255 @@ A Lens resolves conflicting assertions into a deterministic answer at read time. - Fast (runs on every read, avoid allocations) - Pluggable (implement `Lens` trait) -**File Pointer:** `crates/stemedb-lens/src/lib.rs` (planned) +**File Pointer:** `crates/stemedb-lens/src/lib.rs` -## The Trait +## The Traits + +### Synchronous Lens ```rust -pub trait Lens { - fn resolve(&self, candidates: &[Assertion], context: &QueryContext) -> LensResult; +pub trait Lens: Send + Sync { + fn resolve(&self, candidates: &[Assertion]) -> Resolution; + fn name(&self) -> &'static str; } ``` +### Async Lens + +For lenses requiring I/O (e.g., VoteStore lookups): + +```rust +#[async_trait] +pub trait AsyncLens: Send + Sync { + async fn resolve_async(&self, candidates: &[Assertion]) -> Resolution; + fn name(&self) -> &'static str; +} +``` + +### Analysis Lens (Trust but Verify) + +For lenses that surface conflict instead of resolving it: + +```rust +#[async_trait] +pub trait AnalysisLens: Send + Sync { + async fn analyze(&self, candidates: &[Assertion]) -> ConflictAnalysis; + fn name(&self) -> &'static str; +} +``` + +Returns `ConflictAnalysis` with: +- `status`: Unanimous, Agreed, or Contested +- `conflict_score`: 0.0 (unanimous) to 1.0 (chaos) using normalized Shannon entropy +- `claims`: All distinct claims ranked by weight share + +## VoteAwareConsensus Implementation + +The VoteAwareConsensusLens integrates with the Ballot Box pattern (VoteStore) to resolve based on actual vote counts. + +**Resolution Strategy:** +1. For each candidate assertion, lookup vote count and aggregate weight (O(1) cached) +2. Rank by aggregate weight (sum of all vote weights) +3. Return assertion with highest aggregate weight +4. Tiebreaker: If weights equal, prefer most recent timestamp + +**Confidence Calculation:** +``` +confidence = winner_weight / total_weight_across_all_candidates +``` + +**Example:** +```rust +use stemedb_lens::VoteAwareConsensusLens; +use stemedb_storage::{SledStore, GenericVoteStore}; +use std::sync::Arc; + +let store = SledStore::open("./data").await?; +let vote_store = Arc::new(GenericVoteStore::new(store)); +let lens = VoteAwareConsensusLens::new(vote_store); + +let resolution = lens.resolve_async(&candidates).await; +``` + +## TrustAwareAuthority Implementation + +The TrustAwareAuthorityLens integrates with TrustRank to weight assertions by agent reputation. This is the foundation of "The Hive" learning loop. + +**Resolution Strategy:** +1. For each candidate assertion, lookup the primary signer's TrustRank (O(1) lookup) +2. Calculate weighted score: `assertion.confidence * agent.trust_rank` +3. Return assertion with highest weighted score +4. Tiebreaker: If scores equal, prefer most recent timestamp +5. New agents default to 0.5 trust score +6. Unsigned assertions treated as 0.0 trust + +**Confidence Calculation:** +``` +weighted_score = assertion.confidence * agent.trust_rank +confidence = weighted_score // Direct weighted score +``` + +**TrustRank Learning Loop:** +- Agents start at 0.5 (neutral) +- Accurate predictions: +0.05 per correct assertion +- Inaccurate predictions: -0.1 per incorrect assertion (higher penalty discourages spam) +- Confidence half-life: Scores decay over 30 days by default +- Scores bounded to [0.0, 1.0] + +**Example:** +```rust +use stemedb_lens::TrustAwareAuthorityLens; +use stemedb_storage::{SledStore, GenericTrustRankStore}; +use std::sync::Arc; + +let store = SledStore::open("./data").await?; +let trust_store = Arc::new(GenericTrustRankStore::new(store)); +let lens = TrustAwareAuthorityLens::new(trust_store); + +let resolution = lens.resolve_async(&candidates).await; + +// Record outcome for learning +trust_store.record_outcome(&agent_id, was_accurate, timestamp).await?; + +// Apply decay periodically +trust_store.decay_trust_ranks(current_timestamp, None).await?; +``` + ## Standard Lenses -| Lens | Strategy | Use Case | -|------|----------|----------| -| Recency | Latest timestamp wins | News, real-time | -| Consensus | Highest vote count | Democratic truth | -| Authority | Weighted by agent reputation | Expert truth | -| Skeptic | Returns variance/conflict | Finding controversy | -| EpochAware | Filters superseded epochs first | Paradigm-safe queries | -| Constraints | Returns `must_use`/`forbidden` predicates | Pre-flight checks | +| Lens | Strategy | Use Case | Status | +|------|----------|----------|--------| +| Recency | Latest timestamp wins | News, real-time | ✅ Implemented | +| Consensus | Most common object value | Democratic truth (basic) | ✅ Implemented | +| VoteAwareConsensus | Highest vote weight from VoteStore | Democratic truth (advanced) | ✅ Implemented | +| Confidence | Highest assertion `confidence` field | Source-declared certainty | ✅ Implemented | +| Authority | Alias for TrustAwareAuthority | Reputation-weighted (user-friendly name) | ✅ Implemented | +| TrustAwareAuthority | Weighted by TrustRank reputation | Expert truth (The Hive) | ✅ Implemented | +| **Skeptic** | Returns all claims with conflict score | "Trust but Verify" dashboards | ✅ Implemented | +| EpochAware | Filters superseded epochs first | Paradigm-safe queries | ✅ Implemented | +| Constraints | Returns `must_use`/`forbidden` predicates | Pre-flight checks | 🔜 Planned | + +**Note:** The `Authority` lens is now an alias for `TrustAwareAuthority` (both use agent reputation via TrustRank). Use `Confidence` if you want to select by the assertion's self-declared confidence field without considering agent reputation. + +## EpochAwareLens Implementation + +The EpochAwareLens filters assertions from superseded epochs before delegating to an inner lens. This enables "paradigm-safe" queries where obsolete worldviews are automatically excluded. + +**Resolution Strategy:** +1. Collect all unique epoch IDs from candidate assertions +2. For each epoch, read `E:{epoch_id}` from store +3. Walk the `supersedes` chain to build a set of superseded epoch IDs +4. Filter candidates: exclude any assertion whose epoch is in the superseded set +5. Delegate filtered candidates to inner lens (default: RecencyLens) + +**Key Design Decisions:** + +| Behavior | Choice | Rationale | +|----------|--------|-----------| +| Missing epoch record | Include assertion (fail-open) | Data availability > metadata consistency | +| Cycle in supersession chain | Stop walking, include assertions | Pathological data shouldn't hide valid assertions | +| Max depth exceeded (100) | Stop walking, log warning | Prevent infinite loops | +| No epochs in candidates | Delegate directly to inner lens | Optimization for common case | + +**Use Case: Accounting Standard Migration (GAAP → IFRS)** + +```bash +# Create epochs representing paradigm shift +POST /v1/epoch {"name": "GAAP-Era", "start_timestamp": 0} +# Returns epoch_id: "abc123..." + +POST /v1/epoch { + "name": "IFRS-Transition", + "supersedes": "abc123...", + "supersession_type": "Temporal", + "start_timestamp": 1704067200 +} +# Returns epoch_id: "def456..." + +# Query with epoch awareness +GET /v1/query?subject=Acme&predicate=lease_liability&lens=EpochAware + +# Returns IFRS treatment (new epoch) +# GAAP treatment (old epoch) automatically excluded +``` + +**Example:** +```rust +use stemedb_lens::EpochAwareLens; +use stemedb_storage::SledStore; +use std::sync::Arc; + +let store = Arc::new(SledStore::open("./data").expect("store")); + +// Default: filter superseded epochs, then pick most recent +let lens = EpochAwareLens::with_recency(store.clone()); + +// Custom: filter superseded epochs, then use consensus +use stemedb_lens::ConsensusLens; +let lens = EpochAwareLens::with_sync_lens(store, ConsensusLens); + +let resolution = lens.resolve_async(&candidates).await; +``` + +**Limitation:** The lens only filters assertions when assertions from the superseding epoch are present in the candidates. If you only have old-epoch assertions (no new-epoch assertions exist for the query), they will pass through. This is intentional fail-open behavior. + +## SkepticLens Implementation + +The SkepticLens surfaces conflict instead of hiding it. It implements `AnalysisLens` rather than `Lens`, returning a `ConflictAnalysis` with all competing claims. + +**Resolution Strategy:** +1. Group assertions by object value +2. For each group, calculate aggregate vote weight (or fallback to confidence) +3. Calculate normalized Shannon entropy as conflict score +4. Determine status: Unanimous (<0.1), Agreed (<0.4), or Contested (>=0.4) +5. Build ClaimSummary for each group with supporting agents and source provenance + +**Conflict Score Formula:** +``` +entropy = -sum(p * log2(p)) for each claim weight proportion +conflict_score = entropy / log2(num_claims) // Normalized to 0.0-1.0 +``` + +**API Endpoint:** +``` +GET /v1/skeptic?subject=Semaglutide&predicate=muscle_effect + +{ + "status": "Contested", + "conflict_score": 0.72, + "claims": [ + { + "value": {"type": "Text", "value": "Significant loss"}, + "weight_share": 0.45, + "assertion_count": 12, + "supporting_agents": [...] + }, + { + "value": {"type": "Text", "value": "Minimal loss"}, + "weight_share": 0.35, + "assertion_count": 3 + } + ], + "candidates_count": 17 +} +``` + +**Example:** +```rust +use stemedb_lens::SkepticLens; +use stemedb_storage::{SledStore, GenericVoteStore, GenericTrustRankStore}; +use std::sync::Arc; + +let store = SledStore::open("./data").await?; +let vote_store = Arc::new(GenericVoteStore::new(store.clone())); +let trust_store = Arc::new(GenericTrustRankStore::new(store)); +let lens = SkepticLens::new(vote_store, trust_store); + +let analysis = lens.analyze(&candidates).await; +if analysis.status == ResolutionStatus::Contested { + println!("⚠️ This fact is disputed! Conflict score: {:.2}", analysis.conflict_score); +} +``` ## Lens::Constraints (Pre-Flight Check) diff --git a/ai-lookup/services/lifecycle.md b/ai-lookup/services/lifecycle.md index ebeabd4..e6847a0 100644 --- a/ai-lookup/services/lifecycle.md +++ b/ai-lookup/services/lifecycle.md @@ -1,6 +1,8 @@ # Lifecycle Stages > **Quick Ref:** Assertions have lifecycle state: Proposed → UnderReview → Approved | Deprecated | Rejected +> **Status:** Implemented in `stemedb-core` v0.1.0 +> **File:** `crates/stemedb-core/src/types.rs` ## The Problem diff --git a/ai-lookup/services/materializer.md b/ai-lookup/services/materializer.md new file mode 100644 index 0000000..4228fd1 --- /dev/null +++ b/ai-lookup/services/materializer.md @@ -0,0 +1,141 @@ +# Materializer + +**Last Updated:** 2026-01-31 +**Confidence:** High +**Status:** Implemented + +## Summary + +The Materializer is a background worker that pre-computes winning assertions for each subject+predicate pair, storing them at `MV:{subject}:{predicate}` for O(1) reads. It bridges the gap between O(N) lens resolution and sub-millisecond query latency. + +**Key Facts:** +- Scans all `SP:` compound indexes to discover pairs +- Resolves each pair through an `AsyncLens` (default: VoteAwareConsensus) +- Stores `MaterializedView` with winner + provenance metadata +- `step()` for one-shot, `run()` for polling loop, `run_notified()` for event-driven mode +- Event-driven: IngestWorker signals `tokio::sync::Notify` on new data; Materializer reacts immediately +- QueryEngine uses fast-path: checks `MV:` key before falling back to `SP:` index +- Error-resilient: individual pair failures are logged and skipped + +**File Pointers:** +- `crates/stemedb-query/src/materializer.rs` - Materializer worker +- `crates/stemedb-core/src/types.rs` - MaterializedView type + +## Storage Layout + +| Key Pattern | Value | Purpose | +|-------------|-------|---------| +| `MV:{subject}:{predicate}` | Serialized `MaterializedView` | Pre-computed winner + metadata | + +## MaterializedView Type + +```rust +pub struct MaterializedView { + pub winner: Assertion, // The resolved winner + pub lens_name: String, // Which lens produced this (e.g., "VoteAwareConsensus") + pub resolution_confidence: f32, // Confidence in the resolution [0.0, 1.0] + pub candidates_count: usize, // How many candidates were considered + pub materialized_at: u64, // When this view was last computed +} +``` + +## Materializer Interface + +```rust +pub struct Materializer { + store: Arc, + index_store: GenericIndexStore>, + lens: Box, +} + +impl Materializer { + /// Create with any AsyncLens implementation + pub fn new(store: Arc, lens: Box) -> Self; + + /// One full materialization pass over all SP: pairs + pub async fn step(&self) -> Result; + + /// Materialize a single subject+predicate pair + pub async fn materialize_pair(&self, subject: &str, predicate: &str) + -> Result>; + + /// Read a pre-computed view (O(1)) + pub async fn get_materialized_view(&self, subject: &str, predicate: &str) + -> Result>; + + /// Run continuously with configurable interval (polling mode) + pub async fn run(&self, interval: Duration); + + /// Run in event-driven mode, triggered by IngestWorker notifications + pub async fn run_notified(&self, notify: Arc, max_interval: Duration); +} +``` + +## Read Path Integration + +The `QueryEngine` automatically uses the fast path when both subject and predicate are specified. + +**Fast Path (O(1)):** +``` +QueryEngine::execute() -> MV:{subject}:{predicate} -> MaterializedView.winner -> QueryResult +``` + +**Slow Path (O(N)):** +``` +QueryEngine::execute() -> SP:{subject}:{predicate} -> [H:{hash}...] -> candidates -> filter -> QueryResult +``` + +The fast path is used when a materialized view exists and the winner matches query filters (lifecycle, epoch). The slow path is the fallback when no MV exists, the winner doesn't match filters, or only a subject is specified. + +**File:** `crates/stemedb-query/src/engine.rs` — `try_fast_path()` method + +## Event-Driven Mode + +The Materializer supports two operating modes: + +**Polling mode** (`run(interval)`): Fixed-interval passes. Simple but wastes cycles when idle and adds latency after writes. + +**Event-driven mode** (`run_notified(notify, max_interval)`): The IngestWorker signals a `tokio::sync::Notify` after each successful record ingestion. The Materializer awaits this signal, running a pass immediately when new data arrives. A `max_interval` timeout acts as a safety net for missed notifications. + +``` +IngestWorker::step() -> notify.notify_one() -> Materializer::run_notified() wakes -> step() +``` + +**Wiring:** +```rust +let notify = Arc::new(tokio::sync::Notify::new()); +let worker = IngestWorker::new(journal, store.clone()).await?.with_notify(Arc::clone(¬ify)); +let materializer = Materializer::new(store, Box::new(lens)); +// In separate tasks: +tokio::spawn(async move { worker.run().await }); +tokio::spawn(async move { materializer.run_notified(notify, Duration::from_secs(30)).await }); +``` + +**File:** `crates/stemedb-ingest/src/worker.rs` — `with_notify()` method + +## Design Rationale + +### Why a Background Worker? + +Inline materialization (on every write) would: +1. Add latency to the write path +2. Create contention when many agents write simultaneously +3. Couple write and read concerns + +The background worker approach: +1. Keeps the write path fast (append-only) +2. Batches resolution work efficiently +3. Tolerates temporary staleness (eventual consistency) + +### Why Store Metadata? + +The `MaterializedView` includes `lens_name`, `confidence`, `candidates_count`, and `materialized_at` because: +1. **Provenance:** Agents can verify how truth was determined +2. **Debugging:** "Why does the system think Tesla's revenue is X?" +3. **Staleness detection:** Readers can check `materialized_at` to decide if a slow-path re-resolution is needed + +## Related Topics + +- [Ballot Box](./ballot-box.md) - Vote data consumed by the Materializer +- [Storage](./storage.md) - KV layout and key patterns +- [Architecture](../../architecture.md) - Section 3 (Write Path) and Section 4 (Read Path) diff --git a/ai-lookup/services/meter.md b/ai-lookup/services/meter.md new file mode 100644 index 0000000..9ed2d19 --- /dev/null +++ b/ai-lookup/services/meter.md @@ -0,0 +1,131 @@ +# The Meter (Economic Throttling) + +## Overview + +The Meter implements per-agent per-hour quota enforcement using a Token Bucket algorithm. This prevents runaway agents from exhausting system resources while allowing bursty behavior. + +## Cost Model + +| Operation | Base Cost | Notes | +|-----------|-----------|-------| +| Assert | 10 tokens | Writing truth is expensive | +| Vote | 1 token | Voting is cheap | +| Query | 5 tokens | + 1 per Lens applied | +| Payload | +1/KB | Prevents spamming massive blobs | + +Default quota: **10,000 tokens per agent per hour**. + +## Components + +### QuotaStore (`stemedb-storage/src/quota_store.rs`) + +Storage abstraction for quota tracking. + +**Key Types:** +- `QuotaRecord` - Per-agent per-hour usage record +- `CostConfig` - Operation cost configuration +- `QuotaCheckResult` - Result of quota check (allowed, remaining, reset_at) +- `OperationType` - Assert, Vote, or Query + +**Storage Layout:** +``` +QT:{agent_id}:{hour} -> QuotaRecord (serialized) +QL:{agent_id} -> u64 (custom limit override) +``` + +**Key Methods:** +```rust +async fn check_and_record(&self, agent_id, operation, payload_bytes, timestamp) -> QuotaCheckResult; +async fn get_quota_status(&self, agent_id, timestamp) -> QuotaCheckResult; +async fn set_quota_limit(&self, agent_id, limit) -> Result<()>; +``` + +### MeterLayer (`stemedb-api/src/middleware/meter.rs`) + +Tower middleware that intercepts requests and enforces quotas. + +**Request Flow:** +1. Extract `X-Agent-Id` header (hex-encoded 32-byte public key) +2. Determine operation type from path +3. Calculate cost based on operation + payload size +4. Check quota and reject with 429 if exceeded +5. Record cost and forward request +6. Add quota headers to response + +**Headers:** +| Header | Direction | Description | +|--------|-----------|-------------| +| `X-Agent-Id` | Request | Agent's Ed25519 public key (hex, 64 chars) | +| `X-Quota-Remaining` | Response | Remaining tokens in current window | +| `X-Quota-Limit` | Response | Total tokens allowed per hour | +| `X-Quota-Reset` | Response | Unix timestamp when window resets | + +### API Endpoints + +**GET /v1/meter/quota** +Check quota status for an agent. + +Query params: +- `agent_id` - Hex-encoded agent public key + +Response: +```json +{ + "agent_id": "...", + "remaining": 9500, + "limit": 10000, + "reset_at": 1705317600, + "used": 500, + "window_start": 1705314000 +} +``` + +**POST /v1/meter/quota/limit** +Set custom quota limit (admin operation). + +Request: +```json +{ + "agent_id": "...", + "limit": 50000 +} +``` + +## Configuration + +Environment variable: `STEMEDB_METER_ENABLED` +- `true` (default): Enable economic throttling +- `false` or `0`: Disable (all requests pass through) + +## Bypass Paths + +These paths bypass metering: +- `/v1/health` +- `/swagger-ui/*` +- `/api-docs/*` + +## Usage Example + +```bash +# Check quota before operations +curl "http://localhost:3000/v1/meter/quota?agent_id=$(xxd -p -l 32 /dev/urandom)" + +# Make request with agent ID +curl -X POST http://localhost:3000/v1/assert \ + -H "Content-Type: application/json" \ + -H "X-Agent-Id: 0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20" \ + -d '{"subject": "test", ...}' + +# Response headers include quota info +# X-Quota-Remaining: 9989 +# X-Quota-Limit: 10000 +# X-Quota-Reset: 1705317600 +``` + +## Implementation Notes + +- Quota windows are hour-aligned (truncated to the start of the hour) +- Quotas reset automatically at the start of each hour +- On storage errors, requests are allowed (fail open for availability) +- Anonymous requests (no X-Agent-Id) bypass metering +- Token bucket allows burst behavior while enforcing long-term limits diff --git a/ai-lookup/services/query.md b/ai-lookup/services/query.md new file mode 100644 index 0000000..49cef89 --- /dev/null +++ b/ai-lookup/services/query.md @@ -0,0 +1,85 @@ +# Query Engine + +**Last Updated:** 2026-02-01 +**Confidence:** High +**Status:** Implemented in `stemedb-query` v0.1.0 + +## Summary + +The Query Engine provides lifecycle-aware filtering for reading assertions from the knowledge graph. + +**Key Facts:** +- Filters by subject, predicate, lifecycle, epoch +- **Fast path**: checks `MV:{subject}:{predicate}` for pre-computed winner (O(1)) +- **MV staleness control**: `max_stale` parameter to reject stale materialized views +- **Compound index**: `SP:{subject}:{predicate}` for subject+predicate lookups (O(1)) +- **Subject index**: `S:{subject}` for subject-only lookups (O(1)) +- Falls back to full scan when no index available + +**File Pointers:** +- `crates/stemedb-query/src/engine.rs` - QueryEngine with fast-path and staleness check +- `crates/stemedb-query/src/query.rs` - Query and QueryResult types + +## Query Structure + +```rust +pub struct Query { + pub subject: Option, + pub predicate: Option, + pub lifecycle: Option, + pub epoch: Option, + pub limit: Option, + pub max_stale: Option, // Maximum MV age in seconds +} +``` + +## Usage + +```rust +let query = Query::builder() + .subject("Tesla") + .predicate("revenue") + .lifecycle(LifecycleStage::Approved) + .max_stale(300) // Only use MVs < 5 minutes old + .limit(10) + .build(); + +let result = engine.execute(&query).await?; +``` + +## MV Staleness Control + +The `max_stale` parameter controls whether the fast path (materialized view) is used: + +| `max_stale` | Behavior | +|-------------|----------| +| `None` (default) | Accept any MV age (backward compatible) | +| `Some(0)` | Only accept brand-new MVs (age = 0 seconds) | +| `Some(60)` | Only use MV if materialized within last 60 seconds | +| `Some(300)` | Only use MV if materialized within last 5 minutes | + +When the MV is stale, the query falls through to the slow path (SP index lookup + lens resolution). + +**Use cases:** +- Real-time dashboards: `max_stale(60)` for fresh data +- Audit investigations: `max_stale(0)` to ensure current state +- Batch processing: `None` for maximum performance + +## Query Execution Strategy + +0. **Fast path** (subject + predicate): `MV:{subject}:{predicate}` → `MaterializedView.winner` (O(1)) + - Skips if MV doesn't exist + - Skips if MV is too stale (`max_stale` check) + - Skips if winner doesn't match filters (lifecycle, epoch) +1. **Compound index** (subject + predicate): `SP:{subject}:{predicate}` → hashes (O(1)) +2. **Subject index** (subject only): `S:{subject}` → hashes (O(1)) +3. **Full scan** (no subject): Scan `H:` prefix (O(n)) +4. **Filter**: Apply lifecycle/epoch filters on candidates +5. **Limit**: Truncate if limit specified + +## Related Topics + +- [Materializer](./materializer.md) - Produces the MV: keys used by fast path +- [Assertion](./assertion.md) +- [Lifecycle Stages](./lifecycle.md) +- [Lens Resolution](./lens.md) diff --git a/ai-lookup/services/sdk.md b/ai-lookup/services/sdk.md new file mode 100644 index 0000000..58b16fd --- /dev/null +++ b/ai-lookup/services/sdk.md @@ -0,0 +1,329 @@ +# SDK - Go Client Libraries + +**Last Updated:** 2026-02-01 +**Confidence:** High + +## Summary + +Official Go SDK for Episteme with two layers: a low-level HTTP client (`steme`) and an ADK-Go integration layer (`adk`) for building AI agents. Both libraries handle Ed25519 signing, content-addressing, and fluent assertion building. The ADK layer exposes Episteme as Google ADK-Go tools with pre-flight constraint checking and audit callbacks. + +**Key Facts:** +- Languages: Go (initial), Python/TypeScript planned +- Location: `sdk/go/steme/` (core client), `sdk/go/adk/` (ADK integration) +- Signing: Ed25519 with BLAKE3 content-addressing +- Transport: HTTP/JSON (matches `stemedb-api`) +- ADK Tools: Query, Assert, ConstraintCheck, Trace, Supersede +- Test Coverage: 26 tests passing (12 core + 14 ADK) + +**File Pointers:** +- `sdk/go/steme/client.go` - HTTP client with auto-signing +- `sdk/go/steme/assertion.go` - Fluent builder for assertions +- `sdk/go/steme/signer.go` - Ed25519 signature generation +- `sdk/go/adk/tools.go` - ADK tool definitions +- `sdk/go/adk/callbacks.go` - Pre-flight checks and audit hooks +- `sdk/go/adk/config.go` - Agent configurations (Lead, Research, Implementation, etc.) + +## Core SDK (`steme`) + +### Installation + +```go +import "github.com/orchard9/stemedb/sdk/go/steme" +``` + +### Client Creation + +```go +// Create with Ed25519 keypair +privateKey := ed25519.NewKeyFromSeed(seed) +client := steme.NewClient("https://episteme.example.com", privateKey) + +// Or use environment-based config +client := steme.NewClientFromEnv() // STEME_URL, STEME_PRIVATE_KEY +``` + +### Fluent Assertion Builder + +```go +assertion, err := steme.NewAssertion(). + Subject("auth/jwt"). + Predicate("signing_algorithm"). + StringObject("RS256"). + Confidence(0.95). + SourceHash(evidenceHash). + Lifecycle("approved"). + Build() + +// Client auto-signs on submit +hash, err := client.Assert(ctx, assertion) +``` + +### Query API + +```go +result, err := client.Query(ctx, steme.QueryRequest{ + Subject: "auth/jwt", + Predicate: "signing_algorithm", + Lens: "authority", + Lifecycle: "approved", + MinConfidence: 0.8, + AsOf: time.Now().Add(-24 * time.Hour), // Time-travel +}) + +fmt.Printf("Value: %v (confidence: %.2f)\n", result.Value, result.Confidence) +``` + +### Voting + +```go +err := client.Vote(ctx, steme.VoteRequest{ + AssertionHash: targetHash, + Upvote: true, + AgentID: myAgentID, + VoteHash: voteContentHash, +}) +``` + +## ADK Integration (`adk`) + +### Installation + +```go +import ( + "github.com/orchard9/stemedb/sdk/go/adk" + "google.golang.org/adk/llmagent" +) +``` + +### Agent Configuration + +Pre-configured agent personas with appropriate tool access and callbacks: + +```go +// Implementation Agent - Uses approved patterns only +config := adk.ImplementationAgentConfig(stemeClient, model) +agent, err := llmagent.New(config) + +// Research Agent - Stores conflicting information without flattening +config := adk.ResearchAgentConfig(stemeClient, model) +agent, err := llmagent.New(config) + +// Lead Agent - Fast queries with confidence thresholds +config := adk.LeadAgentConfig(stemeClient, model) +agent, err := llmagent.New(config) + +// Supervisor Agent - Time-travel and corrections +config := adk.SupervisorAgentConfig(stemeClient, model) +agent, err := llmagent.New(config) + +// On-Call Agent - Traces and debugging +config := adk.OnCallAgentConfig(stemeClient, model) +agent, err := llmagent.New(config) +``` + +### Available Tools + +All tools are ADK-compatible with structured input/output and OpenAPI schema generation: + +**Query Tool** +```go +type QueryInput struct { + Subject string `json:"subject"` + Predicate string `json:"predicate"` + Lens string `json:"lens,omitempty"` + Lifecycle string `json:"lifecycle,omitempty"` + MinConfidence float32 `json:"min_confidence,omitempty"` + AsOf string `json:"as_of,omitempty"` +} +``` + +**Assert Tool** +```go +type AssertInput struct { + Subject string `json:"subject"` + Predicate string `json:"predicate"` + Object interface{} `json:"object"` + SourceHash string `json:"source_hash"` + Confidence float32 `json:"confidence"` + Lifecycle string `json:"lifecycle,omitempty"` + ParentHash string `json:"parent_hash,omitempty"` +} +``` + +**ConstraintCheck Tool** +```go +type ConstraintCheckInput struct { + Context string `json:"context"` // e.g., "python_http", "auth_jwt" +} +``` + +**Trace Tool** (SRE debugging) +```go +type TraceInput struct { + AgentID string `json:"agent_id"` + From string `json:"from"` // ISO8601 or relative like "-6h" + Subject string `json:"subject,omitempty"` // Filter pattern +} +``` + +**Supersede Tool** (corrections) +```go +type SupersedeInput struct { + Hash string `json:"hash"` // Assertion to correct + Reason string `json:"reason"` // Why it's being invalidated + Type string `json:"type"` // "Invalidate" or "Update" +} +``` + +### Callbacks + +Three callback hooks for safety and observability: + +**ConstraintEnforcement** (BeforeToolCallback) +```go +// Blocks tool calls that violate organizational constraints +// Example: Prevents using SHA1 if auth/jwt has "forbidden: sha1" +BeforeToolCallback: adk.ConstraintEnforcementCallback(client) +``` + +**AuditLogging** (AfterModelCallback) +```go +// Logs agent decisions for debugging and replay +AfterModelCallback: adk.AuditLoggingCallback(client) +``` + +**ConfidenceEscalation** (AfterToolCallback) +```go +// Escalates to human when confidence drops below threshold +// Triggers Gardener on tool failures for TrustRank back-propagation +AfterToolCallback: adk.ConfidenceEscalationCallback(client, 0.7) +``` + +### Custom Agent Example + +```go +import ( + "github.com/orchard9/stemedb/sdk/go/adk" + "google.golang.org/adk/llmagent" + "google.golang.org/adk/tool" +) + +func main() { + stemeClient := steme.NewClientFromEnv() + model := llm.NewClient() + + // Build ADK tools + queryTool, _ := adk.NewQueryTool(stemeClient) + assertTool, _ := adk.NewAssertTool(stemeClient) + constraintTool, _ := adk.NewConstraintCheckTool(stemeClient) + + // Create agent with callbacks + agent, err := llmagent.New(llmagent.Config{ + Name: "custom_agent", + Model: model, + Tools: []tool.Tool{queryTool, assertTool, constraintTool}, + + // Pre-flight constraint checking + BeforeToolCallback: adk.ConstraintEnforcementCallback(stemeClient), + + // Audit all decisions + AfterModelCallback: adk.AuditLoggingCallback(stemeClient), + + // Learn from failures + AfterToolCallback: adk.ConfidenceEscalationCallback(stemeClient, 0.8), + }) + + // Run agent + ctx := context.Background() + response, err := agent.Generate(ctx, llmagent.Input{ + Prompt: "Check if we have an approved JWT signing algorithm", + }) +} +``` + +## E2E Test Coverage + +The SDK implementation is validated by comprehensive integration tests: + +**File:** `crates/stemedb-api/tests/e2e_flow_test.rs` + +**Tests:** +1. `test_basic_write_materialize_query` - Write → MV → Read flow +2. `test_write_multiple_query_recency` - Recency lens with multiple assertions +3. `test_vote_and_query_consensus` - Voting + Consensus lens +4. `test_event_driven_materialization` - MV updates on write events + +**Coverage:** +- Real Ed25519 signature generation and verification +- Event-driven materialization (WAL → MV update) +- All lens types (Recency, Consensus, Authority) +- Time-travel queries +- Vote aggregation with TrustRank + +## Type Hierarchy + +``` +Go SDK (serde JSON) Rust API (serde JSON) Rust Core (rkyv) + | | | +Assertion struct dto::AssertionRequest types::Assertion + | | | + +-- Subject: string +-- subject: String +-- subject: EntityId + +-- Predicate: string +-- predicate: String +-- predicate: RelationId + +-- Object: interface{} +-- object: Value +-- object: ObjectValue + +-- Confidence: float32 +-- confidence: f32 +-- confidence: f32 + +-- SourceHash: string +-- source_hash: Hash +-- source_hash: Hash + +-- Lifecycle: string +-- lifecycle: String +-- lifecycle: LifecycleStage +``` + +## Design Principles + +**Content-Addressed Identity** +- Assertion hash = BLAKE3(canonical JSON serialization) +- Same content = same hash across all SDKs +- Idempotent writes (re-asserting produces same hash) + +**Multi-Signature Support** +- Client signs entire assertion with Ed25519 +- API verifies signature before writing to WAL +- Multiple agents can co-sign the same assertion (multi-sig) + +**Fluent Builder Pattern** +- Type-safe construction with compile-time validation +- Prevents partial/invalid assertions +- Generates content hash automatically on Build() + +**Zero Dependencies on Rust** +- Pure Go implementation with standard library + ADK +- JSON over HTTP (no gRPC/protobuf yet) +- Works with any Episteme deployment + +## Error Handling + +```go +// SDK errors implement error interface +_, err := client.Assert(ctx, assertion) +if err != nil { + var apiErr *steme.APIError + if errors.As(err, &apiErr) { + switch apiErr.Code { + case steme.ErrInvalidSignature: + // Re-sign with correct key + case steme.ErrDuplicateHash: + // Already exists (idempotent - not an error) + case steme.ErrConstraintViolation: + // Check constraints with ConstraintCheck tool + default: + // Log and retry with backoff + } + } +} +``` + +## Related Topics + +- [API Surface](./api.md) - HTTP endpoints and OpenAPI schema +- [Assertion](./assertion.md) - Core data structure +- [Lens](./lens.md) - Read-time resolution strategies +- [ADK Integration Pattern](../patterns/adk-integration.md) - Tool and callback details +- [Query Audit](../features/query-audit.md) - Trace agent decisions +- [TrustRank](../features/trust-rank.md) - Agent reputation and Gardener diff --git a/ai-lookup/services/storage.md b/ai-lookup/services/storage.md index 9c49c5e..a5d9fa5 100644 --- a/ai-lookup/services/storage.md +++ b/ai-lookup/services/storage.md @@ -1,6 +1,6 @@ # Storage -**Last Updated:** 2025-01-31 +**Last Updated:** 2026-01-31 **Confidence:** High ## Summary @@ -13,16 +13,60 @@ Episteme uses a Log-Structured, Content-Addressed storage model. Writes append t - KV store for indexes (sled MVP, trait-abstracted) - Content-addressed by BLAKE3 hash -**File Pointer:** `crates/stemedb-core/src/store.rs` (planned) +**File Pointers:** +- `crates/stemedb-storage/src/traits.rs` - KVStore trait +- `crates/stemedb-storage/src/sled_backend.rs` - Sled implementation +- `crates/stemedb-storage/src/serde_helpers.rs` - Storage-layer serialize/deserialize helpers +- `crates/stemedb-storage/src/vote_store.rs` - VoteStore (Ballot Box) +- `crates/stemedb-storage/src/index_store.rs` - IndexStore (S: and SP: indexes) +- `crates/stemedb-storage/src/trust_rank_store.rs` - TrustRankStore (TR:) ## KV Layout | Key Pattern | Value | Purpose | |-------------|-------|---------| | `H:{Hash}` | `Assertion` (serialized) | Main content store | -| `S:{Subject}` | `Vec` | Subject index | -| `SP:{Subject}:{Predicate}` | `Vec` | Triple index | -| `A:{AgentId}` | `ReputationScore` | TrustRank storage | +| `V:{assertion_hash}:{vote_hash}` | `Vote` (serialized) | Ballot Box votes | +| `VC:{assertion_hash}` | `u64` (LE bytes) | Vote count cache | +| `VW:{assertion_hash}` | `f32` (LE bytes) | Aggregate weight cache | +| `E:{epoch_id}` | `Epoch` (serialized) | Paradigm definitions | +| `S:{Subject}` | `Vec` (rkyv) | Subject index (IndexStore) | +| `SP:{Subject}:{Predicate}` | `Vec` (rkyv) | Compound index (IndexStore) | +| `TR:{AgentId}` | `TrustRank` (rkyv) | Agent reputation (TrustRankStore) | +| `MV:{Subject}:{Predicate}` | `MaterializedView` (rkyv) | Pre-computed winner (Materializer) | +| `__CURSOR__:ingest` | `u64` (LE bytes) | Ingestion WAL offset checkpoint | + +## Serialization + +### stemedb-core (shared types) + +For core types, use the canonical module: + +```rust +use stemedb_core::serde::{serialize, deserialize}; + +let bytes = serialize(&my_value)?; +let value: MyType = deserialize(&bytes)?; +``` + +**File:** `crates/stemedb-core/src/serde.rs` + +Raw `AllocSerializer` usage is prohibited in production code (enforced via CLAUDE.md). + +### stemedb-storage (store implementations) + +In storage modules, use the storage-layer helpers that map to `StorageError`: + +```rust +use crate::serde_helpers::{serialize, deserialize}; + +let bytes = serialize(&my_value)?; // Returns Result, StorageError> +let value: MyType = deserialize(&bytes)?; +``` + +**File:** `crates/stemedb-storage/src/serde_helpers.rs` + +This provides unified error handling across all store implementations (VoteStore, IndexStore, TrustRankStore, AuditStore, TrustPackStore, QuotaStore). ## Write Path @@ -47,4 +91,5 @@ Episteme uses a Log-Structured, Content-Addressed storage model. Writes append t ## Related Topics - [Assertion](./assertion.md) +- [Ballot Box](./ballot-box.md) - High-velocity vote storage - [Architecture](../../../architecture.md) diff --git a/architecture.md b/architecture.md index bd0fcc6..d1199bb 100644 --- a/architecture.md +++ b/architecture.md @@ -1,7 +1,7 @@ # Episteme (StemeDB) Architecture > **Design Philosophy:** Immutable History, Probabilistic Resolution, Materialized Speed. -> **Status:** Draft Spec v1.0 +> **Status:** Draft Spec v1.1 ## 1. System Overview @@ -21,8 +21,8 @@ To solve the O(N) read latency of conflict resolution, Episteme employs a **Mate │ Ingestion │ │ Resolution │ │ Gateway │ │ Engine │ └─────┬──────┘ └─────┬──────┘ - │ (2) Append │ (5) Read Materialized View - │ to Ballot │ OR Apply Custom Lens + │ (2) Append │ (5) Apply Lens + Trust Pack + │ to Ballot │ (BitSet Filter) ▼ │ ┌────────────┐ ┌────────────┐ │ Quarantine │ │ Indexing │ @@ -68,13 +68,26 @@ struct Vote { } ``` -### 2.3. The Storage Layout (LSM Tree) +### 2.3. The Trust Pack (The Overlay) +A curated list of trusted agents, used to filter consensus efficiently. + +```rust +struct TrustPack { + pub id: PackId, + pub name: String, + pub maintainer: PublicKey, + pub agents: BitSet, // BloomFilter or RoaringBitmap for fast intersection +} +``` + +### 2.4. The Storage Layout (LSM Tree) | Key | Value | Purpose | | :--- | :--- | :--- | | `H:{Hash}` | `Assertion` | Immutable Content Store | | `V:{Hash}` | `List` | The Ballot Box (Append-only) | | `MV:{Subject}:{Predicate}` | `Assertion` | **Materialized View** (The "Winner") | +| `TP:{PackID}` | `TrustPack` | Curation Lists | | `S:{Subject}` | `List` | Adjacency Index | --- @@ -84,8 +97,7 @@ struct Vote { 1. **Ingest:** Agents submit `Assertions` or `Votes`. 2. **Journal:** Written to `episteme-wal`. 3. **Ballot Box:** Votes are appended to the `V:{Hash}` stream. -4. **Compactor (Async):** A background worker aggregates Votes + TrustRank to update the `MV:{Subject}:{Predicate}` key. - * This ensures that Read queries (`GET /query`) are O(1) lookups on the Materialized View, not O(N) calculations. +4. **Compactor (Async):** A background worker aggregates Votes + TrustRank to update the `MV` key. --- @@ -96,18 +108,21 @@ struct Vote { * Action: `GET MV:{Subject}:{Predicate}` * Cost: **O(1)**. Low latency. -**Slow Path (Custom/Skeptic Lenses):** -* Query: `GET /query?lens=Skeptic` -* Action: Gather all candidates + votes, compute variance on the fly. -* Cost: **O(N)**. High latency, used for analysis/debugging. +**Trusted Path (Trust Packs):** +* Query: `GET /query?lens=Authority&trust_pack=Science_Pack` +* Action: + 1. Fetch Candidate Assertions. + 2. Fetch Votes. + 3. **Filter:** Intersect Votes with `TrustPack.agents` (BitSet operation). + 4. Sum weights of remaining votes. +* Cost: **O(1)** (if Materialized per Pack) or **O(M)** (Fast calculation). ### Standard Lenses * **Consensus:** Highest cluster density. -* **Authority:** Filter by Reputation. +* **Authority:** Filter by **Trust Pack**. * **Recency:** Last Writer Wins. -* **Skeptic:** Returns variance/conflict metrics. * **EpochAware:** Validates against current paradigm. -* **Constraints:** Returns all `must_use`/`forbidden` assertions for a context. Acts as a "Pre-Flight Check" to solve the Optimization Conflict. +* **Constraints:** (New) Returns all `must_use`/`forbidden` assertions for a context. Acts as a "Pre-Flight Check." --- @@ -138,6 +153,7 @@ The system continuously exports data to train the next generation of Agents. ### Phase 2: The Lattice (Connectivity) * [ ] **The Ballot Box**: Implement separate Vote storage stream. * [ ] **Materializer**: Implement background worker to maintain `MV` keys. +* [ ] **Trust Packs**: Implement BitSet/BloomFilter logic for agent sets. * [ ] **The Meter**: Implement Budget/TAN middleware in Job Manager. * [ ] **Agent Wallet**: Sidecar for key management/signing. @@ -148,4 +164,5 @@ The system continuously exports data to train the next generation of Agents. ### Phase 4: The Hive (Learning) * [ ] **The Simulator**: Log exporter pipeline. -* [ ] TrustRank Learning Loop. +* [ ] **Trust Marketplace**: API for publishing/subscribing to Trust Packs. +* [ ] **The Super Curator**: Implement "Judge" agent with Visual Anchoring. \ No newline at end of file diff --git a/arena-roadmap.md b/arena-roadmap.md new file mode 100644 index 0000000..18ad881 --- /dev/null +++ b/arena-roadmap.md @@ -0,0 +1,509 @@ +# Arena Roadmap: The Simulation + +> **Goal:** Incrementally evolve the simulator from Spine validation to a full Agent-Based Modeling environment. +> **Philosophy:** Make it run. Then add. Verify at every step. +> **Alignment:** Tracks main `roadmap.md` phases; exercises features as they land. + +--- + +## Current State (Baseline) + +The simulator (`stemedb-sim`) currently validates **Phase 1: The Spine**: + +| Component | Status | What It Proves | +|-----------|--------|----------------| +| WAL Durability | ✓ Works | Writes persist | +| rkyv Serialization | ✓ Works | Roundtrip correctness | +| Ed25519 Signatures | ✓ Works | Sign on write, verify on read | +| Ingestor Pipeline | ✓ Works | WAL → KV async flow | +| Agent Identity | ✓ Works | Keypair generation | + +**Run command:** `cargo run --bin stemedb-sim` + +**What's NOW tested (Arena 1-2):** +- ✅ Queries via QueryEngine +- ✅ Lens resolution (Recency, VoteAwareConsensus) +- ✅ Lifecycle filtering +- ✅ Voting & consensus +- ✅ Query audit trail + +**What's NOT yet tested:** +- ❌ HTTP API layer (Arena 2.5.2) +- ❌ Concurrent agents (Arena 6) +- ❌ TrustRank (Arena 5) +- ❌ Materialized Views (Arena 3) +- ❌ Time-travel queries (Arena 7) +- ❌ Crash recovery (Arena 2.5.3) +- ❌ Input validation (Arena 2.5.4) + +--- + +## Arena Phases + +### Arena 0: Make It Verifiable ✅ COMPLETE +*Goal: Add assertions for what the simulation proves. Currently it prints logs; we need programmatic success/failure.* + +**Why first:** Without assertions, we don't know if later changes break things. + +- [x] **0.1 Return Result from main()**: Change from print-and-exit to structured outcome. + - [x] Define `SimulationResult { assertions_written: u64, assertions_verified: u64, errors: Vec }`. + - [x] Library function `run_simulation(config) -> Result`. + - [x] Print summary at end, exit 0 on success, exit 1 on failure, exit 2 on setup error. + +- [x] **0.2 Integration Test Wrapper**: Make the sim runnable as a test. + - [x] Add `crates/stemedb-sim/tests/smoke.rs` with 6 integration tests. + - [x] Assert on `SimulationResult` fields. + - [x] Run in CI via `cargo test -p stemedb-sim`. + +**Exit Criteria:** `cargo test -p stemedb-sim` passes ✅ + +--- + +### Arena 1: Query Path (Exercises Phase 2 Features) ✅ COMPLETE +*Goal: Extend simulation to read via QueryEngine, not direct KV access.* + +**Depends on:** Phase 2 complete (Query Engine, Lenses) +**Aligns with:** `roadmap.md` Phase 2 "The Lattice" + +- [x] **1.1 Add Query Engine to Simulation** + - [x] Import `stemedb-query` crate. + - [x] After ingestion wait, query each assertion via `QueryEngine::execute()`. + - [x] Verify result matches what was written. + +- [x] **1.2 Exercise Recency Lens** + - [x] Write 2 assertions for same subject+predicate with different timestamps. + - [x] Query with `lens=Recency`. + - [x] Verify most recent wins. + +- [x] **1.3 Exercise Lifecycle Filtering** + - [x] Write one `Proposed` and one `Approved` assertion for same fact. + - [x] Query with `lifecycle=Approved`. + - [x] Verify only Approved returned. + - [x] **Use Case Alignment:** This is the JWT signing algorithm bug from Agile Agent Team. + +- [x] **1.4 Query Audit Verification** + - [x] Set `X-Agent-Id` header (or equivalent in direct API call). + - [x] After queries, call `AuditStore::get_audits_for_agent()`. + - [x] Verify audit trail exists with correct contributing assertions. + - [x] **Use Case Alignment:** "What did the deployment agent query?" + +**Exit Criteria:** Simulation writes, ingests, queries, and verifies all three scenarios. ✅ + +--- + +### Arena 2: Voting & Consensus (Exercises Phase 2 VoteStore) ✅ COMPLETE +*Goal: Simulate agents voting on assertions and resolving via VoteAwareConsensusLens.* + +**Depends on:** Arena 1 complete, Phase 2 VoteStore +**Aligns with:** `roadmap.md` Phase 2 "The Ballot Box" + +- [x] **2.1 Add Vote Creation to Agents** + - [x] `Agent::vote(assertion_hash, weight)` method. + - [x] Votes stored directly via VoteStore (bypasses WAL for now - see note below). + +- [x] **2.2 Conflicting Assertions with Votes** + - [x] Scientist_Alpha asserts "Protein_X binds Receptor_Y" (confidence 0.8). + - [x] Scientist_Beta asserts "Protein_X binds Receptor_Z" (confidence 0.8). + - [x] Alpha votes for own assertion (weight 1.0). + - [x] Beta votes for own assertion (weight 1.0). + - [x] Third agent (Believer) votes for Alpha's assertion. + - [x] Query with `lens=VoteAwareConsensus`. + - [x] Verify Alpha's assertion wins (2 votes vs 1). + +- [x] **2.3 Troll Vote Resistance** + - [x] Troll creates low-confidence assertion contradicting consensus. + - [x] Troll votes for own assertion. + - [x] Verify high-vote assertions still win. + +**Exit Criteria:** Vote-based consensus correctly resolves conflicts. ✅ + +--- + +### Arena 2.5: Hardening (Critical Gap Remediation) 🔴 PRIORITY +*Goal: Fix critical gaps discovered during Arena 0-2 review before adding more features.* + +**Depends on:** Arena 2 complete +**Blocks:** Arena 3+ (don't add features on a shaky foundation) +**Rationale:** Gap analysis revealed 58/100 production readiness score with 3 critical blockers. + +- [ ] **2.5.1 Fix Vote Cache Race Condition** (P0 - CRITICAL) + - [ ] VoteStore `put_vote()` uses read-modify-write on VC:/VW: keys + - [ ] Two concurrent calls can lose updates (final count = N instead of N+1) + - [ ] Solution: Add atomic increment or compare-and-swap operation + - [ ] Add test: 100 concurrent `put_vote()` calls, verify final count + - [ ] **File:** `crates/stemedb-storage/src/vote_store.rs:181-206` + +- [ ] **2.5.2 Add API Integration Tests** (P0 - CRITICAL) + - [ ] Create `crates/stemedb-api/tests/http_integration.rs` + - [ ] Test `POST /assertions` - create assertion via HTTP + - [ ] Test `POST /votes` - submit vote via HTTP + - [ ] Test `GET /query` - query with lens parameter + - [ ] Test error responses (400 Bad Request, 500 Internal Error) + - [ ] Test rate limiting via QuotaStore middleware + - [ ] **Gap:** Entire HTTP layer is currently untested + +- [ ] **2.5.3 Add Crash Recovery Test** (P0 - CRITICAL) + - [ ] Write assertions to WAL + - [ ] Kill IngestWorker mid-step (simulate crash) + - [ ] Restart IngestWorker with same WAL + KV store + - [ ] Verify: cursor resumes correctly, no duplicate ingestion + - [ ] Verify: all pre-crash data is recoverable + - [ ] **Validates:** Durability claims in architecture.md + +- [ ] **2.5.4 Add Input Validation** (P1 - HIGH) + - [ ] Max subject length: 1024 characters + - [ ] Max predicate length: 1024 characters + - [ ] Confidence range: 0.0 to 1.0, reject NaN/Inf + - [ ] Vote weight: non-negative, reject NaN/Inf + - [ ] Timestamp: reject values > current time + 1 hour (clock skew protection) + - [ ] Add validation in `IngestWorker::ingest_assertion()` and `ingest_vote()` + - [ ] **File:** `crates/stemedb-ingest/src/worker.rs` + +- [ ] **2.5.5 Replace Sleep Timers with Ingestion Sync** (P1 - HIGH) + - [ ] Current: `tokio::time::sleep(Duration::from_millis(500))` (flaky) + - [ ] Add: `wait_for_ingestion(store, expected_count, timeout)` helper + - [ ] Poll store until expected assertions exist or timeout + - [ ] Replace all hardcoded sleeps in simulation + - [ ] **Benefit:** Faster tests, deterministic behavior + +- [ ] **2.5.6 Fix Defensive Error Handling** (P2 - MEDIUM) + - [ ] `vote_aware_consensus.rs:99-102`: Returns `[0u8; 32]` on serialization failure + - [ ] Change to propagate error or skip candidate with warning + - [ ] `worker.rs:161-173`: Ambiguous EOF handling treats all I/O errors as "no data" + - [ ] Distinguish true EOF from transient errors + +**Exit Criteria:** +- [ ] Vote cache is atomic (concurrent test passes) +- [ ] API layer has integration tests (POST/GET work via HTTP) +- [ ] Crash recovery is verified (no data loss on restart) +- [ ] Input validation rejects malformed data +- [ ] No hardcoded sleep timers in simulation +- [ ] Production readiness score: 75+ (up from 58) + +**Estimated Effort:** 5-6 days with 1 engineer + +--- + +### Arena 3: Materialized Views (Exercises Phase 2 Materializer) +*Goal: Verify fast-path MV reads work under simulation load.* + +**Depends on:** Arena 2 complete, Phase 2 Materializer +**Aligns with:** `roadmap.md` Phase 2 "Materializer" + +- [ ] **3.1 Materializer Integration** + - [ ] Spin up Materializer alongside Ingestor. + - [ ] Wire `Notify` between IngestWorker and Materializer. + - [ ] After ingestion, verify MV keys exist in store. + +- [ ] **3.2 Fast-Path Verification** + - [ ] Query via QueryEngine with subject+predicate. + - [ ] Log whether fast-path or slow-path was used (add debug output). + - [ ] Verify MV winner matches slow-path result. + +- [ ] **3.3 MV Freshness Under Load** + - [ ] Write 10 assertions in rapid succession. + - [ ] Wait for materialization. + - [ ] Verify MV reflects latest state. + - [ ] **Aligns with:** Phase 2.5 "MV Staleness Detection" + +**Exit Criteria:** Fast-path queries return correct results under load. + +--- + +### Arena 4: Agent Personas (First Strategy Differentiation) +*Goal: Agents behave differently based on persona. No longer uniform.* + +**Depends on:** Arena 3 complete +**Aligns with:** Vision document "The Players" + +- [ ] **4.1 AgentStrategy Trait** + ```rust + trait AgentStrategy { + fn decide_action(&self, state: &WorldState) -> AgentAction; + fn base_confidence(&self) -> f32; + fn name(&self) -> &'static str; + } + + enum AgentAction { + Assert { subject: String, predicate: String, object: ObjectValue }, + Vote { assertion_hash: Hash, weight: f32 }, + Query { subject: String, predicate: String }, + Skip, + } + ``` + +- [ ] **4.2 Scientist Strategy** + - [ ] High base confidence (0.85-0.95). + - [ ] Reads from ground truth, asserts facts. + - [ ] Votes for assertions that match ground truth. + +- [ ] **4.3 Troll Strategy** + - [ ] Low base confidence (0.3-0.5). + - [ ] Contradicts existing assertions. + - [ ] Votes against high-reputation assertions. + +- [ ] **4.4 Believer Strategy** + - [ ] Medium base confidence. + - [ ] Queries for consensus, votes for winners. + - [ ] Amplifies existing consensus. + +- [ ] **4.5 Strategy-Driven Tick Loop** + - [ ] Each tick: iterate agents, call `decide_action()`, execute. + - [ ] Track per-strategy metrics (assertions created, votes cast). + +**Exit Criteria:** Different agent types produce different behaviors in logs. + +--- + +### Arena 5: TrustRank Integration (Exercises Phase 4 Foundation) +*Goal: Reputation updates based on agent behavior.* + +**Depends on:** Arena 4 complete, TrustRank implemented +**Aligns with:** `roadmap.md` Phase 4 "TrustRank Engine" + +- [ ] **5.1 Initialize TrustRank for Agents** + - [ ] Each agent starts with base TrustRank (e.g., 0.5). + - [ ] Store in TrustRankStore at simulation start. + +- [ ] **5.2 Reputation Adjustment After Votes** + - [ ] When an assertion gains votes, increase author's TrustRank. + - [ ] When an assertion is contradicted by consensus, decrease author's TrustRank. + - [ ] Use `TrustRankStore::record_outcome()`. + +- [ ] **5.3 TrustAwareAuthorityLens Verification** + - [ ] Two assertions from different agents, same confidence. + - [ ] Agent with higher TrustRank should win via `TrustAwareAuthorityLens`. + - [ ] **Use Case Alignment:** "Expert vs. junior weighting" from Agile Agent Team. + +- [ ] **5.4 Troll Reputation Decay** + - [ ] After 100 ticks, verify Troll's TrustRank has decreased. + - [ ] Verify Scientist's TrustRank has increased. + - [ ] **Success Criteria:** "Trust clusters form naturally without hardcoded rules." + +**Exit Criteria:** TrustRank diverges based on behavior; Troll reputation tanks. + +--- + +### Arena 6: Concurrent Agents (Performance Validation) +*Goal: Move from sequential to parallel agent execution.* + +**Depends on:** Arena 5 complete +**Aligns with:** Vision "1000 concurrent agents without locking" + +- [ ] **6.1 Tokio Task Per Agent** + - [ ] Wrap each agent's tick in `tokio::spawn()`. + - [ ] Use `Arc>` for WAL access (already in place). + - [ ] Run 10 agents concurrently. + +- [ ] **6.2 Scale to 100 Agents** + - [ ] Parameterize agent count. + - [ ] Run with 100 agents for 50 ticks. + - [ ] Verify no deadlocks, no data corruption. + +- [ ] **6.3 Contention Metrics** + - [ ] Add timing around WAL lock acquisition. + - [ ] Log P50/P99 latencies. + - [ ] Identify bottlenecks if any. + +- [ ] **6.4 Target: 1000 Agents** + - [ ] Run with 1000 agents (stretch goal). + - [ ] May require connection pooling or batching. + - [ ] Document findings. + +**Exit Criteria:** 100 agents run concurrently without errors. + +--- + +### Arena 7: Time-Travel & Epochs (Exercises Phase 3 Features) +*Goal: Validate temporal queries and epoch supersession.* + +**Depends on:** Arena 6 complete, Phase 3 Time-Travel + EpochAwareLens +**Aligns with:** `roadmap.md` Phase 3 "Time-Travel Engine", Phase 2.5 "EpochAwareLens" + +- [ ] **7.1 Time-Travel Query Verification** + - [ ] At tick 50, record timestamp T1. + - [ ] At tick 100, write a new assertion superseding an old one. + - [ ] Query with `as_of=T1`. + - [ ] Verify result reflects tick-50 state, not tick-100 state. + - [ ] **Use Case Alignment:** "What was the state of knowledge at 9pm?" + +- [ ] **7.2 Epoch Creation and Supersession** + - [ ] Create epoch "v1" at tick 0. + - [ ] Create epoch "v2" superseding "v1" at tick 50. + - [ ] Assertions referencing "v1" should be filtered by EpochAwareLens. + - [ ] **Use Case Alignment:** "Security team migrates from RS256 to ES256." + +- [ ] **7.3 Epoch Cascade Verification** + - [ ] Chain: v3 supersedes v2 supersedes v1. + - [ ] Query with EpochAwareLens. + - [ ] Only v3 assertions visible. + +**Exit Criteria:** Historical queries and epoch filtering work correctly. + +--- + +### Arena 8: Skeptic & Conflict (Exercises Phase 3 Lenses) +*Goal: Surface disagreement, measure consensus.* + +**Depends on:** Arena 7 complete, Phase 3 Skeptic Lens + Conflict Score +**Aligns with:** `roadmap.md` Phase 3C "Skeptic Lens", Phase 3A.2 "Conflict Score" + +- [ ] **8.1 High-Conflict Scenario** + - [ ] 3 Scientist agents assert conflicting values for same fact. + - [ ] Each votes for own assertion. + - [ ] Query with `lens=Skeptic`. + - [ ] Verify `conflict_score` is high (> 0.5). + +- [ ] **8.2 Low-Conflict Scenario** + - [ ] 3 Scientists assert same value (agreement). + - [ ] Query with `lens=Skeptic`. + - [ ] Verify `conflict_score` is low (< 0.2). + +- [ ] **8.3 Skeptic Surfaces Outlier** + - [ ] Consensus is A, one dissenter says B. + - [ ] Skeptic lens returns B (the controversial position). + - [ ] **Use Case Alignment:** Financial Due Diligence "disagreement is the information." + +**Exit Criteria:** Conflict score accurately reflects disagreement. + +--- + +### Arena 9: Full Gameplay Loop (The Vision) +*Goal: Run the complete vision scenario end-to-end.* + +**Depends on:** Arena 8 complete, all Phase 3 features +**Aligns with:** `simulation-vision.md` "The Gameplay Loop" + +- [ ] **9.1 Ground Truth Injection** + - [ ] Load ground truth from YAML config. + - [ ] Scientists read ground truth, assert facts. + +- [ ] **9.2 The 5-Tick Scenario** + - [ ] Tick 1: Scientist asserts "Protein_X binds Receptor_Y". + - [ ] Tick 2: Troll forks with "Protein_X binds Nothing". + - [ ] Tick 3: Believer queries, votes for Scientist. + - [ ] Tick 4: TrustRank updates (Scientist up, Troll down). + - [ ] Tick 5: Verify consensus via lens. + +- [ ] **9.3 Extended Run (1000 Ticks)** + - [ ] Run full scenario for 1000 ticks. + - [ ] Track metrics: + - `truth_convergence`: % of facts matching ground truth. + - `reputation_distribution`: Scientist vs Troll ranks. + - `fork_depth_max`: Deepest contradiction chain. + +- [ ] **9.4 Success Criteria Verification** + - [ ] ✓ Truth survives: High-reputation assertions outlive spam. + - [ ] ✓ Lenses work: Consensus lens filters Troll noise. + - [ ] ✓ Performance: 1000 ticks complete in < 30 seconds. + - [ ] ✓ Emergence: Trust clusters form naturally. + +**Exit Criteria:** All 4 success criteria from vision document pass. + +--- + +## Alignment with Main Roadmap + +| Arena Phase | Exercises Roadmap Phase | Key Features Validated | +|-------------|------------------------|------------------------| +| Arena 0 | - | Test infrastructure | +| Arena 1 | Phase 2 | QueryEngine, Lenses, Lifecycle, Query Audit | +| Arena 2 | Phase 2 | VoteStore, VoteAwareConsensusLens | +| **Arena 2.5** | **- (Hardening)** | **Race conditions, API tests, crash recovery, input validation** | +| Arena 3 | Phase 2 | Materializer, Fast-Path MV | +| Arena 4 | - | Agent differentiation (simulator-only) | +| Arena 5 | Phase 4 | TrustRank, TrustAwareAuthorityLens | +| Arena 6 | Phase 4 | Concurrency, Performance | +| Arena 7 | Phase 2.5 + Phase 3 | Time-Travel, Epochs, EpochAwareLens | +| Arena 8 | Phase 3 | Skeptic Lens, Conflict Score | +| Arena 9 | All | Full integration | + +--- + +## Alignment with Use Cases + +| Use Case | Arena Phase That Validates It | +|----------|-------------------------------| +| **Agile Agent Team** | | +| - Lifecycle filtering | Arena 1.3 | +| - Query audit trail | Arena 1.4 | +| - Time-travel debugging | Arena 7.1 | +| - Expert weighting | Arena 5.3 | +| - Persistent learning | Arena 5.4 (TrustRank) | +| **Financial Due Diligence** | | +| - Conflict detection | Arena 8.1, 8.3 | +| - Time-travel | Arena 7.1 | +| - Epoch cascades | Arena 7.2, 7.3 | +| **Consumer Health** | | +| - Source-class hierarchy | Phase 3 dependency (not in Arena yet) | +| - Layered consensus | Phase 3 dependency | + +--- + +## Development Cadence + +| Week | Focus | Deliverable | +|------|-------|-------------| +| 1 | Arena 0 | CI-runnable simulation ✅ | +| 2 | Arena 1 | Query path verified ✅ | +| 3 | Arena 2 | Voting verified ✅ | +| **4** | **Arena 2.5** | **Hardening: race fix, API tests, crash recovery** | +| 5 | Arena 3 | Materializer + MVs verified | +| 6 | Arena 4 | Agent personas differentiated | +| 7-8 | Arena 5-6 | TrustRank + concurrency | +| 9-10 | Arena 7-8 | Time-travel + Skeptic | +| 11-12 | Arena 9 | Full gameplay loop | + +--- + +## Metrics to Track + +Once Arena 6+ is complete, export these to logs (and eventually Prometheus): + +| Metric | Description | Success Target | +|--------|-------------|----------------| +| `truth_convergence` | % of facts matching ground truth | > 95% | +| `troll_reputation` | Troll agent TrustRank at end | < 0.2 | +| `scientist_reputation` | Scientist agent TrustRank at end | > 0.8 | +| `fork_depth_max` | Deepest contradiction chain | < 10 | +| `p99_write_latency_ms` | Write path latency | < 10ms | +| `p99_query_latency_ms` | Query path latency | < 50ms | +| `concurrent_agents` | Max concurrent agents without errors | 1000 | + +--- + +## Non-Goals (Kept Simple) + +These are explicitly out of scope for the Arena: + +- **Prometheus/Grafana integration** - Logs suffice for Phase 3. +- **YAML scenario config** - Hardcoded scenarios are fine until Arena 9. +- **Full chaos injection (network partitions, node kills)** - Basic crash recovery in 2.5; advanced chaos deferred to Phase 4+. +- **External agent frameworks (ADK-Go)** - Simulator uses Rust agents. + +**Note:** HTTP API testing was previously a non-goal but is now addressed in Arena 2.5.2 due to critical gap discovery. + +--- + +## Next Step + +Arena 0, 1, and 2 are complete. **Before proceeding to Arena 3**, complete **Arena 2.5: Hardening**. + +### Priority Order for Arena 2.5: + +1. **2.5.1 Fix Vote Cache Race** (Day 1) — Critical, can cause data corruption +2. **2.5.2 API Integration Tests** (Day 2-3) — Critical, HTTP layer is untested +3. **2.5.3 Crash Recovery Test** (Day 4) — Critical, validates durability claims +4. **2.5.4 Input Validation** (Day 5) — High, defensive hardening +5. **2.5.5 Replace Sleep Timers** (Day 5) — High, faster/deterministic tests +6. **2.5.6 Fix Defensive Errors** (Day 6) — Medium, better error handling + +```bash +# Verify Arena 0 + 1 + 2 still work: +cargo test -p stemedb-sim + +# Binary also works: +cargo run --bin stemedb-sim +``` + +After Arena 2.5 is complete (production readiness ≥ 75), proceed to **Arena 3.1**: Materializer Integration. diff --git a/crates/stemedb-api/Cargo.toml b/crates/stemedb-api/Cargo.toml new file mode 100644 index 0000000..4e71cc5 --- /dev/null +++ b/crates/stemedb-api/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "stemedb-api" +version = "0.1.0" +edition = "2021" +description = "HTTP API for Episteme (StemeDB)" + +[lints] +workspace = true + +[dependencies] +stemedb-core = { path = "../stemedb-core" } +stemedb-wal = { path = "../stemedb-wal" } +stemedb-storage = { path = "../stemedb-storage" } +stemedb-ingest = { path = "../stemedb-ingest" } +stemedb-query = { path = "../stemedb-query" } +stemedb-lens = { path = "../stemedb-lens" } + +axum = { version = "0.7", features = ["json"] } +tokio = { version = "1", features = ["full"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +utoipa = { version = "5", features = ["axum_extras"] } +utoipa-axum = "0.1" +utoipa-swagger-ui = { version = "8", features = ["axum"] } +tower = { version = "0.4", features = ["util"] } +tower-http = { version = "0.5", features = ["trace", "cors"] } +futures = "0.3" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +thiserror = "1" +hex = "0.4" +blake3 = "1" + +[dev-dependencies] +tempfile = "3" +tower = { version = "0.4", features = ["util"] } +ed25519-dalek = { version = "2", features = ["rand_core"] } +rand = "0.8" +hex = "0.4" diff --git a/crates/stemedb-api/README.md b/crates/stemedb-api/README.md new file mode 100644 index 0000000..1f65b58 --- /dev/null +++ b/crates/stemedb-api/README.md @@ -0,0 +1,178 @@ +# stemedb-api + +HTTP API for Episteme (StemeDB) - a probabilistic knowledge graph database. + +## Architecture + +The API follows the standard axum pattern: + +- **DTOs** (`dto.rs`) - JSON request/response types with hex-encoded binary data +- **Handlers** (`handlers/`) - Thin HTTP handlers that delegate to underlying engines +- **State** (`state.rs`) - Shared application state (Journal, Store) +- **Router** (`lib.rs`) - axum router with OpenAPI support via utoipa + +## Write Path + +``` +POST /v1/assert → DTO → Assertion → serialize → append to WAL → return hash +``` + +## Read Path + +``` +GET /v1/query → QueryParams → Query → QueryEngine → Lens (optional) → DTOs +``` + +## Running the Server + +```bash +# Start the API server (defaults to http://127.0.0.1:3000) +cargo run --package stemedb-api + +# With custom configuration +STEMEDB_WAL_DIR=./my-wal STEMEDB_DB_DIR=./my-db STEMEDB_BIND_ADDR=0.0.0.0:8080 cargo run --package stemedb-api +``` + +The server automatically: +1. Opens Journal (WAL) and SledStore (KV storage) +2. Spawns IngestWorker background task to tail WAL +3. Starts HTTP server with OpenAPI documentation + +## API Documentation + +Once the server is running, visit: + +``` +http://127.0.0.1:3000/swagger-ui +``` + +This provides interactive OpenAPI documentation for all endpoints. + +## Endpoints + +### POST /v1/assert + +Create a new assertion. + +**Request:** +```json +{ + "subject": "Tesla_Inc", + "predicate": "has_revenue", + "object": { + "type": "Number", + "value": 96.7 + }, + "confidence": 0.95, + "signatures": [{ + "agent_id": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20", + "signature": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f40", + "timestamp": 1706745600 + }], + "source_hash": "0000000000000000000000000000000000000000000000000000000000000000" +} +``` + +**Response:** +```json +{ + "hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "status": "created" +} +``` + +### POST /v1/vote + +Create a vote on an existing assertion. + +**Request:** +```json +{ + "assertion_hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "agent_id": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20", + "weight": 0.8, + "signature": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f40" +} +``` + +**Response:** +```json +{ + "hash": "f3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "status": "created" +} +``` + +### GET /v1/query + +Query assertions with optional filters and lens. + +**Query Parameters:** +- `subject` (optional) - Filter by subject entity +- `predicate` (optional) - Filter by predicate/relation +- `lifecycle` (optional) - Filter by lifecycle stage (Proposed, UnderReview, Approved, Deprecated, Rejected) +- `epoch` (optional) - Filter by epoch (hex-encoded) +- `lens` (optional) - Apply lens for conflict resolution (Recency, Consensus, Authority, VoteAwareConsensus, TrustAwareAuthority) +- `limit` (optional) - Maximum results (default: 100) + +**Example:** +``` +GET /v1/query?subject=Tesla_Inc&predicate=has_revenue&lifecycle=Approved&lens=Recency +``` + +**Response:** +```json +{ + "assertions": [{ + "hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "subject": "Tesla_Inc", + "predicate": "has_revenue", + "object": { + "type": "Number", + "value": 96.7 + }, + "confidence": 0.95, + "lifecycle": "Approved", + "signatures": [...], + "timestamp": 1706745600, + "source_hash": "0000000000000000000000000000000000000000000000000000000000000000" + }], + "total_count": 1, + "has_more": false +} +``` + +### GET /v1/health + +Health check endpoint. + +**Response:** +```json +{ + "status": "healthy", + "version": "0.1.0", + "assertions_count": 42 +} +``` + +## Environment Variables + +- `STEMEDB_WAL_DIR` - Directory for WAL files (default: `data/wal`) +- `STEMEDB_DB_DIR` - Directory for KV store (default: `data/db`) +- `STEMEDB_BIND_ADDR` - HTTP server bind address (default: `127.0.0.1:3000`) + +## Binary Data Encoding + +All binary data (hashes, signatures, agent IDs) use hex encoding in JSON: +- Assertion hash: 32 bytes (64 hex characters) +- Agent ID (public key): 32 bytes (64 hex characters) +- Signature: 64 bytes (128 hex characters) +- Source hash: 32 bytes (64 hex characters) +- Visual hash (optional): 8 bytes (16 hex characters) + +## Critical Rules + +- **Append-Only**: The API never mutates existing assertions. Create new ones. +- **Content-Addressed**: Assertion ID = BLAKE3 hash of content. +- **No Unwrap**: All error handling uses `?` with context (enforced by clippy). +- **Defensive Writes**: All writes go through WAL with fsync. diff --git a/crates/stemedb-api/src/dto.rs b/crates/stemedb-api/src/dto.rs new file mode 100644 index 0000000..ba46cf4 --- /dev/null +++ b/crates/stemedb-api/src/dto.rs @@ -0,0 +1,916 @@ +//! Data Transfer Objects for the StemeDB HTTP API. +//! +//! These types define the JSON API contract. They use hex-encoded strings +//! for binary data (hashes, signatures, agent IDs) to be JSON-friendly. +//! +//! # Conversion Pattern +//! +//! DTOs convert to/from internal stemedb-core types: +//! - Request DTOs → internal types (decode hex to bytes) +//! - Internal types → Response DTOs (encode bytes to hex) + +use serde::{Deserialize, Serialize}; +use stemedb_core::types::{ + LifecycleStage, ObjectValue, SignatureEntry, SourceClass, SupersessionType, +}; +use utoipa::ToSchema; + +// ============================================================================ +// Request DTOs +// ============================================================================ + +/// Request to create a new assertion. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct CreateAssertionRequest { + /// The subject entity (e.g., "Tesla_Inc") + pub subject: String, + + /// The predicate/relation (e.g., "has_revenue") + pub predicate: String, + + /// The object value + pub object: ObjectValueDto, + + /// Confidence score (0.0 to 1.0) + #[schema(minimum = 0.0, maximum = 1.0)] + pub confidence: f32, + + /// Agent signatures vouching for this assertion + pub signatures: Vec, + + /// Hash of parent assertion (hex-encoded, optional for forks) + #[serde(skip_serializing_if = "Option::is_none")] + pub parent_hash: Option, + + /// Hash of source evidence (hex-encoded) + pub source_hash: String, + + /// Source authority tier (defaults to Expert if not specified) + #[serde(skip_serializing_if = "Option::is_none")] + pub source_class: Option, + + /// Perceptual hash for visual anchoring (hex-encoded, optional) + #[serde(skip_serializing_if = "Option::is_none")] + pub visual_hash: Option, + + /// Epoch ID (hex-encoded, optional) + #[serde(skip_serializing_if = "Option::is_none")] + pub epoch: Option, + + /// Lifecycle stage (defaults to Proposed if not specified) + #[serde(skip_serializing_if = "Option::is_none")] + pub lifecycle: Option, + + /// Semantic embedding vector (optional) + #[serde(skip_serializing_if = "Option::is_none")] + pub vector: Option>, +} + +/// Request to create a new vote on an assertion. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct CreateVoteRequest { + /// Hash of the assertion being voted on (hex-encoded) + pub assertion_hash: String, + + /// Public key of the voting agent (hex-encoded, 32 bytes) + pub agent_id: String, + + /// Weight of the vote (0.0 to 1.0) + #[schema(minimum = 0.0, maximum = 1.0)] + pub weight: f32, + + /// Signature over the assertion hash (hex-encoded, 64 bytes) + pub signature: String, +} + +/// Request to create a new epoch. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct CreateEpochRequest { + /// Human-readable name (e.g., "Pre-2024", "Newtonian") + pub name: String, + + /// ID of the epoch this supersedes (hex-encoded, optional) + #[serde(skip_serializing_if = "Option::is_none")] + pub supersedes: Option, + + /// How this epoch supersedes the previous one (optional) + #[serde(skip_serializing_if = "Option::is_none")] + pub supersession_type: Option, + + /// Start timestamp (Unix epoch, optional - defaults to now) + #[serde(skip_serializing_if = "Option::is_none")] + pub start_timestamp: Option, +} + +/// Request to supersede an assertion (error correction). +/// +/// Supersession enables error correction without violating append-only semantics. +/// Instead of mutating an assertion, we create a supersession record that points +/// from the old (target) to the new (replacement) assertion. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct SupersedeRequest { + /// Hash of the assertion being superseded (hex-encoded, 32 bytes) + pub target_hash: String, + + /// How the target is being superseded + pub supersession_type: SupersessionTypeDto, + + /// Human-readable explanation (for audit trail) + pub reason: String, + + /// Hash of the replacement assertion (hex-encoded, 32 bytes, optional) + /// None for RequiresReview (flagging, not replacing) or pure invalidation. + #[serde(skip_serializing_if = "Option::is_none")] + pub new_hash: Option, + + /// Public key of the agent creating the supersession (hex-encoded, 32 bytes) + pub agent_id: String, + + /// Signature over the supersession content (hex-encoded, 64 bytes) + /// Signs: BLAKE3(target_hash || type || reason || new_hash || timestamp) + pub signature: String, +} + +/// Response from creating a supersession. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct SupersedeResponse { + /// Status message + pub status: String, + + /// Hash of the target assertion that was superseded (hex-encoded) + pub target_hash: String, + + /// Type of supersession applied + pub supersession_type: SupersessionTypeDto, + + /// Unix timestamp when the supersession was recorded + pub timestamp: u64, +} + +/// Query parameters for searching assertions. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +#[serde(default)] +pub struct QueryParams { + /// Filter by subject entity + pub subject: Option, + + /// Filter by predicate/relation + pub predicate: Option, + + /// Filter by lifecycle stage + pub lifecycle: Option, + + /// Filter by epoch (hex-encoded) + pub epoch: Option, + + /// Apply a lens for conflict resolution + pub lens: Option, + + /// Maximum number of results to return (defaults to 100) + #[serde(default = "default_limit")] + pub limit: usize, + + /// Maximum acceptable staleness of materialized views in seconds. + /// + /// When set, the fast path (MV lookup) will be skipped if the materialized + /// view is older than this threshold. This causes the query to re-compute + /// the result from all candidate assertions. + /// + /// - Not set: Accept any MV age (default, fastest) + /// - 0: Never use cached MV, always compute fresh + /// - 60: Only use MV if materialized within the last 60 seconds + #[serde(skip_serializing_if = "Option::is_none")] + pub max_stale: Option, + + /// Filter by visual similarity to a reference pHash (hex-encoded, 16 chars). + /// + /// Returns assertions whose `visual_hash` has hamming distance <= `visual_threshold`. + /// Assertions without a `visual_hash` are excluded when this is set. + /// + /// Example: `visual_near=a3f2b1c4d5e6f708` finds assertions with similar screenshots. + #[serde(skip_serializing_if = "Option::is_none")] + pub visual_near: Option, + + /// Maximum hamming distance for `visual_near` matching (0-64, default: 8). + /// + /// Lower values require closer visual similarity: + /// - 0: Exact match only + /// - 8 (default): ~12.5% bit difference, catches resizing/compression + /// - 16: ~25% bit difference, more lenient + #[serde(skip_serializing_if = "Option::is_none")] + pub visual_threshold: Option, +} + +fn default_limit() -> usize { + 100 +} + +impl Default for QueryParams { + fn default() -> Self { + Self { + subject: None, + predicate: None, + lifecycle: None, + epoch: None, + lens: None, + limit: 100, + max_stale: None, + visual_near: None, + visual_threshold: None, + } + } +} + +// ============================================================================ +// Response DTOs +// ============================================================================ + +/// Response containing a single assertion. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct AssertionResponse { + /// Content-addressed hash of this assertion (hex-encoded) + pub hash: String, + + /// The subject entity + pub subject: String, + + /// The predicate/relation + pub predicate: String, + + /// The object value + pub object: ObjectValueDto, + + /// Hash of parent assertion (hex-encoded, optional) + #[serde(skip_serializing_if = "Option::is_none")] + pub parent_hash: Option, + + /// Hash of source evidence (hex-encoded) + pub source_hash: String, + + /// Source authority tier + pub source_class: SourceClassDto, + + /// Perceptual hash for visual anchoring (hex-encoded, optional) + #[serde(skip_serializing_if = "Option::is_none")] + pub visual_hash: Option, + + /// Epoch ID (hex-encoded, optional) + #[serde(skip_serializing_if = "Option::is_none")] + pub epoch: Option, + + /// Lifecycle stage + pub lifecycle: LifecycleDto, + + /// Agent signatures + pub signatures: Vec, + + /// Confidence score (0.0 to 1.0) + pub confidence: f32, + + /// Creation timestamp (Unix epoch) + pub timestamp: u64, + + /// Semantic embedding vector (optional) + #[serde(skip_serializing_if = "Option::is_none")] + pub vector: Option>, +} + +/// Response from a query operation. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct QueryResponse { + /// Matching assertions + pub assertions: Vec, + + /// Total number of results returned + pub total_count: usize, + + /// Whether there are more results beyond the limit + pub has_more: bool, +} + +/// Response from a create operation. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct CreateResponse { + /// Content-addressed hash of the created resource (hex-encoded) + pub hash: String, + + /// Status message + pub status: String, +} + +/// Error response. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct ErrorResponse { + /// Human-readable error message + pub error: String, + + /// Machine-readable error code + pub code: String, +} + +/// Health check response. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct HealthResponse { + /// Service status (e.g., "healthy") + pub status: String, + + /// API version + pub version: String, + + /// Total number of assertions in the database + pub assertions_count: u64, +} + +// ============================================================================ +// Enum DTOs +// ============================================================================ + +/// Object value in an assertion. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +#[serde(tag = "type", content = "value")] +pub enum ObjectValueDto { + /// Text string value + Text(String), + + /// Numeric value (float) + Number(f64), + + /// Boolean value + Boolean(bool), + + /// Reference to another entity + Reference(String), +} + +/// Lifecycle stage of an assertion. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema)] +#[serde(rename_all = "PascalCase")] +pub enum LifecycleDto { + /// Initial proposal, idea, or RFC + Proposed, + + /// Under active review or debate + UnderReview, + + /// Accepted as current truth + Approved, + + /// Was true, now superseded + Deprecated, + + /// Considered and explicitly declined + Rejected, +} + +/// Source authority tier classification. +/// +/// Sources are tiered from most authoritative (Regulatory, Tier 0) to +/// least authoritative (Anecdotal, Tier 5). This enables indexing by +/// tier and tier-based decay rates. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema)] +#[serde(rename_all = "PascalCase")] +pub enum SourceClassDto { + /// Tier 0: Regulatory bodies (FDA, EMA, WHO) + Regulatory, + + /// Tier 1: Clinical trials, peer-reviewed research + Clinical, + + /// Tier 2: Observational studies, real-world evidence + Observational, + + /// Tier 3: Expert opinions, medical guidelines + Expert, + + /// Tier 4: Curated community knowledge + Community, + + /// Tier 5: Individual reports, testimonials, social media + Anecdotal, +} + +/// Type of supersession (epoch or assertion). +/// +/// Determines how old knowledge should be treated when superseded. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema)] +#[serde(rename_all = "PascalCase")] +pub enum SupersessionTypeDto { + /// Old assertion was factually incorrect and should be hidden/ignored. + Invalidate, + + /// Old assertion was correct at the time but now outdated. + Temporal, + + /// Old assertion was a simplification; new one is more precise. + Refinement, + + /// Old assertion needs human review before trusting. + RequiresReview, + + /// New assertion adds context without invalidating the old one. + Additive, +} + +/// Lens strategy for conflict resolution. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema)] +#[serde(rename_all = "PascalCase")] +pub enum LensDto { + /// Latest timestamp wins + Recency, + + /// Most common object value + Consensus, + + /// Highest assertion confidence field wins. + /// Use this when assertions have meaningful self-declared confidence scores. + Confidence, + + /// Weighted by agent reputation (TrustRank). + /// This is the real "authority" lens - uses agent history and reputation. + /// Equivalent to TrustAwareAuthority. + Authority, + + /// Highest vote weight from VoteStore + VoteAwareConsensus, + + /// Weighted by TrustRank reputation. + /// Same as Authority - both route to TrustAwareAuthorityLens. + TrustAwareAuthority, + + /// Filters assertions from superseded epochs before applying Recency. + /// Use when querying across paradigm shifts (e.g., GAAP to IFRS transition). + /// Assertions from epochs that have been superseded by newer epochs are excluded. + EpochAware, +} + +/// Agent signature entry. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct SignatureDto { + /// Ed25519 public key of the agent (hex-encoded, 32 bytes) + pub agent_id: String, + + /// Ed25519 signature (hex-encoded, 64 bytes) + pub signature: String, + + /// Timestamp when the agent signed (Unix epoch) + pub timestamp: u64, +} + +// ============================================================================ +// Conversions: DTOs ↔ Internal Types +// ============================================================================ + +impl From for ObjectValueDto { + fn from(value: ObjectValue) -> Self { + match value { + ObjectValue::Text(s) => ObjectValueDto::Text(s), + ObjectValue::Number(n) => ObjectValueDto::Number(n), + ObjectValue::Boolean(b) => ObjectValueDto::Boolean(b), + ObjectValue::Reference(r) => ObjectValueDto::Reference(r), + } + } +} + +impl From for ObjectValue { + fn from(dto: ObjectValueDto) -> Self { + match dto { + ObjectValueDto::Text(s) => ObjectValue::Text(s), + ObjectValueDto::Number(n) => ObjectValue::Number(n), + ObjectValueDto::Boolean(b) => ObjectValue::Boolean(b), + ObjectValueDto::Reference(r) => ObjectValue::Reference(r), + } + } +} + +impl From for LifecycleDto { + fn from(stage: LifecycleStage) -> Self { + match stage { + LifecycleStage::Proposed => LifecycleDto::Proposed, + LifecycleStage::UnderReview => LifecycleDto::UnderReview, + LifecycleStage::Approved => LifecycleDto::Approved, + LifecycleStage::Deprecated => LifecycleDto::Deprecated, + LifecycleStage::Rejected => LifecycleDto::Rejected, + } + } +} + +impl From for LifecycleStage { + fn from(dto: LifecycleDto) -> Self { + match dto { + LifecycleDto::Proposed => LifecycleStage::Proposed, + LifecycleDto::UnderReview => LifecycleStage::UnderReview, + LifecycleDto::Approved => LifecycleStage::Approved, + LifecycleDto::Deprecated => LifecycleStage::Deprecated, + LifecycleDto::Rejected => LifecycleStage::Rejected, + } + } +} + +impl From for SupersessionTypeDto { + fn from(stype: SupersessionType) -> Self { + match stype { + SupersessionType::Invalidate => SupersessionTypeDto::Invalidate, + SupersessionType::Temporal => SupersessionTypeDto::Temporal, + SupersessionType::Refinement => SupersessionTypeDto::Refinement, + SupersessionType::RequiresReview => SupersessionTypeDto::RequiresReview, + SupersessionType::Additive => SupersessionTypeDto::Additive, + } + } +} + +impl From for SupersessionType { + fn from(dto: SupersessionTypeDto) -> Self { + match dto { + SupersessionTypeDto::Invalidate => SupersessionType::Invalidate, + SupersessionTypeDto::Temporal => SupersessionType::Temporal, + SupersessionTypeDto::Refinement => SupersessionType::Refinement, + SupersessionTypeDto::RequiresReview => SupersessionType::RequiresReview, + SupersessionTypeDto::Additive => SupersessionType::Additive, + } + } +} + +impl From for SourceClassDto { + fn from(sc: SourceClass) -> Self { + match sc { + SourceClass::Regulatory => SourceClassDto::Regulatory, + SourceClass::Clinical => SourceClassDto::Clinical, + SourceClass::Observational => SourceClassDto::Observational, + SourceClass::Expert => SourceClassDto::Expert, + SourceClass::Community => SourceClassDto::Community, + SourceClass::Anecdotal => SourceClassDto::Anecdotal, + } + } +} + +impl From for SourceClass { + fn from(dto: SourceClassDto) -> Self { + match dto { + SourceClassDto::Regulatory => SourceClass::Regulatory, + SourceClassDto::Clinical => SourceClass::Clinical, + SourceClassDto::Observational => SourceClass::Observational, + SourceClassDto::Expert => SourceClass::Expert, + SourceClassDto::Community => SourceClass::Community, + SourceClassDto::Anecdotal => SourceClass::Anecdotal, + } + } +} + +impl From for SignatureDto { + fn from(entry: SignatureEntry) -> Self { + SignatureDto { + agent_id: hex::encode(entry.agent_id), + signature: hex::encode(entry.signature), + timestamp: entry.timestamp, + } + } +} + +// ============================================================================ +// Query Audit DTOs +// ============================================================================ + +/// Query parameters for listing query audits. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, utoipa::IntoParams)] +#[serde(default)] +pub struct AuditQueryParams { + /// Filter by agent public key (hex-encoded, 32 bytes) + pub agent_id: Option, + + /// Start of time range (Unix timestamp) + pub from: Option, + + /// End of time range (Unix timestamp) + pub to: Option, + + /// Maximum number of results to return (defaults to 100) + #[serde(default = "default_limit")] + pub limit: usize, +} + +impl Default for AuditQueryParams { + fn default() -> Self { + Self { agent_id: None, from: None, to: None, limit: 100 } + } +} + +/// Response containing a query audit record. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct QueryAuditResponse { + /// Unique identifier for this query (hex-encoded, 32 bytes) + pub query_id: String, + + /// Agent public key who made the query (hex-encoded, optional) + #[serde(skip_serializing_if = "Option::is_none")] + pub agent_id: Option, + + /// Unix timestamp when the query was executed + pub timestamp: u64, + + /// Query parameters that were used + pub params: QueryParamsAuditDto, + + /// Hash of the winning assertion (hex-encoded, optional) + #[serde(skip_serializing_if = "Option::is_none")] + pub result_hash: Option, + + /// Confidence score of the resolution (0.0 to 1.0) + pub result_confidence: f32, + + /// Assertions that contributed to this result + pub contributing_assertions: Vec, +} + +/// Query parameters captured for audit purposes. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct QueryParamsAuditDto { + /// Filter by subject entity + #[serde(skip_serializing_if = "Option::is_none")] + pub subject: Option, + + /// Filter by predicate/relation + #[serde(skip_serializing_if = "Option::is_none")] + pub predicate: Option, + + /// Filter by lifecycle stage + #[serde(skip_serializing_if = "Option::is_none")] + pub lifecycle: Option, + + /// Filter by epoch (hex-encoded) + #[serde(skip_serializing_if = "Option::is_none")] + pub epoch: Option, + + /// Lens used for conflict resolution + #[serde(skip_serializing_if = "Option::is_none")] + pub lens: Option, +} + +/// An assertion that contributed to a query result. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct ContributingAssertionDto { + /// Hash of the assertion (hex-encoded) + pub assertion_hash: String, + + /// How much this assertion influenced the result (0.0 to 1.0) + pub weight: f32, + + /// Hash of the source evidence (hex-encoded) + pub source_hash: String, + + /// Lifecycle stage of this assertion + pub lifecycle: LifecycleDto, +} + +/// Response from listing query audits. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct QueryAuditListResponse { + /// List of query audit records + pub audits: Vec, + + /// Total number of results returned + pub total_count: usize, +} + +// Conversions from internal types +impl From for QueryAuditResponse { + fn from(audit: stemedb_core::types::QueryAudit) -> Self { + QueryAuditResponse { + query_id: hex::encode(audit.query_id), + agent_id: audit.agent_id.map(hex::encode), + timestamp: audit.timestamp, + params: QueryParamsAuditDto { + subject: audit.params.subject, + predicate: audit.params.predicate, + lifecycle: audit.params.lifecycle.map(Into::into), + epoch: audit.params.epoch.map(hex::encode), + lens: audit.params.lens, + }, + result_hash: audit.result_hash.map(hex::encode), + result_confidence: audit.result_confidence, + contributing_assertions: audit + .contributing_assertions + .into_iter() + .map(Into::into) + .collect(), + } + } +} + +impl From for ContributingAssertionDto { + fn from(ca: stemedb_core::types::ContributingAssertion) -> Self { + ContributingAssertionDto { + assertion_hash: hex::encode(ca.assertion_hash), + weight: ca.weight, + source_hash: hex::encode(ca.source_hash), + lifecycle: ca.lifecycle.into(), + } + } +} + +// ============================================================================ +// Skeptic View DTOs ("Trust but Verify") +// ============================================================================ + +/// Query parameters for the skeptic endpoint. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, utoipa::IntoParams)] +pub struct SkepticQueryParams { + /// Subject entity to analyze (required) + pub subject: String, + + /// Predicate/relation to analyze (required) + pub predicate: String, +} + +/// Resolution status indicating level of agreement. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema)] +pub enum ResolutionStatusDto { + /// All assertions agree on the same value + Unanimous, + /// Strong majority (>75% weight) agrees + Agreed, + /// No clear consensus; significant disagreement exists + Contested, +} + +impl From for ResolutionStatusDto { + fn from(status: stemedb_core::types::ResolutionStatus) -> Self { + match status { + stemedb_core::types::ResolutionStatus::Unanimous => ResolutionStatusDto::Unanimous, + stemedb_core::types::ResolutionStatus::Agreed => ResolutionStatusDto::Agreed, + stemedb_core::types::ResolutionStatus::Contested => ResolutionStatusDto::Contested, + } + } +} + +/// Summary of a single claim in the conflict analysis. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct ClaimSummaryDto { + /// The claimed value + pub value: ObjectValueDto, + + /// Normalized weight (0.0 to 1.0) relative to all claims + #[schema(minimum = 0.0, maximum = 1.0)] + pub weight_share: f32, + + /// Number of assertions making this exact claim + pub assertion_count: u32, + + /// Hash of the representative assertion (hex-encoded) + pub representative_hash: String, + + /// Source provenance + pub source: SourceSummaryDto, + + /// Agents supporting this claim + pub supporting_agents: Vec, +} + +/// Source provenance summary. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct SourceSummaryDto { + /// Hash of the source document (hex-encoded) + pub source_hash: String, + + /// Visual anchor hash (hex-encoded, optional) + #[serde(skip_serializing_if = "Option::is_none")] + pub visual_hash: Option, +} + +/// Agent summary with trust score. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct AgentSummaryDto { + /// Agent's public key (hex-encoded) + pub agent_id: String, + + /// Trust score at query time (0.0 to 1.0) + #[schema(minimum = 0.0, maximum = 1.0)] + pub trust_score: f32, +} + +/// Response from the skeptic endpoint. +/// +/// This is the "Trust but Verify" response that shows all competing claims +/// instead of hiding conflict behind a single winner. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct SkepticResponse { + /// The subject that was queried + pub subject: String, + + /// The predicate that was queried + pub predicate: String, + + /// Overall resolution status + pub status: ResolutionStatusDto, + + /// Conflict score (0.0 = unanimous, 1.0 = chaos) + #[schema(minimum = 0.0, maximum = 1.0)] + pub conflict_score: f32, + + /// All distinct claims, ranked by weight_share descending + pub claims: Vec, + + /// Total number of candidate assertions considered + pub candidates_count: usize, + + /// Unix timestamp when this view was computed + pub computed_at: u64, + + /// Which lens was used (always "Skeptic") + pub lens_name: String, +} + +// Conversion from internal types +impl From for SkepticResponse { + fn from(view: stemedb_query::SkepticView) -> Self { + SkepticResponse { + subject: view.subject, + predicate: view.predicate, + status: view.analysis.status.into(), + conflict_score: view.analysis.conflict_score, + claims: view.analysis.claims.into_iter().map(Into::into).collect(), + candidates_count: view.analysis.candidates_count, + computed_at: view.computed_at, + lens_name: view.lens_name, + } + } +} + +impl From for ClaimSummaryDto { + fn from(claim: stemedb_core::types::ClaimSummary) -> Self { + ClaimSummaryDto { + value: claim.value.into(), + weight_share: claim.weight_share, + assertion_count: claim.assertion_count, + representative_hash: hex::encode(claim.representative_hash), + source: SourceSummaryDto { + source_hash: hex::encode(claim.source.source_hash), + visual_hash: claim.source.visual_hash.map(hex::encode), + }, + supporting_agents: claim.supporting_agents.into_iter().map(Into::into).collect(), + } + } +} + +impl From for AgentSummaryDto { + fn from(agent: stemedb_core::types::AgentSummary) -> Self { + AgentSummaryDto { agent_id: hex::encode(agent.agent_id), trust_score: agent.trust_score } + } +} + +// ============================================================================ +// Trace API DTOs (Agent Decision Tracing) +// ============================================================================ + +/// Query parameters for the trace endpoint. +/// +/// Returns a filtered list of query audits for debugging agent decision-making. +/// All parameters are optional filters that narrow down results. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, utoipa::IntoParams)] +#[serde(default)] +pub struct TraceParams { + /// Filter by agent public key (hex-encoded, 32 bytes) - required + pub agent_id: String, + + /// Start of time range (Unix timestamp or ISO8601) - required + pub from: String, + + /// End of time range (Unix timestamp or ISO8601, defaults to now) + #[serde(skip_serializing_if = "Option::is_none")] + pub to: Option, + + /// Filter by subject pattern (e.g., "Tesla*", "auth/*") + #[serde(skip_serializing_if = "Option::is_none")] + pub subject: Option, + + /// Maximum number of results (default: 100) + #[serde(default = "default_limit")] + pub limit: usize, +} + +impl Default for TraceParams { + fn default() -> Self { + Self { agent_id: String::new(), from: String::new(), to: None, subject: None, limit: 100 } + } +} + +/// Response from the trace endpoint. +/// +/// Returns query audits matching the trace filters, useful for debugging +/// why an agent made specific decisions. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct TraceResponse { + /// Matching query audit records + pub audits: Vec, + + /// Total number of results returned + pub total_count: usize, + + /// Agent ID that was traced (hex-encoded) + pub agent_id: String, + + /// Time range start (Unix timestamp) + pub from_timestamp: u64, + + /// Time range end (Unix timestamp) + pub to_timestamp: u64, +} diff --git a/crates/stemedb-api/src/error.rs b/crates/stemedb-api/src/error.rs new file mode 100644 index 0000000..2e495d9 --- /dev/null +++ b/crates/stemedb-api/src/error.rs @@ -0,0 +1,102 @@ +//! Error types for the StemeDB API. + +use axum::{ + http::StatusCode, + response::{IntoResponse, Response}, + Json, +}; +use thiserror::Error; + +use crate::dto::ErrorResponse; + +/// API-level errors. +#[derive(Debug, Error)] +pub enum ApiError { + /// Invalid hex encoding in request. + #[error("Invalid hex encoding: {0}")] + InvalidHex(String), + + /// Hash has incorrect byte length. + #[error("Invalid hash length: expected {expected}, got {actual}")] + InvalidHashLength { + /// Expected length in bytes. + expected: usize, + /// Actual length in bytes. + actual: usize, + }, + + /// Write-ahead log error. + #[error("WAL error: {0}")] + Wal(#[from] stemedb_wal::QuarantineError), + + /// Storage backend error. + #[error("Storage error: {0}")] + Storage(#[from] stemedb_storage::StorageError), + + /// Serialization/deserialization error. + #[error("Serialization error: {0}")] + Serialization(String), + + /// Ingestion pipeline error. + #[error("Ingest error: {0}")] + Ingest(#[from] stemedb_ingest::error::IngestError), + + /// Query execution error. + #[error("Query error: {0}")] + Query(#[from] stemedb_query::QueryError), + + /// Invalid request parameters. + #[error("Invalid request: {0}")] + InvalidRequest(String), + + /// Resource not found. + #[error("Not found: {0}")] + NotFound(String), + + /// Resource conflict (e.g., already superseded). + #[error("Conflict: {0}")] + Conflict(String), + + /// Internal server error. + #[error("Internal error: {0}")] + Internal(String), +} + +impl IntoResponse for ApiError { + fn into_response(self) -> Response { + let (status, code, message) = match self { + ApiError::InvalidHex(ref msg) => (StatusCode::BAD_REQUEST, "INVALID_HEX", msg.clone()), + ApiError::InvalidHashLength { .. } => { + (StatusCode::BAD_REQUEST, "INVALID_HASH_LENGTH", self.to_string()) + } + ApiError::InvalidRequest(ref msg) => { + (StatusCode::BAD_REQUEST, "INVALID_REQUEST", msg.clone()) + } + ApiError::NotFound(ref msg) => (StatusCode::NOT_FOUND, "NOT_FOUND", msg.clone()), + ApiError::Wal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "WAL_ERROR", self.to_string()), + ApiError::Storage(_) => { + (StatusCode::INTERNAL_SERVER_ERROR, "STORAGE_ERROR", self.to_string()) + } + ApiError::Serialization(_) => { + (StatusCode::INTERNAL_SERVER_ERROR, "SERIALIZATION_ERROR", self.to_string()) + } + ApiError::Ingest(_) => { + (StatusCode::INTERNAL_SERVER_ERROR, "INGEST_ERROR", self.to_string()) + } + ApiError::Query(_) => { + (StatusCode::INTERNAL_SERVER_ERROR, "QUERY_ERROR", self.to_string()) + } + ApiError::Conflict(ref msg) => (StatusCode::CONFLICT, "CONFLICT", msg.clone()), + ApiError::Internal(ref msg) => { + (StatusCode::INTERNAL_SERVER_ERROR, "INTERNAL_ERROR", msg.clone()) + } + }; + + let error_response = ErrorResponse { error: message, code: code.to_string() }; + + (status, Json(error_response)).into_response() + } +} + +/// Result type for API operations. +pub type Result = std::result::Result; diff --git a/crates/stemedb-api/src/handlers/assert.rs b/crates/stemedb-api/src/handlers/assert.rs new file mode 100644 index 0000000..335868a --- /dev/null +++ b/crates/stemedb-api/src/handlers/assert.rs @@ -0,0 +1,122 @@ +//! Handler for creating assertions. + +use axum::{extract::State, http::StatusCode, Json}; +use tracing::instrument; + +use crate::{ + dto::{CreateAssertionRequest, CreateResponse, ErrorResponse, SignatureDto}, + error::{ApiError, Result}, + hex, + state::AppState, +}; + +use stemedb_core::types::{Assertion, LifecycleStage, ObjectValue, SignatureEntry, SourceClass}; +use stemedb_ingest::worker::serialize_assertion; + +/// Create a new assertion in the knowledge graph. +/// +/// This endpoint accepts an assertion DTO, validates confidence bounds (0.0-1.0), +/// converts hex-encoded fields to binary, serializes the assertion to WAL format, +/// and appends it to the journal. Returns the content-addressed BLAKE3 hash. +/// +/// # Validation +/// - Confidence must be between 0.0 and 1.0 +/// - At least one signature is required +/// - All hex fields must have correct lengths (32 bytes for hashes, 64 bytes for signatures) +#[utoipa::path( + post, + path = "/v1/assert", + request_body = CreateAssertionRequest, + responses( + (status = 201, description = "Assertion created successfully", body = CreateResponse), + (status = 400, description = "Invalid request", body = ErrorResponse), + (status = 500, description = "Internal server error", body = ErrorResponse) + ), + tag = "assertions" +)] +#[instrument(skip(state), fields(subject = %req.subject, predicate = %req.predicate))] +pub async fn create_assertion( + State(state): State, + Json(req): Json, +) -> Result<(StatusCode, Json)> { + // Convert DTO to internal Assertion type + let assertion = dto_to_assertion(req)?; + + // Serialize to WAL format (includes record type header) + let payload = serialize_assertion(&assertion) + .map_err(|e| ApiError::Serialization(format!("Failed to serialize assertion: {}", e)))?; + + // Compute the content-addressed hash + // This must match the hash computation in the ingest worker + let serialized_assertion = stemedb_core::serde::serialize(&assertion) + .map_err(|e| ApiError::Serialization(format!("Failed to serialize for hash: {}", e)))?; + let hash = blake3::hash(&serialized_assertion); + + // Append to WAL + let mut journal = state.journal.lock().await; + journal.append(payload)?; + + let response = + CreateResponse { hash: hash.to_hex().to_string(), status: "created".to_string() }; + + Ok((StatusCode::CREATED, Json(response))) +} + +/// Convert CreateAssertionRequest DTO to internal Assertion type. +fn dto_to_assertion(req: CreateAssertionRequest) -> Result { + // Validate confidence bounds (0.0 to 1.0) + if req.confidence < 0.0 || req.confidence > 1.0 { + return Err(ApiError::InvalidRequest(format!( + "Confidence must be between 0.0 and 1.0, got {}", + req.confidence + ))); + } + + // Decode hex fields using shared hex module + let parent_hash = req.parent_hash.map(|h| hex::decode_hash_32(&h)).transpose()?; + + let source_hash = hex::decode_hash_32(&req.source_hash)?; + + let visual_hash = req.visual_hash.map(|h| hex::decode_hash_8(&h)).transpose()?; + + let epoch = req.epoch.map(|e| hex::decode_hash_32(&e)).transpose()?; + + // Convert signatures + let signatures = + req.signatures.into_iter().map(decode_signature).collect::>>()?; + + // Validate signatures are not empty + if signatures.is_empty() { + return Err(ApiError::InvalidRequest("At least one signature is required".to_string())); + } + + // Get current timestamp + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|e| ApiError::Serialization(format!("Failed to get timestamp: {}", e)))? + .as_secs(); + + Ok(Assertion { + subject: req.subject, + predicate: req.predicate, + object: ObjectValue::from(req.object), + parent_hash, + source_hash, + source_class: req.source_class.map(Into::into).unwrap_or(SourceClass::Expert), + visual_hash, + epoch, + lifecycle: req.lifecycle.map(Into::into).unwrap_or(LifecycleStage::Proposed), + signatures, + confidence: req.confidence, + timestamp, + vector: req.vector, + }) +} + +/// Decode a signature DTO. +fn decode_signature(dto: SignatureDto) -> Result { + let agent_id = hex::decode_hash_32(&dto.agent_id)?; + let signature = hex::decode_signature(&dto.signature)?; + + Ok(SignatureEntry { agent_id, signature, timestamp: dto.timestamp }) +} diff --git a/crates/stemedb-api/src/handlers/audit.rs b/crates/stemedb-api/src/handlers/audit.rs new file mode 100644 index 0000000..fa94fa0 --- /dev/null +++ b/crates/stemedb-api/src/handlers/audit.rs @@ -0,0 +1,101 @@ +//! Handlers for query audit trail endpoints. + +use axum::{ + extract::{Path, Query as AxumQuery, State}, + Json, +}; +use tracing::instrument; + +use crate::{ + dto::{AuditQueryParams, QueryAuditListResponse, QueryAuditResponse}, + error::{ApiError, Result}, + hex as hex_utils, + state::AppState, +}; + +use stemedb_storage::{AuditStore, GenericAuditStore}; + +/// List recent query audits with optional filters. +/// +/// Returns a paginated list of query audit records. Use the `agent_id` and +/// time range filters to narrow down results for incident investigation. +/// +/// # Query Parameters +/// +/// - `agent_id` (optional): Filter by agent public key (hex-encoded, 32 bytes) +/// - `from` (optional): Start of time range (Unix timestamp) +/// - `to` (optional): End of time range (Unix timestamp) +/// - `limit` (optional): Maximum number of results (default: 100) +#[utoipa::path( + get, + path = "/v1/audit/queries", + params(AuditQueryParams), + responses( + (status = 200, description = "List of query audits", body = QueryAuditListResponse), + (status = 400, description = "Invalid request", body = crate::dto::ErrorResponse), + (status = 500, description = "Internal server error", body = crate::dto::ErrorResponse) + ), + tag = "audit" +)] +#[instrument(skip(state), fields( + agent_id = ?params.agent_id, + from = ?params.from, + to = ?params.to, + limit = params.limit +))] +pub async fn list_audits( + State(state): State, + AxumQuery(params): AxumQuery, +) -> Result> { + let audit_store = GenericAuditStore::new(state.store.clone()); + + let audits = if let Some(agent_id_hex) = params.agent_id { + // Filter by agent with limit pushed down to storage layer + let agent_id = hex_utils::decode_agent_id(&agent_id_hex)?; + let from = params.from.unwrap_or(0); + let to = params.to; + audit_store.get_audits_for_agent(&agent_id, from, to, params.limit).await? + } else { + // List recent (limit already applied in storage layer) + audit_store.list_recent_audits(params.limit).await? + }; + let total_count = audits.len(); + + // Convert to response DTOs + let audit_responses: Vec = + audits.into_iter().map(QueryAuditResponse::from).collect(); + + Ok(Json(QueryAuditListResponse { audits: audit_responses, total_count })) +} + +/// Get a specific query audit by ID. +/// +/// Returns the full audit record including all contributing assertions +/// that influenced the query result. +#[utoipa::path( + get, + path = "/v1/audit/query/{id}", + params( + ("id" = String, Path, description = "Query ID (hex-encoded, 32 bytes)") + ), + responses( + (status = 200, description = "Query audit details", body = QueryAuditResponse), + (status = 400, description = "Invalid query ID", body = crate::dto::ErrorResponse), + (status = 404, description = "Audit not found", body = crate::dto::ErrorResponse), + (status = 500, description = "Internal server error", body = crate::dto::ErrorResponse) + ), + tag = "audit" +)] +#[instrument(skip(state), fields(query_id = %id))] +pub async fn get_audit( + State(state): State, + Path(id): Path, +) -> Result> { + let query_id = hex_utils::decode_hash_32(&id)?; + let audit_store = GenericAuditStore::new(state.store.clone()); + + match audit_store.get_audit(&query_id).await? { + Some(audit) => Ok(Json(QueryAuditResponse::from(audit))), + None => Err(ApiError::NotFound(format!("Query audit not found: {}", id))), + } +} diff --git a/crates/stemedb-api/src/handlers/epoch.rs b/crates/stemedb-api/src/handlers/epoch.rs new file mode 100644 index 0000000..148ddfb --- /dev/null +++ b/crates/stemedb-api/src/handlers/epoch.rs @@ -0,0 +1,299 @@ +//! Handler for creating epochs. + +use axum::{extract::State, http::StatusCode, Json}; +use tracing::instrument; + +use crate::{ + dto::{CreateEpochRequest, CreateResponse, ErrorResponse}, + error::{ApiError, Result}, + hex, + state::AppState, +}; + +use stemedb_core::types::Epoch; +use stemedb_ingest::worker::serialize_epoch; + +/// Create a new epoch (paradigm) in the knowledge graph. +/// +/// Epochs represent distinct periods of truth or worldviews. Assertions can +/// reference epochs to indicate which paradigm they belong to. Epochs can +/// supersede previous epochs via Invalidation, Temporal, or Refinement. +/// +/// # Epoch ID Generation +/// +/// The epoch ID is computed as BLAKE3 hash of a canonical string representation: +/// `"{name}:{supersedes_hex}:{timestamp}"`. This ensures: +/// - Deterministic IDs for the same input (same name + timestamp = same ID) +/// - IDs that won't change if the Epoch struct's serialization format changes +/// - Human-readable debugging via the canonical format +/// +/// # Validation +/// +/// - Name must be non-empty +/// - Supersedes field, if provided, must be a valid 32-byte hex-encoded hash +/// - If supersedes is provided, supersession_type is required +/// +/// # Example Request +/// +/// ```json +/// { +/// "name": "GAAP-2024", +/// "supersedes": "a1b2c3...", // optional, hex-encoded 32-byte hash +/// "supersession_type": "Temporal", // optional +/// "start_timestamp": 1704067200 // optional, defaults to now +/// } +/// ``` +#[utoipa::path( + post, + path = "/v1/epoch", + request_body = CreateEpochRequest, + responses( + (status = 201, description = "Epoch created successfully", body = CreateResponse), + (status = 400, description = "Invalid request", body = ErrorResponse), + (status = 500, description = "Internal server error", body = ErrorResponse) + ), + tag = "epochs" +)] +#[instrument(skip(state), fields(name = %req.name))] +pub async fn create_epoch( + State(state): State, + Json(req): Json, +) -> Result<(StatusCode, Json)> { + // Convert DTO to internal Epoch type + let epoch = dto_to_epoch(req)?; + + // Serialize to WAL format (includes record type header) + let payload = serialize_epoch(&epoch) + .map_err(|e| ApiError::Serialization(format!("Failed to serialize epoch: {}", e)))?; + + // The epoch ID is already computed from the content hash during dto_to_epoch + // For the response, we return this same ID as a hex string + let epoch_id_hex = ::hex::encode(epoch.id); + + // Append to WAL + let mut journal = state.journal.lock().await; + journal.append(payload)?; + + let response = CreateResponse { hash: epoch_id_hex, status: "created".to_string() }; + + Ok((StatusCode::CREATED, Json(response))) +} + +/// Convert CreateEpochRequest DTO to internal Epoch type. +/// +/// Generates a content-addressed epoch ID by hashing a canonical string +/// representation: `"{name}:{supersedes_hex}:{timestamp}"`. This differs +/// from assertions (which hash serialized bytes) to provide stable IDs +/// that won't change with struct serialization format changes. +fn dto_to_epoch(req: CreateEpochRequest) -> Result { + // Validate name is non-empty + if req.name.trim().is_empty() { + return Err(ApiError::InvalidRequest("Epoch name cannot be empty".to_string())); + } + + // Decode supersedes epoch ID if provided + let supersedes = req.supersedes.map(|h| hex::decode_hash_32(&h)).transpose()?; + + // Convert supersession_type if provided + let supersession_type = req.supersession_type.map(Into::into); + + // Validate: if supersedes is provided, supersession_type should also be provided + if supersedes.is_some() && supersession_type.is_none() { + return Err(ApiError::InvalidRequest( + "supersession_type is required when supersedes is provided".to_string(), + )); + } + + // Get timestamp (use provided or default to now) + let start_timestamp = req.start_timestamp.unwrap_or_else(|| { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) + }); + + // Create epoch with placeholder ID (will compute below) + let mut epoch = Epoch { + id: [0u8; 32], // Placeholder, computed below + name: req.name, + supersedes, + supersession_type, + start_timestamp, + end_timestamp: None, // New epochs are open-ended + }; + + // Compute content-addressed ID by hashing a canonical string representation. + // Using format "{name}:{supersedes_hex}:{timestamp}" to ensure deterministic + // IDs that won't change with struct serialization format changes. + let id_content = format!( + "{}:{}:{}", + epoch.name, + epoch.supersedes.map(::hex::encode).unwrap_or_default(), + epoch.start_timestamp + ); + let id_hash = blake3::hash(id_content.as_bytes()); + epoch.id = *id_hash.as_bytes(); + + Ok(epoch) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::dto::SupersessionTypeDto; + + #[test] + fn test_dto_to_epoch_basic() { + let req = CreateEpochRequest { + name: "GAAP-2024".to_string(), + supersedes: None, + supersession_type: None, + start_timestamp: Some(1704067200), + }; + + let epoch = dto_to_epoch(req).expect("should convert"); + assert_eq!(epoch.name, "GAAP-2024"); + assert!(epoch.supersedes.is_none()); + assert!(epoch.supersession_type.is_none()); + assert_eq!(epoch.start_timestamp, 1704067200); + assert!(epoch.end_timestamp.is_none()); + // ID should be computed (not all zeros) + assert_ne!(epoch.id, [0u8; 32]); + } + + #[test] + fn test_dto_to_epoch_with_supersedes() { + let supersedes_hex = "a".repeat(64); + let req = CreateEpochRequest { + name: "GAAP-2025".to_string(), + supersedes: Some(supersedes_hex), + supersession_type: Some(SupersessionTypeDto::Temporal), + start_timestamp: Some(1735689600), + }; + + let epoch = dto_to_epoch(req).expect("should convert"); + assert_eq!(epoch.name, "GAAP-2025"); + assert!(epoch.supersedes.is_some()); + assert!(epoch.supersession_type.is_some()); + } + + #[test] + fn test_dto_to_epoch_empty_name_fails() { + let req = CreateEpochRequest { + name: "".to_string(), + supersedes: None, + supersession_type: None, + start_timestamp: None, + }; + + let result = dto_to_epoch(req); + assert!(result.is_err()); + let err = result.unwrap_err().to_string(); + assert!(err.contains("cannot be empty")); + } + + #[test] + fn test_dto_to_epoch_whitespace_name_fails() { + let req = CreateEpochRequest { + name: " ".to_string(), + supersedes: None, + supersession_type: None, + start_timestamp: None, + }; + + let result = dto_to_epoch(req); + assert!(result.is_err()); + } + + #[test] + fn test_dto_to_epoch_supersedes_without_type_fails() { + let supersedes_hex = "a".repeat(64); + let req = CreateEpochRequest { + name: "Test".to_string(), + supersedes: Some(supersedes_hex), + supersession_type: None, // Missing! + start_timestamp: None, + }; + + let result = dto_to_epoch(req); + assert!(result.is_err()); + let err = result.unwrap_err().to_string(); + assert!(err.contains("supersession_type is required")); + } + + #[test] + fn test_dto_to_epoch_invalid_supersedes_hex() { + let req = CreateEpochRequest { + name: "Test".to_string(), + supersedes: Some("invalid".to_string()), // Too short + supersession_type: Some(SupersessionTypeDto::Invalidate), + start_timestamp: None, + }; + + let result = dto_to_epoch(req); + assert!(result.is_err()); + } + + #[test] + fn test_dto_to_epoch_defaults_timestamp() { + let req = CreateEpochRequest { + name: "Now".to_string(), + supersedes: None, + supersession_type: None, + start_timestamp: None, // Should default to now + }; + + let epoch = dto_to_epoch(req).expect("should convert"); + // Timestamp should be recent (within last minute) + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + assert!(epoch.start_timestamp <= now); + assert!(epoch.start_timestamp > now - 60); + } + + #[test] + fn test_epoch_id_is_deterministic() { + let req1 = CreateEpochRequest { + name: "Test".to_string(), + supersedes: None, + supersession_type: None, + start_timestamp: Some(1000), + }; + let req2 = CreateEpochRequest { + name: "Test".to_string(), + supersedes: None, + supersession_type: None, + start_timestamp: Some(1000), + }; + + let epoch1 = dto_to_epoch(req1).expect("should convert"); + let epoch2 = dto_to_epoch(req2).expect("should convert"); + + // Same input should produce same ID + assert_eq!(epoch1.id, epoch2.id); + } + + #[test] + fn test_epoch_id_differs_by_name() { + let req1 = CreateEpochRequest { + name: "Epoch-A".to_string(), + supersedes: None, + supersession_type: None, + start_timestamp: Some(1000), + }; + let req2 = CreateEpochRequest { + name: "Epoch-B".to_string(), + supersedes: None, + supersession_type: None, + start_timestamp: Some(1000), + }; + + let epoch1 = dto_to_epoch(req1).expect("should convert"); + let epoch2 = dto_to_epoch(req2).expect("should convert"); + + // Different names should produce different IDs + assert_ne!(epoch1.id, epoch2.id); + } +} diff --git a/crates/stemedb-api/src/handlers/health.rs b/crates/stemedb-api/src/handlers/health.rs new file mode 100644 index 0000000..d0f3070 --- /dev/null +++ b/crates/stemedb-api/src/handlers/health.rs @@ -0,0 +1,38 @@ +//! Handler for health checks. + +use axum::{extract::State, Json}; +use tracing::instrument; + +use crate::{dto::HealthResponse, error::Result, state::AppState}; +use stemedb_storage::KVStore; + +/// Health check endpoint. +/// +/// Returns service status ("healthy"), API version, and the total number of assertions +/// currently stored in the database. Useful for monitoring and load balancer health checks. +#[utoipa::path( + get, + path = "/v1/health", + responses( + (status = 200, description = "Service is healthy", body = HealthResponse), + ), + tag = "health" +)] +#[instrument(skip(state))] +pub async fn health_check(State(state): State) -> Result> { + // Count assertions in the database + let assertions_count = count_assertions(&state).await?; + + Ok(Json(HealthResponse { + status: "healthy".to_string(), + version: env!("CARGO_PKG_VERSION").to_string(), + assertions_count, + })) +} + +/// Count the number of assertions in the database. +async fn count_assertions(state: &AppState) -> Result { + // Scan all assertion keys (H: prefix) + let keys = state.store.scan_prefix(b"H:").await?; + Ok(keys.len() as u64) +} diff --git a/crates/stemedb-api/src/handlers/meter.rs b/crates/stemedb-api/src/handlers/meter.rs new file mode 100644 index 0000000..b228d12 --- /dev/null +++ b/crates/stemedb-api/src/handlers/meter.rs @@ -0,0 +1,142 @@ +//! Handler for quota status endpoint. + +use axum::{ + extract::{Query, State}, + Json, +}; +use serde::{Deserialize, Serialize}; +use stemedb_storage::QuotaStore; +use tracing::instrument; +use utoipa::{IntoParams, ToSchema}; + +use crate::{hex::decode_agent_id, state::AppState, Result}; + +/// Query parameters for quota status. +#[derive(Debug, Clone, Deserialize, IntoParams)] +pub struct QuotaStatusParams { + /// Agent's Ed25519 public key (hex-encoded, 64 chars) + pub agent_id: String, +} + +/// Response containing quota status. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct QuotaStatusResponse { + /// Agent's public key (hex-encoded) + pub agent_id: String, + + /// Remaining tokens in current window + pub remaining: u64, + + /// Total tokens allowed per hour + pub limit: u64, + + /// Unix timestamp when this quota window resets + pub reset_at: u64, + + /// Tokens already consumed in current window + pub used: u64, + + /// Current window start timestamp + pub window_start: u64, +} + +/// Get quota status for an agent. +/// +/// Returns the current quota status including remaining tokens, +/// limit, and reset time for the current hourly window. +#[utoipa::path( + get, + path = "/v1/meter/quota", + params(QuotaStatusParams), + responses( + (status = 200, description = "Quota status retrieved", body = QuotaStatusResponse), + (status = 400, description = "Invalid agent_id format"), + ), + tag = "meter" +)] +#[instrument(skip(state), fields(agent_id = %params.agent_id))] +pub async fn get_quota_status( + State(state): State, + Query(params): Query, +) -> Result> { + // Decode agent ID from hex + let agent_id = decode_agent_id(¶ms.agent_id)?; + + // Get current timestamp + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + + // Query quota status + let quota_result = state.quota_store.get_quota_status(&agent_id, timestamp).await?; + + // Calculate window start (truncate to hour) + let window_start = (timestamp / 3600) * 3600; + let used = quota_result.limit.saturating_sub(quota_result.remaining); + + Ok(Json(QuotaStatusResponse { + agent_id: params.agent_id, + remaining: quota_result.remaining, + limit: quota_result.limit, + reset_at: quota_result.reset_at, + used, + window_start, + })) +} + +/// Set quota limit for an agent (admin operation). +/// +/// This allows setting a custom quota limit for a specific agent. +/// Typically used to grant higher quotas to trusted agents or +/// lower quotas to rate-limited agents. +#[derive(Debug, Clone, Deserialize, ToSchema)] +pub struct SetQuotaLimitRequest { + /// Agent's Ed25519 public key (hex-encoded, 64 chars) + pub agent_id: String, + + /// New quota limit (tokens per hour) + pub limit: u64, +} + +/// Response for set quota limit operation. +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct SetQuotaLimitResponse { + /// Agent's public key (hex-encoded) + pub agent_id: String, + + /// New quota limit that was set + pub limit: u64, + + /// Status message + pub status: String, +} + +/// Set a custom quota limit for an agent. +#[utoipa::path( + post, + path = "/v1/meter/quota/limit", + request_body = SetQuotaLimitRequest, + responses( + (status = 200, description = "Quota limit updated", body = SetQuotaLimitResponse), + (status = 400, description = "Invalid request"), + ), + tag = "meter" +)] +#[instrument(skip(state), fields(agent_id = %req.agent_id, limit = req.limit))] +pub async fn set_quota_limit( + State(state): State, + Json(req): Json, +) -> Result> { + // Decode agent ID from hex + let agent_id = decode_agent_id(&req.agent_id)?; + + // Set the quota limit + state.quota_store.set_quota_limit(&agent_id, req.limit).await?; + + Ok(Json(SetQuotaLimitResponse { + agent_id: req.agent_id, + limit: req.limit, + status: "Quota limit updated".to_string(), + })) +} diff --git a/crates/stemedb-api/src/handlers/mod.rs b/crates/stemedb-api/src/handlers/mod.rs new file mode 100644 index 0000000..569bfdb --- /dev/null +++ b/crates/stemedb-api/src/handlers/mod.rs @@ -0,0 +1,23 @@ +//! HTTP request handlers. + +pub mod assert; +pub mod audit; +pub mod epoch; +pub mod health; +pub mod meter; +pub mod query; +pub mod skeptic; +pub mod supersede; +pub mod trace; +pub mod vote; + +pub use assert::create_assertion; +pub use audit::{get_audit, list_audits}; +pub use epoch::create_epoch; +pub use health::health_check; +pub use meter::{get_quota_status, set_quota_limit}; +pub use query::query_assertions; +pub use skeptic::skeptic_query; +pub use supersede::supersede; +pub use trace::trace; +pub use vote::create_vote; diff --git a/crates/stemedb-api/src/handlers/query.rs b/crates/stemedb-api/src/handlers/query.rs new file mode 100644 index 0000000..6b55e94 --- /dev/null +++ b/crates/stemedb-api/src/handlers/query.rs @@ -0,0 +1,370 @@ +//! Handler for querying assertions. + +use axum::{ + extract::{Query as AxumQuery, State}, + http::HeaderMap, + Json, +}; +use tracing::{debug, instrument}; + +use crate::{ + dto::{AssertionResponse, ErrorResponse, LensDto, QueryParams, QueryResponse}, + error::{ApiError, Result}, + hex as hex_utils, + state::AppState, +}; + +use stemedb_core::types::{ + Assertion, ContributingAssertion, QueryAudit, QueryParams as AuditQueryParams, +}; +use stemedb_lens::{ + AsyncLens, ConfidenceLens, ConsensusLens, EpochAwareLens, Lens, RecencyLens, + TrustAwareAuthorityLens, VoteAwareConsensusLens, +}; +use stemedb_query::Query; +use stemedb_storage::{AuditStore, GenericAuditStore, GenericTrustRankStore, GenericVoteStore}; + +/// Query assertions with optional filters and lens-based conflict resolution. +/// +/// This endpoint builds a query from parameters (subject, predicate, lifecycle, epoch, limit), +/// executes it via the QueryEngine, optionally applies a Lens for conflict resolution, +/// and returns matching assertions. Returns early with empty results if no assertions match. +/// +/// # Lens Resolution +/// When a lens is specified, it resolves conflicts among matching assertions and returns +/// only the winning assertion based on the lens strategy (Recency, Consensus, Authority, etc.) +/// +/// # Audit Trail +/// Every query is logged to the audit trail for incident investigation. +/// Include the `X-Agent-Id` header (hex-encoded, 32 bytes) to associate queries with an agent. +#[utoipa::path( + get, + path = "/v1/query", + responses( + (status = 200, description = "Query successful", body = QueryResponse), + (status = 400, description = "Invalid request", body = ErrorResponse), + (status = 500, description = "Internal server error", body = ErrorResponse) + ), + tag = "query" +)] +#[instrument(skip(state, headers), fields( + subject = ?params.subject, + predicate = ?params.predicate, + lifecycle = ?params.lifecycle, + lens = ?params.lens +))] +pub async fn query_assertions( + State(state): State, + headers: HeaderMap, + AxumQuery(params): AxumQuery, +) -> Result> { + let query_start_timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + + // Extract agent_id from headers if present + let agent_id = extract_agent_id(&headers); + + // Capture params for audit before they're moved + let audit_params = AuditQueryParams { + subject: params.subject.clone(), + predicate: params.predicate.clone(), + lifecycle: params.lifecycle.map(Into::into), + epoch: params.epoch.as_ref().and_then(|h| hex_utils::decode_hash_32(h).ok()), + lens: params.lens.map(|l| format!("{:?}", l)), + }; + + // Build the query + let mut builder = Query::builder(); + + if let Some(ref subject) = params.subject { + builder = builder.subject(subject.clone()); + } + + if let Some(ref predicate) = params.predicate { + builder = builder.predicate(predicate.clone()); + } + + if let Some(lifecycle_dto) = params.lifecycle { + builder = builder.lifecycle(lifecycle_dto.into()); + } + + if let Some(ref epoch_hex) = params.epoch { + let epoch = hex_utils::decode_hash_32(epoch_hex)?; + builder = builder.epoch(epoch); + } + + builder = builder.limit(params.limit); + + if let Some(max_stale) = params.max_stale { + builder = builder.max_stale(max_stale); + } + + if let Some(ref visual_near) = params.visual_near { + // Clamp threshold to valid range (0-64, max hamming distance for 8-byte hash) + let threshold = params.visual_threshold.unwrap_or(8).min(64); + builder = builder.visual_near(visual_near.clone(), threshold); + } + + let query = builder.build(); + + // Execute the query + let query_engine = state.query_engine(); + let result = query_engine.execute(&query).await?; + + // Return early if no assertions found (before lens application) + if result.assertions.is_empty() { + // Log empty query audit + log_query_audit(&state, agent_id, query_start_timestamp, &audit_params, None, 0.0, vec![]) + .await; + + return Ok(Json(QueryResponse { + assertions: vec![], + total_count: 0, + has_more: result.has_more, + })); + } + + // Capture contributing assertions before lens resolution + let candidates: Vec<_> = result.assertions.clone(); + + // Apply lens if specified + let (assertions, resolution_confidence) = if let Some(lens_dto) = params.lens { + let (winner, confidence) = + apply_lens_with_confidence(lens_dto, result.assertions, state.store.clone()).await?; + (winner, confidence) + } else { + // No lens = return all candidates with full confidence + (result.assertions, 1.0) + }; + + // Compute contributing assertions for audit + let contributing = build_contributing_assertions(&candidates, &assertions)?; + + // Compute result hash (hash of the winning assertion, if any) + let result_hash = if let Some(winner) = assertions.first() { + let serialized = stemedb_core::serde::serialize(winner) + .map_err(|e| ApiError::Serialization(format!("Failed to serialize winner: {}", e)))?; + Some(*blake3::hash(&serialized).as_bytes()) + } else { + None + }; + + // Log query audit (fire and forget - don't fail the query if audit fails) + log_query_audit( + &state, + agent_id, + query_start_timestamp, + &audit_params, + result_hash, + resolution_confidence, + contributing, + ) + .await; + + // Convert to response DTOs - collect as Result to propagate errors + let assertion_responses: Vec = + assertions.into_iter().map(assertion_to_dto).collect::>>()?; + + let total_count = assertion_responses.len(); + + Ok(Json(QueryResponse { + assertions: assertion_responses, + total_count, + has_more: result.has_more, + })) +} + +/// Extract agent_id from X-Agent-Id header if present and valid. +fn extract_agent_id(headers: &HeaderMap) -> Option<[u8; 32]> { + headers + .get("X-Agent-Id") + .and_then(|v| v.to_str().ok()) + .and_then(|s| hex_utils::decode_hash_32(s).ok()) +} + +/// Log a query audit record. Errors are logged but don't fail the query. +async fn log_query_audit( + state: &AppState, + agent_id: Option<[u8; 32]>, + timestamp: u64, + params: &AuditQueryParams, + result_hash: Option<[u8; 32]>, + result_confidence: f32, + contributing_assertions: Vec, +) { + // Generate query_id from content hash of params + timestamp + let query_id = generate_query_id(params, timestamp); + + let audit = QueryAudit { + query_id, + agent_id, + timestamp, + params: params.clone(), + result_hash, + result_confidence, + contributing_assertions, + }; + + let audit_store = GenericAuditStore::new(state.store.clone()); + if let Err(e) = audit_store.put_audit(&audit).await { + // Log but don't fail the query + debug!(error = %e, query_id = %hex::encode(query_id), "Failed to log query audit"); + } +} + +/// Generate a deterministic query_id from params and timestamp. +/// +/// The query_id is a BLAKE3 hash of the canonical string representation +/// of the query parameters plus timestamp. This ensures: +/// - Deterministic: same params + timestamp = same ID +/// - Collision-resistant: BLAKE3 provides cryptographic security +fn generate_query_id(params: &AuditQueryParams, timestamp: u64) -> [u8; 32] { + // Build a canonical string representation for hashing + let mut content = String::new(); + if let Some(ref s) = params.subject { + content.push_str(s); + } + content.push(':'); + if let Some(ref p) = params.predicate { + content.push_str(p); + } + content.push(':'); + if let Some(l) = params.lifecycle { + content.push_str(&format!("{:?}", l)); + } + content.push(':'); + if let Some(ref e) = params.epoch { + content.push_str(&hex::encode(e)); + } + content.push(':'); + if let Some(ref l) = params.lens { + content.push_str(l); + } + content.push(':'); + content.push_str(×tamp.to_string()); + + // BLAKE3 is collision-resistant; no additional entropy needed + *blake3::hash(content.as_bytes()).as_bytes() +} + +/// Build ContributingAssertion records from candidates and winners. +/// +/// Pre-computes winner hashes once for O(n) total instead of O(n*w). +fn build_contributing_assertions( + candidates: &[Assertion], + winners: &[Assertion], +) -> Result> { + use std::collections::HashSet; + + // Pre-compute winner hashes once: O(w) where w = number of winners + let winner_hashes: HashSet<[u8; 32]> = winners + .iter() + .filter_map(|w| { + stemedb_core::serde::serialize(w).ok().map(|s| *blake3::hash(&s).as_bytes()) + }) + .collect(); + + let mut contributing = Vec::with_capacity(candidates.len()); + + for candidate in candidates { + let serialized = stemedb_core::serde::serialize(candidate).map_err(|e| { + ApiError::Serialization(format!("Failed to serialize candidate: {}", e)) + })?; + let assertion_hash = *blake3::hash(&serialized).as_bytes(); + + // O(1) lookup instead of O(w) serializations per candidate + let is_winner = winner_hashes.contains(&assertion_hash); + + contributing.push(ContributingAssertion { + assertion_hash, + weight: if is_winner { 1.0 } else { 0.0 }, + source_hash: candidate.source_hash, + lifecycle: candidate.lifecycle, + }); + } + + Ok(contributing) +} + +/// Apply the specified lens to resolve conflicts and return confidence. +async fn apply_lens_with_confidence( + lens_dto: LensDto, + assertions: Vec, + store: std::sync::Arc, +) -> Result<(Vec, f32)> { + let assertion_count = assertions.len(); + + let resolution = match lens_dto { + LensDto::Recency => { + let lens = RecencyLens; + lens.resolve(&assertions) + } + LensDto::Consensus => { + let lens = ConsensusLens; + lens.resolve(&assertions) + } + LensDto::Confidence => { + let lens = ConfidenceLens; + lens.resolve(&assertions) + } + LensDto::VoteAwareConsensus => { + let vote_store = std::sync::Arc::new(GenericVoteStore::new(store.clone())); + let lens = VoteAwareConsensusLens::new(vote_store); + lens.resolve_async(&assertions).await + } + // Authority and TrustAwareAuthority both route to TrustAwareAuthorityLens. + // Authority is the user-friendly name; TrustAwareAuthority is the explicit name. + LensDto::Authority | LensDto::TrustAwareAuthority => { + let trust_store = std::sync::Arc::new(GenericTrustRankStore::new(store)); + let lens = TrustAwareAuthorityLens::new(trust_store); + lens.resolve_async(&assertions).await + } + LensDto::EpochAware => { + // EpochAwareLens filters assertions from superseded epochs before + // delegating to RecencyLens for final resolution. + let lens = EpochAwareLens::with_recency(store); + lens.resolve_async(&assertions).await + } + }; + + let confidence = resolution.resolution_confidence; + + let winner = resolution.winner.ok_or_else(|| { + ApiError::InvalidRequest(format!( + "Lens {:?} failed to resolve a winner among {} assertions", + lens_dto, assertion_count + )) + })?; + + Ok((vec![winner], confidence)) +} + +/// Convert an internal Assertion to an AssertionResponse DTO. +/// +/// Returns an error if serialization fails (should never happen for assertions +/// that came from the database, as they were already serialized once). +fn assertion_to_dto(assertion: Assertion) -> Result { + // Compute hash - propagate errors instead of silent fallback + let serialized = stemedb_core::serde::serialize(&assertion) + .map_err(|e| ApiError::Serialization(format!("Failed to serialize assertion: {}", e)))?; + let hash = blake3::hash(&serialized); + + Ok(AssertionResponse { + hash: hash.to_hex().to_string(), + subject: assertion.subject, + predicate: assertion.predicate, + object: assertion.object.into(), + parent_hash: assertion.parent_hash.map(hex::encode), + source_hash: hex::encode(assertion.source_hash), + source_class: assertion.source_class.into(), + visual_hash: assertion.visual_hash.map(hex::encode), + epoch: assertion.epoch.map(hex::encode), + lifecycle: assertion.lifecycle.into(), + signatures: assertion.signatures.into_iter().map(Into::into).collect(), + confidence: assertion.confidence, + timestamp: assertion.timestamp, + vector: assertion.vector, + }) +} diff --git a/crates/stemedb-api/src/handlers/skeptic.rs b/crates/stemedb-api/src/handlers/skeptic.rs new file mode 100644 index 0000000..a5ae581 --- /dev/null +++ b/crates/stemedb-api/src/handlers/skeptic.rs @@ -0,0 +1,84 @@ +//! Handler for skeptic (conflict analysis) queries. + +use axum::{ + extract::{Query as AxumQuery, State}, + Json, +}; +use tracing::instrument; + +use crate::{ + dto::{ErrorResponse, SkepticQueryParams, SkepticResponse}, + error::Result, + state::AppState, +}; + +use stemedb_query::SkepticResolver; +use stemedb_storage::{GenericTrustRankStore, GenericVoteStore}; + +/// Query for conflict analysis using SkepticLens. +/// +/// This endpoint provides "Trust but Verify" analysis, showing all competing +/// claims for a subject+predicate instead of picking a single winner. +/// +/// # Response +/// +/// Returns a `SkepticResponse` with: +/// - `status`: Unanimous, Agreed, or Contested +/// - `conflict_score`: 0.0 (unanimous) to 1.0 (chaos) +/// - `claims`: All distinct claims ranked by support +/// +/// # Example +/// +/// ```ignore +/// GET /v1/skeptic?subject=Semaglutide&predicate=muscle_effect +/// +/// { +/// "status": "Contested", +/// "conflict_score": 0.72, +/// "claims": [ +/// { "value": {"type": "Text", "value": "Significant loss"}, "weight_share": 0.45 }, +/// { "value": {"type": "Text", "value": "Minimal loss"}, "weight_share": 0.35 } +/// ] +/// } +/// ``` +#[utoipa::path( + get, + path = "/v1/skeptic", + params(SkepticQueryParams), + responses( + (status = 200, description = "Conflict analysis successful", body = SkepticResponse), + (status = 404, description = "No assertions found for subject+predicate", body = ErrorResponse), + (status = 400, description = "Invalid request", body = ErrorResponse), + (status = 500, description = "Internal server error", body = ErrorResponse) + ), + tag = "query" +)] +#[instrument(skip(state), fields(subject = %params.subject, predicate = %params.predicate))] +pub async fn skeptic_query( + State(state): State, + AxumQuery(params): AxumQuery, +) -> Result> { + // Create the resolver with vote and trust stores + let vote_store = std::sync::Arc::new(GenericVoteStore::new((*state.store).clone())); + let trust_store = std::sync::Arc::new(GenericTrustRankStore::new((*state.store).clone())); + let resolver = SkepticResolver::new(state.store.clone(), vote_store, trust_store); + + // Execute the skeptic resolution + let view = resolver.resolve(¶ms.subject, ¶ms.predicate).await?; + + // Return 404 if no assertions found + let view = view.ok_or_else(|| { + crate::error::ApiError::NotFound(format!( + "No assertions found for subject '{}' and predicate '{}'", + params.subject, params.predicate + )) + })?; + + Ok(Json(view.into())) +} + +#[cfg(test)] +mod tests { + // Integration tests would go here + // For now, the unit tests in stemedb-query cover the core functionality +} diff --git a/crates/stemedb-api/src/handlers/supersede.rs b/crates/stemedb-api/src/handlers/supersede.rs new file mode 100644 index 0000000..1f7aa75 --- /dev/null +++ b/crates/stemedb-api/src/handlers/supersede.rs @@ -0,0 +1,173 @@ +//! Handler for assertion supersession endpoint. +//! +//! The supersede endpoint enables error correction without violating append-only +//! semantics. Instead of mutating an assertion, we create a supersession record +//! that points from the old (target) to the new (replacement) assertion. +//! +//! # Use Case: 3am Incident Investigation +//! +//! 1. SRE finds agent deployed bad config +//! 2. Trace shows agent queried assertion X with hash `abc123` +//! 3. Supervisor creates supersession: `abc123` → `new_hash` (Invalidate) +//! 4. Future queries skip `abc123` automatically +//! 5. Audit trail preserved: "Who fixed it? When? Why?" + +use axum::{extract::State, http::StatusCode, Json}; +use tracing::instrument; + +use crate::{ + dto::{SupersedeRequest, SupersedeResponse}, + error::{ApiError, Result}, + hex, + state::AppState, +}; + +use stemedb_core::types::{Supersession, SupersessionType}; +use stemedb_storage::{GenericSupersessionStore, SupersessionStore}; + +/// Create a supersession record for error correction. +/// +/// This endpoint accepts a supersession request, validates the fields, +/// and stores the supersession record. Future queries will automatically +/// filter out superseded assertions based on type. +/// +/// # Request Body +/// +/// - `target_hash`: Hash of the assertion being superseded (hex-encoded) +/// - `supersession_type`: How the target is being superseded (Invalidate, Temporal, etc.) +/// - `reason`: Human-readable explanation for audit trail +/// - `new_hash`: Hash of replacement assertion (optional) +/// - `agent_id`: Public key of agent creating the supersession +/// - `signature`: Signature over the supersession content +/// +/// # Example +/// +/// ```text +/// POST /v1/supersede +/// { +/// "target_hash": "abc123...", +/// "supersession_type": "Invalidate", +/// "reason": "Proposal treated as approved. See incident INC-2024-001", +/// "new_hash": "def456...", +/// "agent_id": "deadbeef...", +/// "signature": "..." +/// } +/// ``` +#[utoipa::path( + post, + path = "/v1/supersede", + request_body = SupersedeRequest, + responses( + (status = 201, description = "Supersession recorded successfully", body = SupersedeResponse), + (status = 400, description = "Invalid request parameters", body = crate::dto::ErrorResponse), + (status = 404, description = "Target assertion not found", body = crate::dto::ErrorResponse), + (status = 409, description = "Assertion already superseded", body = crate::dto::ErrorResponse), + (status = 500, description = "Internal server error", body = crate::dto::ErrorResponse) + ), + tag = "supersession" +)] +#[instrument(skip(state), fields( + target_hash = %req.target_hash, + supersession_type = ?req.supersession_type, + agent_id = %req.agent_id +))] +pub async fn supersede( + State(state): State, + Json(req): Json, +) -> Result<(StatusCode, Json)> { + // Decode and validate hex fields + let target_hash = hex::decode_hash_32(&req.target_hash)?; + let agent_id = hex::decode_agent_id(&req.agent_id)?; + let signature = hex::decode_signature(&req.signature)?; + + let new_hash = req.new_hash.map(|h| hex::decode_hash_32(&h)).transpose()?; + + // Validate reason is not empty + if req.reason.trim().is_empty() { + return Err(ApiError::InvalidRequest( + "Reason is required for supersession audit trail".to_string(), + )); + } + + // Get current timestamp + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|e| ApiError::InvalidRequest(format!("System clock error: {}", e)))? + .as_secs(); + + // Create supersession store + let supersession_store = GenericSupersessionStore::new(state.store.clone()); + + // Check if already superseded + if supersession_store + .is_superseded(&target_hash) + .await + .map_err(|e| ApiError::Internal(format!("Failed to check supersession status: {}", e)))? + { + return Err(ApiError::Conflict(format!( + "Assertion {} is already superseded", + req.target_hash + ))); + } + + // Convert DTO type to core type + let supersession_type: SupersessionType = req.supersession_type.into(); + + // Create supersession record + let supersession = Supersession { + target_hash, + supersession_type, + reason: req.reason.clone(), + new_hash, + timestamp, + agent_id, + signature, + }; + + // Store the supersession + supersession_store + .put_supersession(&supersession) + .await + .map_err(|e| ApiError::Internal(format!("Failed to store supersession: {}", e)))?; + + // Build response + let response = SupersedeResponse { + status: "superseded".to_string(), + target_hash: req.target_hash, + supersession_type: req.supersession_type, + timestamp, + }; + + Ok((StatusCode::CREATED, Json(response))) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::dto::SupersessionTypeDto; + + #[test] + fn test_supersession_type_conversion() { + // Test all DTO types convert correctly + assert_eq!( + SupersessionType::from(SupersessionTypeDto::Invalidate), + SupersessionType::Invalidate + ); + assert_eq!( + SupersessionType::from(SupersessionTypeDto::Temporal), + SupersessionType::Temporal + ); + assert_eq!( + SupersessionType::from(SupersessionTypeDto::Refinement), + SupersessionType::Refinement + ); + assert_eq!( + SupersessionType::from(SupersessionTypeDto::RequiresReview), + SupersessionType::RequiresReview + ); + assert_eq!( + SupersessionType::from(SupersessionTypeDto::Additive), + SupersessionType::Additive + ); + } +} diff --git a/crates/stemedb-api/src/handlers/trace.rs b/crates/stemedb-api/src/handlers/trace.rs new file mode 100644 index 0000000..59148b5 --- /dev/null +++ b/crates/stemedb-api/src/handlers/trace.rs @@ -0,0 +1,248 @@ +//! Handler for agent decision tracing endpoint. +//! +//! The trace endpoint enables debugging agent decision-making by retrieving +//! query audits filtered by agent ID, time range, and optional subject pattern. + +use axum::{ + extract::{Query as AxumQuery, State}, + Json, +}; +use tracing::instrument; + +use crate::{ + dto::{QueryAuditResponse, TraceParams, TraceResponse}, + error::{ApiError, Result}, + hex as hex_utils, + state::AppState, +}; + +use stemedb_storage::{AuditStore, GenericAuditStore}; + +/// Query the audit log for agent decision tracing. +/// +/// Returns query audits for a specific agent within a time range, optionally +/// filtered by subject pattern. This enables "Why did the agent think that?" +/// debugging for incident investigation. +/// +/// # Query Parameters +/// +/// - `agent_id` (required): Agent public key (hex-encoded, 32 bytes) +/// - `from` (required): Start of time range (Unix timestamp) +/// - `to` (optional): End of time range (Unix timestamp, defaults to now) +/// - `subject` (optional): Filter by subject pattern (e.g., "Tesla*", "auth/*", "*" for all) +/// - `limit` (optional): Maximum number of results (default: 100, max: 1000) +/// +/// # Example +/// +/// ```text +/// GET /v1/trace?agent_id=deadbeef...&from=1704067200&to=1704153600&subject=Tesla*&limit=50 +/// ``` +#[utoipa::path( + get, + path = "/v1/trace", + params(TraceParams), + responses( + (status = 200, description = "Matching query audits for the agent", body = TraceResponse), + (status = 400, description = "Invalid request parameters", body = crate::dto::ErrorResponse), + (status = 500, description = "Internal server error", body = crate::dto::ErrorResponse) + ), + tag = "audit" +)] +#[instrument(skip(state), fields( + agent_id = %params.agent_id, + from = %params.from, + to = ?params.to, + subject = ?params.subject, + limit = params.limit +))] +pub async fn trace( + State(state): State, + AxumQuery(params): AxumQuery, +) -> Result> { + // Validate and parse agent_id (required) + if params.agent_id.is_empty() { + return Err(ApiError::InvalidRequest("agent_id is required for trace queries".to_string())); + } + let agent_id = hex_utils::decode_agent_id(¶ms.agent_id)?; + + // Parse from timestamp (required) + if params.from.is_empty() { + return Err(ApiError::InvalidRequest( + "from timestamp is required for trace queries".to_string(), + )); + } + let from_timestamp = parse_timestamp(¶ms.from)?; + + // Parse to timestamp (defaults to now) + let to_timestamp = if let Some(ref to_str) = params.to { + parse_timestamp(to_str)? + } else { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|e| ApiError::InvalidRequest(format!("System clock error: {}", e)))? + .as_secs() + }; + + // Validate time range + if from_timestamp > to_timestamp { + return Err(ApiError::InvalidRequest( + "from timestamp must be before to timestamp".to_string(), + )); + } + + // Query the audit store + let audit_store = GenericAuditStore::new(state.store.clone()); + let audits = audit_store + .get_audits_for_agent(&agent_id, from_timestamp, Some(to_timestamp), params.limit) + .await?; + + // Apply subject pattern filter if specified + let filtered_audits = if let Some(ref pattern) = params.subject { + filter_by_subject_pattern(audits, pattern) + } else { + audits + }; + + let total_count = filtered_audits.len(); + + // Convert to response DTOs + let audit_responses: Vec = + filtered_audits.into_iter().map(QueryAuditResponse::from).collect(); + + Ok(Json(TraceResponse { + audits: audit_responses, + total_count, + agent_id: params.agent_id, + from_timestamp, + to_timestamp, + })) +} + +/// Parse a timestamp string (Unix timestamp). +/// +/// Supports: +/// - Unix timestamps: "1704067200" +/// +/// Note: ISO8601 support planned for future release. +fn parse_timestamp(s: &str) -> Result { + s.parse::().map_err(|_| { + ApiError::InvalidRequest(format!( + "Invalid timestamp format: '{}'. Expected Unix timestamp (e.g., 1704067200)", + s + )) + }) +} + +/// Filter query audits by subject pattern. +/// +/// Supports simple glob patterns: +/// - Exact match: "Tesla" +/// - Prefix match: "Tesla*" +/// - Suffix match: "*Inc" +/// - Contains: "*Tesla*" +/// - Wildcard: "*" matches everything including queries without subject filter +fn filter_by_subject_pattern( + audits: Vec, + pattern: &str, +) -> Vec { + // Wildcard matches everything, including queries without subject filter + if pattern == "*" { + return audits; + } + + audits + .into_iter() + .filter(|audit| { + audit.params.subject.as_ref().is_some_and(|subject| matches_pattern(subject, pattern)) + }) + .collect() +} + +/// Check if a subject matches a glob pattern. +/// +/// Supports: +/// - Exact: "Tesla" matches "Tesla" +/// - Prefix: "Tesla*" matches "Tesla_Inc" +/// - Suffix: "*Inc" matches "Tesla_Inc" +/// - Contains: "*Tesla*" matches "My_Tesla_Stock" +fn matches_pattern(subject: &str, pattern: &str) -> bool { + if pattern == "*" { + return true; + } + + let starts_with_wildcard = pattern.starts_with('*'); + let ends_with_wildcard = pattern.ends_with('*'); + + match (starts_with_wildcard, ends_with_wildcard) { + (false, false) => { + // Exact match + subject == pattern + } + (false, true) => { + // Prefix match: "Tesla*" + let prefix = &pattern[..pattern.len() - 1]; + subject.starts_with(prefix) + } + (true, false) => { + // Suffix match: "*Inc" + let suffix = &pattern[1..]; + subject.ends_with(suffix) + } + (true, true) => { + // Contains match: "*Tesla*" + let substring = &pattern[1..pattern.len() - 1]; + subject.contains(substring) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_matches_pattern_exact() { + assert!(matches_pattern("Tesla", "Tesla")); + assert!(!matches_pattern("Tesla_Inc", "Tesla")); + } + + #[test] + fn test_matches_pattern_prefix() { + assert!(matches_pattern("Tesla_Inc", "Tesla*")); + assert!(matches_pattern("Tesla", "Tesla*")); + assert!(!matches_pattern("My_Tesla", "Tesla*")); + } + + #[test] + fn test_matches_pattern_suffix() { + assert!(matches_pattern("Tesla_Inc", "*Inc")); + assert!(matches_pattern("Inc", "*Inc")); + assert!(!matches_pattern("Inc_Tesla", "*Inc")); + } + + #[test] + fn test_matches_pattern_contains() { + assert!(matches_pattern("My_Tesla_Stock", "*Tesla*")); + assert!(matches_pattern("Tesla", "*Tesla*")); + assert!(matches_pattern("Tesla_Inc", "*Tesla*")); + assert!(!matches_pattern("MyStock", "*Tesla*")); + } + + #[test] + fn test_matches_pattern_wildcard() { + assert!(matches_pattern("anything", "*")); + assert!(matches_pattern("", "*")); + } + + #[test] + fn test_parse_timestamp_unix() { + assert_eq!(parse_timestamp("1704067200").unwrap(), 1704067200); + assert_eq!(parse_timestamp("0").unwrap(), 0); + } + + #[test] + fn test_parse_timestamp_invalid() { + assert!(parse_timestamp("not-a-number").is_err()); + assert!(parse_timestamp("").is_err()); + } +} diff --git a/crates/stemedb-api/src/handlers/vote.rs b/crates/stemedb-api/src/handlers/vote.rs new file mode 100644 index 0000000..4c9daf8 --- /dev/null +++ b/crates/stemedb-api/src/handlers/vote.rs @@ -0,0 +1,84 @@ +//! Handler for creating votes. + +use axum::{extract::State, http::StatusCode, Json}; +use tracing::instrument; + +use crate::{ + dto::{CreateResponse, CreateVoteRequest, ErrorResponse}, + error::{ApiError, Result}, + hex, + state::AppState, +}; + +use stemedb_core::types::Vote; +use stemedb_ingest::worker::serialize_vote; + +/// Create a new vote on an assertion. +/// +/// This endpoint accepts a vote DTO, validates weight bounds (0.0-1.0), +/// converts hex-encoded fields to binary, serializes the vote to WAL format, +/// and appends it to the journal. Returns the content-addressed BLAKE3 hash. +/// +/// # Validation +/// - Weight must be between 0.0 and 1.0 +/// - All hex fields must have correct lengths (32 bytes for agent_id/assertion_hash, 64 bytes for signature) +#[utoipa::path( + post, + path = "/v1/vote", + request_body = CreateVoteRequest, + responses( + (status = 201, description = "Vote created successfully", body = CreateResponse), + (status = 400, description = "Invalid request", body = ErrorResponse), + (status = 500, description = "Internal server error", body = ErrorResponse) + ), + tag = "votes" +)] +#[instrument(skip(state), fields(assertion_hash = %req.assertion_hash, weight = %req.weight))] +pub async fn create_vote( + State(state): State, + Json(req): Json, +) -> Result<(StatusCode, Json)> { + // Convert DTO to internal Vote type + let vote = dto_to_vote(req)?; + + // Serialize to WAL format (includes record type header) + let payload = serialize_vote(&vote) + .map_err(|e| ApiError::Serialization(format!("Failed to serialize vote: {}", e)))?; + + // Compute the content-addressed hash + let serialized_vote = stemedb_core::serde::serialize(&vote) + .map_err(|e| ApiError::Serialization(format!("Failed to serialize for hash: {}", e)))?; + let hash = blake3::hash(&serialized_vote); + + // Append to WAL + let mut journal = state.journal.lock().await; + journal.append(payload)?; + + let response = + CreateResponse { hash: hash.to_hex().to_string(), status: "created".to_string() }; + + Ok((StatusCode::CREATED, Json(response))) +} + +/// Convert CreateVoteRequest DTO to internal Vote type. +fn dto_to_vote(req: CreateVoteRequest) -> Result { + // Validate weight bounds (0.0 to 1.0) + if req.weight < 0.0 || req.weight > 1.0 { + return Err(ApiError::InvalidRequest(format!( + "Weight must be between 0.0 and 1.0, got {}", + req.weight + ))); + } + + let assertion_hash = hex::decode_hash_32(&req.assertion_hash)?; + let agent_id = hex::decode_hash_32(&req.agent_id)?; + let signature = hex::decode_signature(&req.signature)?; + + // Get current timestamp + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|e| ApiError::Serialization(format!("Failed to get timestamp: {}", e)))? + .as_secs(); + + Ok(Vote { assertion_hash, agent_id, weight: req.weight, signature, timestamp }) +} diff --git a/crates/stemedb-api/src/hex.rs b/crates/stemedb-api/src/hex.rs new file mode 100644 index 0000000..6f8eee4 --- /dev/null +++ b/crates/stemedb-api/src/hex.rs @@ -0,0 +1,160 @@ +//! Hex decoding utilities with validation. +//! +//! This module provides validated hex decoding functions that check string length +//! BEFORE attempting to decode, providing clear error messages. + +use crate::error::{ApiError, Result}; + +/// Decode a 32-byte hash from hex string. +/// +/// Validates that the hex string is exactly 64 characters (32 bytes) before decoding. +pub fn decode_hash_32(hex: &str) -> Result<[u8; 32]> { + const EXPECTED_BYTES: usize = 32; + const EXPECTED_HEX_CHARS: usize = EXPECTED_BYTES * 2; + + // Check length FIRST before attempting decode + if hex.len() != EXPECTED_HEX_CHARS { + return Err(ApiError::InvalidRequest(format!( + "Expected {} hex characters ({} bytes), got {}", + EXPECTED_HEX_CHARS, + EXPECTED_BYTES, + hex.len() + ))); + } + + let bytes = hex::decode(hex).map_err(|e| ApiError::InvalidHex(e.to_string()))?; + + if bytes.len() != EXPECTED_BYTES { + return Err(ApiError::InvalidHashLength { expected: EXPECTED_BYTES, actual: bytes.len() }); + } + + let mut hash = [0u8; 32]; + hash.copy_from_slice(&bytes); + Ok(hash) +} + +/// Decode an 8-byte hash from hex string. +/// +/// Validates that the hex string is exactly 16 characters (8 bytes) before decoding. +pub fn decode_hash_8(hex: &str) -> Result<[u8; 8]> { + const EXPECTED_BYTES: usize = 8; + const EXPECTED_HEX_CHARS: usize = EXPECTED_BYTES * 2; + + // Check length FIRST before attempting decode + if hex.len() != EXPECTED_HEX_CHARS { + return Err(ApiError::InvalidRequest(format!( + "Expected {} hex characters ({} bytes), got {}", + EXPECTED_HEX_CHARS, + EXPECTED_BYTES, + hex.len() + ))); + } + + let bytes = hex::decode(hex).map_err(|e| ApiError::InvalidHex(e.to_string()))?; + + if bytes.len() != EXPECTED_BYTES { + return Err(ApiError::InvalidHashLength { expected: EXPECTED_BYTES, actual: bytes.len() }); + } + + let mut hash = [0u8; 8]; + hash.copy_from_slice(&bytes); + Ok(hash) +} + +/// Decode a 32-byte agent ID from hex string. +/// +/// Agent IDs are Ed25519 public keys (32 bytes). +/// Validates that the hex string is exactly 64 characters before decoding. +pub fn decode_agent_id(hex: &str) -> Result<[u8; 32]> { + decode_hash_32(hex) +} + +/// Decode a 64-byte signature from hex string. +/// +/// Validates that the hex string is exactly 128 characters (64 bytes) before decoding. +pub fn decode_signature(hex: &str) -> Result<[u8; 64]> { + const EXPECTED_BYTES: usize = 64; + const EXPECTED_HEX_CHARS: usize = EXPECTED_BYTES * 2; + + // Check length FIRST before attempting decode + if hex.len() != EXPECTED_HEX_CHARS { + return Err(ApiError::InvalidRequest(format!( + "Expected {} hex characters ({} bytes), got {}", + EXPECTED_HEX_CHARS, + EXPECTED_BYTES, + hex.len() + ))); + } + + let bytes = hex::decode(hex).map_err(|e| ApiError::InvalidHex(e.to_string()))?; + + if bytes.len() != EXPECTED_BYTES { + return Err(ApiError::InvalidHashLength { expected: EXPECTED_BYTES, actual: bytes.len() }); + } + + let mut sig = [0u8; 64]; + sig.copy_from_slice(&bytes); + Ok(sig) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_decode_hash_32_valid() { + let valid_hex = "a".repeat(64); + let result = decode_hash_32(&valid_hex); + assert!(result.is_ok()); + } + + #[test] + fn test_decode_hash_32_wrong_length() { + let short_hex = "abc"; + let result = decode_hash_32(short_hex); + assert!(result.is_err()); + let err = result.unwrap_err().to_string(); + assert!(err.contains("Expected 64 hex characters")); + assert!(err.contains("got 3")); + } + + #[test] + fn test_decode_hash_8_valid() { + let valid_hex = "a".repeat(16); + let result = decode_hash_8(&valid_hex); + assert!(result.is_ok()); + } + + #[test] + fn test_decode_hash_8_wrong_length() { + let short_hex = "abc"; + let result = decode_hash_8(short_hex); + assert!(result.is_err()); + let err = result.unwrap_err().to_string(); + assert!(err.contains("Expected 16 hex characters")); + } + + #[test] + fn test_decode_signature_valid() { + let valid_hex = "b".repeat(128); + let result = decode_signature(&valid_hex); + assert!(result.is_ok()); + } + + #[test] + fn test_decode_signature_wrong_length() { + let short_hex = "xyz"; + let result = decode_signature(short_hex); + assert!(result.is_err()); + let err = result.unwrap_err().to_string(); + assert!(err.contains("Expected 128 hex characters")); + assert!(err.contains("got 3")); + } + + #[test] + fn test_decode_hash_32_invalid_hex() { + let invalid_hex = "z".repeat(64); + let result = decode_hash_32(&invalid_hex); + assert!(result.is_err()); + } +} diff --git a/crates/stemedb-api/src/lib.rs b/crates/stemedb-api/src/lib.rs new file mode 100644 index 0000000..f0c83d5 --- /dev/null +++ b/crates/stemedb-api/src/lib.rs @@ -0,0 +1,207 @@ +//! HTTP API for Episteme (StemeDB). +//! +//! This crate provides a RESTful HTTP API using axum and utoipa for OpenAPI documentation. +//! +//! # Architecture +//! +//! The API follows the standard axum pattern: +//! - **DTOs** (`dto.rs`) - JSON request/response types with hex-encoded binary data +//! - **Handlers** (`handlers/`) - Thin HTTP handlers that delegate to underlying engines +//! - **State** (`state.rs`) - Shared application state (Journal, Store, QueryEngine) +//! - **Router** (`router()`) - axum router with OpenAPI support via utoipa-axum +//! +//! # Write Path +//! +//! POST /v1/assert → DTO → Assertion → serialize → append to WAL → return hash +//! +//! # Read Path +//! +//! GET /v1/query → QueryParams → Query → QueryEngine → Lens (optional) → DTOs +//! +//! # Example +//! +//! ```ignore +//! use stemedb_api::{create_router, AppState}; +//! +//! let state = AppState::new(journal, store); +//! let app = create_router(state); +//! +//! axum::Server::bind(&addr).serve(app.into_make_service()).await?; +//! ``` + +pub mod dto; +pub mod error; +pub mod handlers; +pub mod hex; +pub mod middleware; +pub mod state; + +use axum::{ + routing::{get, post}, + Router, +}; +use tower_http::trace::TraceLayer; +use utoipa::OpenApi; +use utoipa_swagger_ui::SwaggerUi; + +pub use error::{ApiError, Result}; +pub use middleware::{MeterLayer, MeterService}; +pub use state::AppState; + +// Re-export the path items for OpenAPI +use handlers::{ + assert::__path_create_assertion, + audit::{__path_get_audit, __path_list_audits}, + epoch::__path_create_epoch, + health::__path_health_check, + meter::{__path_get_quota_status, __path_set_quota_limit}, + query::__path_query_assertions, + skeptic::__path_skeptic_query, + supersede::__path_supersede, + trace::__path_trace, + vote::__path_create_vote, +}; + +/// OpenAPI documentation schema. +#[derive(OpenApi)] +#[openapi( + paths( + create_assertion, + create_epoch, + create_vote, + query_assertions, + skeptic_query, + health_check, + list_audits, + get_audit, + trace, + supersede, + get_quota_status, + set_quota_limit, + ), + components( + schemas( + dto::CreateAssertionRequest, + dto::CreateVoteRequest, + dto::CreateEpochRequest, + dto::QueryParams, + dto::AssertionResponse, + dto::QueryResponse, + dto::CreateResponse, + dto::ErrorResponse, + dto::HealthResponse, + dto::ObjectValueDto, + dto::LifecycleDto, + dto::SupersessionTypeDto, + dto::LensDto, + dto::SignatureDto, + dto::AuditQueryParams, + dto::QueryAuditResponse, + dto::QueryAuditListResponse, + dto::QueryParamsAuditDto, + dto::ContributingAssertionDto, + dto::TraceParams, + dto::TraceResponse, + dto::SupersedeRequest, + dto::SupersedeResponse, + dto::SkepticQueryParams, + dto::SkepticResponse, + dto::ResolutionStatusDto, + dto::ClaimSummaryDto, + dto::SourceSummaryDto, + dto::AgentSummaryDto, + handlers::meter::QuotaStatusResponse, + handlers::meter::SetQuotaLimitRequest, + handlers::meter::SetQuotaLimitResponse, + ) + ), + tags( + (name = "assertions", description = "Create and manage assertions"), + (name = "epochs", description = "Create and manage epochs (paradigms)"), + (name = "votes", description = "Create votes on assertions"), + (name = "query", description = "Query assertions with filters and lenses"), + (name = "health", description = "Health check endpoint"), + (name = "audit", description = "Query audit trail for incident investigation"), + (name = "supersession", description = "Supersede assertions for error correction"), + (name = "meter", description = "Economic throttling and quota management"), + ), + info( + title = "Episteme (StemeDB) API", + version = env!("CARGO_PKG_VERSION"), + description = "HTTP API for the probabilistic knowledge graph", + contact( + name = "Episteme Project", + ) + ) +)] +struct ApiDoc; + +/// Create the axum router with all routes and OpenAPI documentation. +/// +/// This creates a router without economic throttling (The Meter). +/// For production use, prefer `create_router_with_meter`. +pub fn create_router(state: AppState) -> Router { + // Build the API router + let api_router = Router::new() + .route("/v1/assert", post(handlers::create_assertion)) + .route("/v1/epoch", post(handlers::create_epoch)) + .route("/v1/vote", post(handlers::create_vote)) + .route("/v1/query", get(handlers::query_assertions)) + .route("/v1/skeptic", get(handlers::skeptic_query)) + .route("/v1/health", get(handlers::health_check)) + .route("/v1/audit/queries", get(handlers::list_audits)) + .route("/v1/audit/query/{id}", get(handlers::get_audit)) + .route("/v1/trace", get(handlers::trace)) + .route("/v1/supersede", post(handlers::supersede)) + .route("/v1/meter/quota", get(handlers::get_quota_status)) + .route("/v1/meter/quota/limit", post(handlers::set_quota_limit)) + .with_state(state) + .layer(TraceLayer::new_for_http()); + + // Mount Swagger UI + Router::new() + .merge(SwaggerUi::new("/swagger-ui").url("/api-docs/openapi.json", ApiDoc::openapi())) + .merge(api_router) +} + +/// Create the axum router with economic throttling (The Meter) enabled. +/// +/// This router enforces per-agent per-hour quotas based on operation costs: +/// - Assert: 10 tokens base + 1/KB payload +/// - Vote: 1 token base + 1/KB payload +/// - Query: 5 tokens base + 1 per lens + 1/KB payload +/// +/// Agents must provide `X-Agent-Id` header (hex-encoded Ed25519 public key). +/// Quota status headers are returned on all responses: +/// - `X-Quota-Remaining`: Tokens left in current window +/// - `X-Quota-Limit`: Total tokens per hour +/// - `X-Quota-Reset`: Unix timestamp when window resets +pub fn create_router_with_meter(state: AppState) -> Router { + use std::sync::Arc; + + // Create MeterLayer with the quota store from state + let meter_layer = MeterLayer::new(Arc::clone(&state.quota_store)); + + // Build the API router with metering + let api_router = Router::new() + .route("/v1/assert", post(handlers::create_assertion)) + .route("/v1/epoch", post(handlers::create_epoch)) + .route("/v1/vote", post(handlers::create_vote)) + .route("/v1/query", get(handlers::query_assertions)) + .route("/v1/skeptic", get(handlers::skeptic_query)) + .route("/v1/health", get(handlers::health_check)) + .route("/v1/audit/queries", get(handlers::list_audits)) + .route("/v1/audit/query/{id}", get(handlers::get_audit)) + .route("/v1/trace", get(handlers::trace)) + .route("/v1/supersede", post(handlers::supersede)) + .route("/v1/meter/quota", get(handlers::get_quota_status)) + .route("/v1/meter/quota/limit", post(handlers::set_quota_limit)) + .with_state(state) + .layer(meter_layer) + .layer(TraceLayer::new_for_http()); + + // Mount Swagger UI + Router::new() + .merge(SwaggerUi::new("/swagger-ui").url("/api-docs/openapi.json", ApiDoc::openapi())) + .merge(api_router) +} diff --git a/crates/stemedb-api/src/main.rs b/crates/stemedb-api/src/main.rs new file mode 100644 index 0000000..20c7bbf --- /dev/null +++ b/crates/stemedb-api/src/main.rs @@ -0,0 +1,143 @@ +//! Episteme (StemeDB) API server binary. +//! +//! This starts the HTTP API server with the following components: +//! 1. Opens Journal (WAL) and SledStore (KV storage) +//! 2. Spawns IngestWorker background task to tail WAL +//! 3. Starts axum HTTP server with OpenAPI documentation +//! 4. Optionally enables The Meter (economic throttling) +//! +//! # Environment Variables +//! +//! | Variable | Default | Description | +//! |----------|---------|-------------| +//! | `STEMEDB_WAL_DIR` | `data/wal` | Directory for WAL files | +//! | `STEMEDB_DB_DIR` | `data/db` | Directory for KV store | +//! | `STEMEDB_BIND_ADDR` | `127.0.0.1:3000` | HTTP server bind address | +//! | `STEMEDB_METER_ENABLED` | `true` | Enable economic throttling | + +use std::path::PathBuf; +use std::sync::Arc; +use tracing::{error, info}; +use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; + +use stemedb_api::{create_router, create_router_with_meter, AppState}; +use stemedb_ingest::worker::IngestWorker; +use stemedb_storage::SledStore; +use stemedb_wal::Journal; + +/// Server configuration. +#[derive(Debug, Clone)] +struct Config { + /// Directory for WAL files + wal_dir: PathBuf, + + /// Directory for KV store + db_dir: PathBuf, + + /// HTTP server bind address + bind_addr: String, + + /// Enable economic throttling (The Meter) + meter_enabled: bool, +} + +impl Default for Config { + fn default() -> Self { + Self { + wal_dir: PathBuf::from("data/wal"), + db_dir: PathBuf::from("data/db"), + bind_addr: "127.0.0.1:3000".to_string(), + meter_enabled: true, + } + } +} + +impl Config { + /// Load configuration from environment variables. + fn from_env() -> Self { + let mut config = Self::default(); + + if let Ok(wal_dir) = std::env::var("STEMEDB_WAL_DIR") { + config.wal_dir = PathBuf::from(wal_dir); + } + + if let Ok(db_dir) = std::env::var("STEMEDB_DB_DIR") { + config.db_dir = PathBuf::from(db_dir); + } + + if let Ok(bind_addr) = std::env::var("STEMEDB_BIND_ADDR") { + config.bind_addr = bind_addr; + } + + if let Ok(meter_enabled) = std::env::var("STEMEDB_METER_ENABLED") { + config.meter_enabled = meter_enabled.to_lowercase() != "false" && meter_enabled != "0"; + } + + config + } +} + +#[tokio::main] +async fn main() -> Result<(), Box> { + // Initialize tracing + let env_filter = match tracing_subscriber::EnvFilter::try_from_default_env() { + Ok(filter) => filter, + Err(_) => "stemedb_api=debug,tower_http=debug".into(), + }; + + tracing_subscriber::registry().with(env_filter).with(tracing_subscriber::fmt::layer()).init(); + + let config = Config::from_env(); + + info!("Starting Episteme (StemeDB) API server"); + info!(?config, "Configuration loaded"); + + // Ensure directories exist + std::fs::create_dir_all(&config.wal_dir)?; + std::fs::create_dir_all(&config.db_dir)?; + + // Open Journal and Store + info!("Opening Journal at {:?}", config.wal_dir); + let journal = Journal::open(&config.wal_dir)?; + + info!("Opening SledStore at {:?}", config.db_dir); + let store = SledStore::open(&config.db_dir)?; + + // Create application state + let state = AppState::new(journal, store.clone()); + + // Spawn IngestWorker background task + info!("Spawning IngestWorker background task"); + let worker_journal = state.journal.clone(); + let worker_store = Arc::new(store); + tokio::spawn(async move { + let worker_result = IngestWorker::new(worker_journal, worker_store).await; + match worker_result { + Ok(mut worker) => { + info!("IngestWorker started, entering run loop"); + worker.run().await; + } + Err(e) => { + error!("Failed to create IngestWorker: {:?}", e); + } + } + }); + + // Build router (with or without metering) + let app = if config.meter_enabled { + info!("The Meter enabled: economic throttling active (10K tokens/agent/hour)"); + create_router_with_meter(state) + } else { + info!("The Meter disabled: no quota enforcement"); + create_router(state) + }; + + // Start server + let listener = tokio::net::TcpListener::bind(&config.bind_addr).await?; + info!("API server listening on {}", config.bind_addr); + info!("Swagger UI available at http://{}/swagger-ui", config.bind_addr); + + axum::serve(listener, app).await?; + + Ok(()) +} diff --git a/crates/stemedb-api/src/middleware/meter.rs b/crates/stemedb-api/src/middleware/meter.rs new file mode 100644 index 0000000..c273450 --- /dev/null +++ b/crates/stemedb-api/src/middleware/meter.rs @@ -0,0 +1,334 @@ +//! Economic throttling middleware (The Meter). +//! +//! This middleware enforces per-agent per-hour quotas using a Token Bucket algorithm. +//! It extracts the agent ID from the `X-Agent-Id` header, determines the operation +//! type from the request path, and checks/records costs against the quota store. +//! +//! # Request Flow +//! +//! 1. Extract `X-Agent-Id` header (hex-encoded 32-byte public key) +//! 2. Determine operation type from request path (`/v1/assert`, `/v1/vote`, `/v1/query`) +//! 3. Calculate cost based on operation + payload size +//! 4. Check quota and reject with 429 if exceeded +//! 5. Record cost and forward request +//! 6. Add `X-Quota-Remaining` header to response +//! +//! # Headers +//! +//! | Header | Direction | Description | +//! |--------|-----------|-------------| +//! | `X-Agent-Id` | Request | Agent's Ed25519 public key (hex, 64 chars) | +//! | `X-Quota-Remaining` | Response | Remaining tokens in current window | +//! | `X-Quota-Limit` | Response | Total tokens allowed per hour | +//! | `X-Quota-Reset` | Response | Unix timestamp when quota resets | + +use axum::{ + body::Body, + http::{Request, Response, StatusCode}, + response::IntoResponse, + Json, +}; +use futures::future::BoxFuture; +use serde::Serialize; +use std::sync::Arc; +use std::task::{Context, Poll}; +use stemedb_storage::{OperationType, QuotaStore}; +use tower::{Layer, Service}; +use tracing::{debug, warn}; + +/// Header name for agent identification. +pub const AGENT_ID_HEADER: &str = "x-agent-id"; + +/// Header name for remaining quota. +pub const QUOTA_REMAINING_HEADER: &str = "x-quota-remaining"; + +/// Header name for quota limit. +pub const QUOTA_LIMIT_HEADER: &str = "x-quota-limit"; + +/// Header name for quota reset timestamp. +pub const QUOTA_RESET_HEADER: &str = "x-quota-reset"; + +/// Error response for quota exceeded. +#[derive(Debug, Serialize)] +struct QuotaExceededError { + error: String, + code: String, + remaining: u64, + limit: u64, + reset_at: u64, +} + +/// Tower Layer for economic throttling. +/// +/// Wrap your router with this layer to enable quota enforcement. +/// The cost configuration is determined by the `QuotaStore`. +/// +/// # Example +/// +/// ```ignore +/// let meter_layer = MeterLayer::new(quota_store); +/// let app = Router::new() +/// .route("/v1/assert", post(create_assertion)) +/// .layer(meter_layer); +/// ``` +#[derive(Clone)] +pub struct MeterLayer { + quota_store: Arc, + /// Paths that bypass metering (e.g., health checks). + bypass_paths: Vec, +} + +impl MeterLayer { + /// Create a new MeterLayer. + /// + /// The cost configuration is determined by the `QuotaStore`. + pub fn new(quota_store: Arc) -> Self { + Self { + quota_store, + bypass_paths: vec![ + "/v1/health".to_string(), + "/swagger-ui".to_string(), + "/api-docs".to_string(), + ], + } + } + + /// Add a path to bypass metering. + pub fn bypass_path(mut self, path: impl Into) -> Self { + self.bypass_paths.push(path.into()); + self + } +} + +impl Layer for MeterLayer +where + Q: Clone, +{ + type Service = MeterService; + + fn layer(&self, inner: S) -> Self::Service { + MeterService { + inner, + quota_store: Arc::clone(&self.quota_store), + bypass_paths: self.bypass_paths.clone(), + } + } +} + +/// Tower Service for economic throttling. +#[derive(Clone)] +pub struct MeterService { + inner: S, + quota_store: Arc, + bypass_paths: Vec, +} + +impl MeterService { + /// Determine operation type from request path. + fn operation_from_path(path: &str) -> Option { + if path.starts_with("/v1/assert") { + Some(OperationType::Assert) + } else if path.starts_with("/v1/vote") { + Some(OperationType::Vote) + } else if path.starts_with("/v1/query") || path.starts_with("/v1/skeptic") { + // Count lenses: if path has "lens" param or it's skeptic (which uses Skeptic lens) + let lens_count = if path.starts_with("/v1/skeptic") { 1 } else { 0 }; + Some(OperationType::Query { lens_count }) + } else if path.starts_with("/v1/audit") { + // Audit queries are free (internal debugging) + None + } else { + None + } + } + + /// Check if path should bypass metering. + #[allow(dead_code)] // Used in tests, may be used directly in the future + fn should_bypass(&self, path: &str) -> bool { + self.bypass_paths.iter().any(|p| path.starts_with(p)) + } + + /// Extract agent ID from request headers. + fn extract_agent_id(req: &Request) -> Option<[u8; 32]> { + req.headers().get(AGENT_ID_HEADER).and_then(|v| v.to_str().ok()).and_then(|s| { + let bytes = hex::decode(s).ok()?; + if bytes.len() == 32 { + let mut arr = [0u8; 32]; + arr.copy_from_slice(&bytes); + Some(arr) + } else { + None + } + }) + } +} + +impl Service> for MeterService +where + S: Service, Response = Response> + Clone + Send + 'static, + S::Future: Send, + Q: QuotaStore + 'static, +{ + type Response = Response; + type Error = S::Error; + type Future = BoxFuture<'static, Result>; + + fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.inner.poll_ready(cx) + } + + fn call(&mut self, req: Request) -> Self::Future { + let path = req.uri().path().to_string(); + let quota_store = Arc::clone(&self.quota_store); + let bypass_paths = self.bypass_paths.clone(); + + // Clone the inner service for the async block + let mut inner = self.inner.clone(); + + Box::pin(async move { + // Check if this path should bypass metering + if bypass_paths.iter().any(|p| path.starts_with(p)) { + debug!(path = %path, "Bypassing meter for path"); + return inner.call(req).await; + } + + // Determine operation type + let operation = match Self::operation_from_path(&path) { + Some(op) => op, + None => { + // Unknown operation, pass through without metering + debug!(path = %path, "No metering for path"); + return inner.call(req).await; + } + }; + + // Extract agent ID + let agent_id = match Self::extract_agent_id(&req) { + Some(id) => id, + None => { + // No agent ID provided, pass through (anonymous queries allowed) + debug!(path = %path, "No agent ID, allowing anonymous request"); + return inner.call(req).await; + } + }; + + // Get content length for payload-based costing + let content_length = req + .headers() + .get(axum::http::header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|s| s.parse::().ok()) + .unwrap_or(0); + + // Get current timestamp + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + + // Check and record quota + let quota_result = match quota_store + .check_and_record(&agent_id, operation, content_length, timestamp) + .await + { + Ok(result) => result, + Err(e) => { + warn!(error = %e, "Quota check failed, allowing request"); + // On error, allow the request (fail open for availability) + return inner.call(req).await; + } + }; + + if !quota_result.allowed { + // Quota exceeded - return 429 + let error = QuotaExceededError { + error: format!( + "Quota exceeded. You have {} tokens remaining, but this operation costs {}.", + quota_result.remaining, quota_result.cost + ), + code: "QUOTA_EXCEEDED".to_string(), + remaining: quota_result.remaining, + limit: quota_result.limit, + reset_at: quota_result.reset_at, + }; + + let mut response = (StatusCode::TOO_MANY_REQUESTS, Json(error)).into_response(); + + // Add quota headers + let headers = response.headers_mut(); + if let Ok(v) = quota_result.remaining.to_string().parse() { + headers.insert(QUOTA_REMAINING_HEADER, v); + } + if let Ok(v) = quota_result.limit.to_string().parse() { + headers.insert(QUOTA_LIMIT_HEADER, v); + } + if let Ok(v) = quota_result.reset_at.to_string().parse() { + headers.insert(QUOTA_RESET_HEADER, v); + } + + return Ok(response); + } + + // Quota OK - call inner service + let mut response = inner.call(req).await?; + + // Add quota headers to response + let headers = response.headers_mut(); + if let Ok(v) = quota_result.remaining.to_string().parse() { + headers.insert(QUOTA_REMAINING_HEADER, v); + } + if let Ok(v) = quota_result.limit.to_string().parse() { + headers.insert(QUOTA_LIMIT_HEADER, v); + } + if let Ok(v) = quota_result.reset_at.to_string().parse() { + headers.insert(QUOTA_RESET_HEADER, v); + } + + Ok(response) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_operation_from_path() { + assert!(matches!( + MeterService::<(), ()>::operation_from_path("/v1/assert"), + Some(OperationType::Assert) + )); + + assert!(matches!( + MeterService::<(), ()>::operation_from_path("/v1/vote"), + Some(OperationType::Vote) + )); + + assert!(matches!( + MeterService::<(), ()>::operation_from_path("/v1/query"), + Some(OperationType::Query { lens_count: 0 }) + )); + + assert!(matches!( + MeterService::<(), ()>::operation_from_path("/v1/skeptic"), + Some(OperationType::Query { lens_count: 1 }) + )); + + assert!(MeterService::<(), ()>::operation_from_path("/v1/health").is_none()); + assert!(MeterService::<(), ()>::operation_from_path("/v1/audit/queries").is_none()); + } + + #[test] + fn test_bypass_paths() { + let service = MeterService::<(), ()> { + inner: (), + quota_store: Arc::new(()), + bypass_paths: vec!["/v1/health".to_string(), "/swagger-ui".to_string()], + }; + + assert!(service.should_bypass("/v1/health")); + assert!(service.should_bypass("/swagger-ui/index.html")); + assert!(!service.should_bypass("/v1/assert")); + } +} diff --git a/crates/stemedb-api/src/middleware/mod.rs b/crates/stemedb-api/src/middleware/mod.rs new file mode 100644 index 0000000..26efe34 --- /dev/null +++ b/crates/stemedb-api/src/middleware/mod.rs @@ -0,0 +1,5 @@ +//! Middleware layers for the API. + +pub mod meter; + +pub use meter::{MeterLayer, MeterService}; diff --git a/crates/stemedb-api/src/state.rs b/crates/stemedb-api/src/state.rs new file mode 100644 index 0000000..be7b996 --- /dev/null +++ b/crates/stemedb-api/src/state.rs @@ -0,0 +1,46 @@ +//! Application state shared across all request handlers. + +use std::sync::Arc; +use tokio::sync::Mutex; + +use stemedb_query::QueryEngine; +use stemedb_storage::{GenericQuotaStore, SledStore}; +use stemedb_wal::Journal; + +/// Quota store type alias for convenience. +pub type QuotaStoreImpl = GenericQuotaStore>; + +/// Application state shared across all HTTP handlers. +/// +/// This is passed to every request via axum's `State` extractor. +#[derive(Clone)] +pub struct AppState { + /// Write-ahead log for appending new assertions/votes/epochs + pub journal: Arc>, + + /// Key-value store for reading assertions + pub store: Arc, + + /// Quota store for economic throttling (The Meter) + pub quota_store: Arc, +} + +impl AppState { + /// Create a new application state. + pub fn new(journal: Journal, store: SledStore) -> Self { + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(store); + + // Create quota store backed by the same KV store + let quota_store = Arc::new(GenericQuotaStore::new(Arc::clone(&store))); + + Self { journal, store, quota_store } + } + + /// Get a QueryEngine for this state. + /// + /// Creates a new QueryEngine each time since it cannot be cloned. + pub fn query_engine(&self) -> QueryEngine { + QueryEngine::new(self.store.clone()) + } +} diff --git a/crates/stemedb-api/tests/e2e_flow_test.rs b/crates/stemedb-api/tests/e2e_flow_test.rs new file mode 100644 index 0000000..eb85ca8 --- /dev/null +++ b/crates/stemedb-api/tests/e2e_flow_test.rs @@ -0,0 +1,590 @@ +//! End-to-end integration test for the write → materialize → query flow. +//! +//! This test proves the complete StemeDB pipeline works: +//! 1. POST /v1/assert - Write a signed assertion to the WAL +//! 2. IngestWorker - Process the WAL and write to KV store + indexes +//! 3. Materializer - Resolve conflicts and write to MV:{subject}:{predicate} +//! 4. GET /v1/query - Read the materialized view through a lens +//! +//! The test uses Ed25519 signatures, tokio::sync::Notify for event-driven +//! materialization, and axum's test utilities for HTTP requests. + +#![allow(clippy::expect_used)] + +use axum::{ + body::Body, + http::{Request, StatusCode}, +}; +use ed25519_dalek::{Signer, SigningKey}; +use rand::rngs::OsRng; +use serde_json::json; +use std::sync::Arc; +use tokio::sync::{Mutex, Notify}; +use tower::ServiceExt; + +use stemedb_api::{create_router, AppState}; +use stemedb_ingest::worker::IngestWorker; +use stemedb_lens::VoteAwareConsensusLens; +use stemedb_query::Materializer; +use stemedb_storage::{GenericVoteStore, SledStore}; +use stemedb_wal::Journal; + +// Test configuration constants +const INGEST_ITERATIONS: usize = 10; +const INGEST_SLEEP_MS: u64 = 10; +const MATERIALIZER_ITERATIONS: usize = 5; +const MATERIALIZER_TIMEOUT_MS: u64 = 200; +const WORKER_SHUTDOWN_MS: u64 = 50; +const POLLING_TIMEOUT_MS: u64 = 500; +const POLLING_INTERVAL_MS: u64 = 50; + +/// Test environment that keeps temp directories alive. +struct TestEnvironment { + _temp_dir: tempfile::TempDir, + state: AppState, + store: Arc, + journal: Arc>, +} + +/// Helper to create a test environment with temporary directories. +async fn create_test_environment() -> TestEnvironment { + let temp_dir = tempfile::tempdir().expect("Failed to create temp dir"); + let wal_dir = temp_dir.path().join("wal"); + let db_dir = temp_dir.path().join("db"); + + std::fs::create_dir_all(&wal_dir).expect("Failed to create WAL dir"); + std::fs::create_dir_all(&db_dir).expect("Failed to create DB dir"); + + let journal = Journal::open(&wal_dir).expect("Failed to open journal"); + let store = SledStore::open(&db_dir).expect("Failed to open store"); + + let journal_arc = Arc::new(Mutex::new(journal)); + let store_arc = Arc::new(store); + + // Open a second journal handle for AppState (WAL supports multiple readers) + let journal_for_state = Journal::open(&wal_dir).expect("Failed to open second journal handle"); + let state = AppState::new(journal_for_state, (*store_arc).clone()); + + TestEnvironment { _temp_dir: temp_dir, state, store: store_arc, journal: journal_arc } +} + +/// Sign a message using Ed25519 and return the signature + public key. +fn sign_message(message: &str) -> ([u8; 32], [u8; 64]) { + let mut csprng = OsRng; + let signing_key = SigningKey::generate(&mut csprng); + let verifying_key = signing_key.verifying_key(); + + let signature = signing_key.sign(message.as_bytes()); + + (verifying_key.to_bytes(), signature.to_bytes()) +} + +#[tokio::test] +async fn test_e2e_write_materialize_query_flow() { + // ======================================================================== + // Phase 1: Setup - Create environment and spawn background workers + // ======================================================================== + + let env = create_test_environment().await; + let state = env.state.clone(); + let store = Arc::clone(&env.store); + let journal = Arc::clone(&env.journal); + + // Create a notification channel for event-driven materialization + let notify = Arc::new(Notify::new()); + + // Spawn IngestWorker in the background with notification + let ingest_notify = Arc::clone(¬ify); + let mut ingest_worker = IngestWorker::new(Arc::clone(&journal), Arc::clone(&store)) + .await + .expect("Failed to create IngestWorker") + .with_notify(ingest_notify); + + let ingest_handle = tokio::spawn(async move { + // Run a few ingestion steps (not infinite loop for tests) + for _ in 0..INGEST_ITERATIONS { + match ingest_worker.step().await { + Ok(0) => { + // No data, sleep briefly + tokio::time::sleep(tokio::time::Duration::from_millis(INGEST_SLEEP_MS)).await; + } + Ok(_) => { + // Processed data, continue immediately + } + Err(e) => { + tracing::error!("Ingestion error: {:?}", e); + break; + } + } + } + }); + + // Spawn Materializer in the background (event-driven mode) + let materializer_notify = Arc::clone(¬ify); + let vote_store = Arc::new(GenericVoteStore::new(Arc::clone(&store))); + let lens = VoteAwareConsensusLens::new(vote_store); + let materializer = Arc::new(Materializer::new(Arc::clone(&store), Box::new(lens))); + let materializer_clone = Arc::clone(&materializer); + + let materializer_handle = tokio::spawn(async move { + // Run event-driven materialization with a short timeout + // We'll only run a few passes for the test + for _ in 0..MATERIALIZER_ITERATIONS { + let was_notified = tokio::time::timeout( + tokio::time::Duration::from_millis(MATERIALIZER_TIMEOUT_MS), + materializer_notify.notified(), + ) + .await + .is_ok(); + + if was_notified { + if let Err(e) = materializer_clone.step().await { + tracing::error!("Materialization error: {:?}", e); + } + } + } + }); + + // ======================================================================== + // Phase 2: Write - Create a properly signed assertion via API + // ======================================================================== + + let subject = "Tesla_Inc"; + let predicate = "has_revenue"; + let message = format!("{}:{}", subject, predicate); + let (agent_id, signature) = sign_message(&message); + + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("Time error") + .as_secs(); + + let assertion_request = json!({ + "subject": subject, + "predicate": predicate, + "object": {"type": "Number", "value": 96.7}, + "confidence": 0.95, + "signatures": [{ + "agent_id": hex::encode(agent_id), + "signature": hex::encode(signature), + "timestamp": timestamp + }], + "source_hash": hex::encode([3u8; 32]) + }); + + let app = create_router(state.clone()); + + let create_request = Request::builder() + .uri("/v1/assert") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&assertion_request).expect("JSON serialization"))) + .expect("Failed to build request"); + + let create_response = app.clone().oneshot(create_request).await.expect("Request failed"); + + let status = create_response.status(); + + // Debug: Print response if not successful + if status != StatusCode::CREATED { + let body_bytes = axum::body::to_bytes(create_response.into_body(), usize::MAX) + .await + .expect("Failed to read error body"); + let error_text = String::from_utf8_lossy(&body_bytes); + panic!("Assertion creation failed with status {}: {}", status, error_text); + } + + assert_eq!(status, StatusCode::CREATED, "Assertion creation should succeed"); + + let create_body = axum::body::to_bytes(create_response.into_body(), usize::MAX) + .await + .expect("Failed to read response body"); + let create_json: serde_json::Value = + serde_json::from_slice(&create_body).expect("Failed to parse JSON"); + + let assertion_hash = create_json["hash"].as_str().expect("Missing hash field").to_string(); + + assert_eq!(create_json["status"], "created"); + assert!(!assertion_hash.is_empty(), "Hash should not be empty"); + + // ======================================================================== + // Phase 3: Wait - Allow ingestion and materialization to complete + // ======================================================================== + + // Poll for the assertion to be available instead of blind sleep + // This is more robust and fails fast if something goes wrong + let start = tokio::time::Instant::now(); + let timeout = tokio::time::Duration::from_millis(POLLING_TIMEOUT_MS); + let poll_interval = tokio::time::Duration::from_millis(POLLING_INTERVAL_MS); + + loop { + // Try to query the assertion + let test_query = Request::builder() + .uri(format!("/v1/query?subject={}&predicate={}", subject, predicate)) + .method("GET") + .body(Body::empty()) + .expect("Failed to build test query"); + + let test_response = app.clone().oneshot(test_query).await.expect("Query failed"); + let test_body = axum::body::to_bytes(test_response.into_body(), usize::MAX) + .await + .expect("Failed to read body"); + let test_json: serde_json::Value = + serde_json::from_slice(&test_body).expect("Failed to parse JSON"); + + if test_json["total_count"].as_u64().unwrap_or(0) > 0 { + // Assertion is available, proceed + break; + } + + if start.elapsed() > timeout { + panic!("Timeout waiting for assertion to be ingested and materialized"); + } + + tokio::time::sleep(poll_interval).await; + } + + // ======================================================================== + // Phase 4: Query - Read the assertion via lens-based query + // ======================================================================== + + let query_request = Request::builder() + .uri(format!("/v1/query?subject={}&predicate={}&lens=Consensus", subject, predicate)) + .method("GET") + .body(Body::empty()) + .expect("Failed to build query request"); + + let query_response = app.oneshot(query_request).await.expect("Query request failed"); + + assert_eq!(query_response.status(), StatusCode::OK, "Query should succeed"); + + let query_body = axum::body::to_bytes(query_response.into_body(), usize::MAX) + .await + .expect("Failed to read query response body"); + let query_json: serde_json::Value = + serde_json::from_slice(&query_body).expect("Failed to parse query JSON"); + + // ======================================================================== + // Phase 5: Verify - Assertion matches what we created + // ======================================================================== + + let assertions = query_json["assertions"].as_array().expect("Missing assertions array"); + + assert_eq!(assertions.len(), 1, "Should return exactly one assertion after lens resolution"); + + let returned_assertion = &assertions[0]; + + // Verify the assertion fields + assert_eq!( + returned_assertion["hash"].as_str().expect("Missing hash"), + assertion_hash, + "Returned assertion hash should match created hash" + ); + assert_eq!(returned_assertion["subject"].as_str().expect("Missing subject"), subject); + assert_eq!(returned_assertion["predicate"].as_str().expect("Missing predicate"), predicate); + assert_eq!( + returned_assertion["object"]["type"].as_str().expect("Missing object type"), + "Number" + ); + assert!( + (returned_assertion["object"]["value"].as_f64().expect("Missing object value") - 96.7) + .abs() + < 0.01 + ); + assert!( + (returned_assertion["confidence"].as_f64().expect("Missing confidence") - 0.95).abs() + < 0.01 + ); + + // Verify signature round-trip + let signatures = returned_assertion["signatures"].as_array().expect("Missing signatures array"); + assert_eq!(signatures.len(), 1, "Should have one signature"); + assert_eq!( + signatures[0]["agent_id"].as_str().expect("Missing agent_id"), + hex::encode(agent_id) + ); + assert_eq!( + signatures[0]["signature"].as_str().expect("Missing signature"), + hex::encode(signature) + ); + + // Verify metadata + assert_eq!(query_json["total_count"], 1); + assert_eq!(query_json["has_more"], false); + + // ======================================================================== + // Cleanup - Abort background workers + // ======================================================================== + + ingest_handle.abort(); + materializer_handle.abort(); + + // Wait a bit to ensure clean shutdown + tokio::time::sleep(tokio::time::Duration::from_millis(WORKER_SHUTDOWN_MS)).await; +} + +#[tokio::test] +async fn test_e2e_query_with_no_lens_returns_all_candidates() { + // ======================================================================== + // Setup + // ======================================================================== + + let env = create_test_environment().await; + let state = env.state.clone(); + let store = Arc::clone(&env.store); + let journal = Arc::clone(&env.journal); + let notify = Arc::new(Notify::new()); + + let ingest_notify = Arc::clone(¬ify); + let mut ingest_worker = IngestWorker::new(Arc::clone(&journal), Arc::clone(&store)) + .await + .expect("Failed to create IngestWorker") + .with_notify(ingest_notify); + + // ======================================================================== + // Create two competing assertions for the same subject+predicate + // ======================================================================== + + let subject = "Apple_Inc"; + let predicate = "has_revenue"; + + // Assertion 1: revenue = 380.0 + let message1 = format!("{}:{}", subject, predicate); + let (agent_id1, signature1) = sign_message(&message1); + let timestamp1 = 1000; + + let assertion1 = json!({ + "subject": subject, + "predicate": predicate, + "object": {"type": "Number", "value": 380.0}, + "confidence": 0.9, + "signatures": [{ + "agent_id": hex::encode(agent_id1), + "signature": hex::encode(signature1), + "timestamp": timestamp1 + }], + "source_hash": hex::encode([1u8; 32]) + }); + + // Assertion 2: revenue = 385.0 (newer timestamp) + let message2 = format!("{}:{}", subject, predicate); + let (agent_id2, signature2) = sign_message(&message2); + let timestamp2 = 2000; + + let assertion2 = json!({ + "subject": subject, + "predicate": predicate, + "object": {"type": "Number", "value": 385.0}, + "confidence": 0.85, + "signatures": [{ + "agent_id": hex::encode(agent_id2), + "signature": hex::encode(signature2), + "timestamp": timestamp2 + }], + "source_hash": hex::encode([2u8; 32]) + }); + + let app = create_router(state.clone()); + + // Create both assertions + for assertion in [&assertion1, &assertion2] { + let request = Request::builder() + .uri("/v1/assert") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(assertion).expect("JSON serialization"))) + .expect("Failed to build request"); + + let response = app.clone().oneshot(request).await.expect("Request failed"); + assert_eq!(response.status(), StatusCode::CREATED); + } + + // Process ingestion + for _ in 0..INGEST_ITERATIONS { + if ingest_worker.step().await.expect("Ingestion failed") == 0 { + break; + } + } + + // ======================================================================== + // Query without a lens - should return both assertions + // ======================================================================== + + let query_request = Request::builder() + .uri(format!("/v1/query?subject={}&predicate={}", subject, predicate)) + .method("GET") + .body(Body::empty()) + .expect("Failed to build query request"); + + let query_response = app.oneshot(query_request).await.expect("Query request failed"); + + assert_eq!(query_response.status(), StatusCode::OK); + + let query_body = axum::body::to_bytes(query_response.into_body(), usize::MAX) + .await + .expect("Failed to read query response body"); + let query_json: serde_json::Value = + serde_json::from_slice(&query_body).expect("Failed to parse query JSON"); + + let assertions = query_json["assertions"].as_array().expect("Missing assertions array"); + + assert_eq!(assertions.len(), 2, "Without a lens, should return all candidate assertions"); + + // Verify both values are present + let values: Vec = + assertions.iter().map(|a| a["object"]["value"].as_f64().expect("Missing value")).collect(); + + assert!(values.contains(&380.0), "Should contain first assertion value"); + assert!(values.contains(&385.0), "Should contain second assertion value"); + + assert_eq!(query_json["total_count"], 2); +} + +#[tokio::test] +async fn test_e2e_lens_resolution_picks_most_recent() { + // ======================================================================== + // Setup + // ======================================================================== + + let env = create_test_environment().await; + let state = env.state.clone(); + let store = Arc::clone(&env.store); + let journal = Arc::clone(&env.journal); + let notify = Arc::new(Notify::new()); + + let ingest_notify = Arc::clone(¬ify); + let mut ingest_worker = IngestWorker::new(Arc::clone(&journal), Arc::clone(&store)) + .await + .expect("Failed to create IngestWorker") + .with_notify(ingest_notify); + + // ======================================================================== + // Create two assertions with different timestamps + // ======================================================================== + + let subject = "Microsoft_Corp"; + let predicate = "has_ceo"; + + // Older assertion: Satya (timestamp 1000) + let message1 = format!("{}:{}", subject, predicate); + let (agent_id1, signature1) = sign_message(&message1); + + let old_assertion = json!({ + "subject": subject, + "predicate": predicate, + "object": {"type": "Text", "value": "Satya_Nadella"}, + "confidence": 0.9, + "signatures": [{ + "agent_id": hex::encode(agent_id1), + "signature": hex::encode(signature1), + "timestamp": 1000 + }], + "source_hash": hex::encode([1u8; 32]) + }); + + // Newer assertion: Bill (timestamp 5000) - hypothetically outdated info + let message2 = format!("{}:{}", subject, predicate); + let (agent_id2, signature2) = sign_message(&message2); + + let new_assertion = json!({ + "subject": subject, + "predicate": predicate, + "object": {"type": "Text", "value": "Bill_Gates"}, + "confidence": 0.8, + "signatures": [{ + "agent_id": hex::encode(agent_id2), + "signature": hex::encode(signature2), + "timestamp": 5000 + }], + "source_hash": hex::encode([2u8; 32]) + }); + + let app = create_router(state.clone()); + + // Create both assertions + for assertion in [&old_assertion, &new_assertion] { + let request = Request::builder() + .uri("/v1/assert") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(assertion).expect("JSON serialization"))) + .expect("Failed to build request"); + + let response = app.clone().oneshot(request).await.expect("Request failed"); + assert_eq!(response.status(), StatusCode::CREATED); + } + + // Process ingestion + for _ in 0..INGEST_ITERATIONS { + if ingest_worker.step().await.expect("Ingestion failed") == 0 { + break; + } + } + + // ======================================================================== + // Query with Recency lens - should pick the newer one + // ======================================================================== + + let query_request = Request::builder() + .uri(format!("/v1/query?subject={}&predicate={}&lens=Recency", subject, predicate)) + .method("GET") + .body(Body::empty()) + .expect("Failed to build query request"); + + let query_response = app.oneshot(query_request).await.expect("Query request failed"); + + assert_eq!(query_response.status(), StatusCode::OK); + + let query_body = axum::body::to_bytes(query_response.into_body(), usize::MAX) + .await + .expect("Failed to read query response body"); + let query_json: serde_json::Value = + serde_json::from_slice(&query_body).expect("Failed to parse query JSON"); + + let assertions = query_json["assertions"].as_array().expect("Missing assertions array"); + + assert_eq!(assertions.len(), 1, "Recency lens should return exactly one assertion"); + + // Verify it picked the newer one (Bill_Gates at timestamp 5000) + let winner = &assertions[0]; + assert_eq!( + winner["object"]["value"].as_str().expect("Missing value"), + "Bill_Gates", + "Recency lens should pick the most recent assertion" + ); + assert_eq!(winner["signatures"][0]["timestamp"].as_u64().expect("Missing timestamp"), 5000); +} + +#[tokio::test] +async fn test_e2e_empty_query_returns_no_results() { + // ======================================================================== + // Setup with no data + // ======================================================================== + + let env = create_test_environment().await; + let app = create_router(env.state); + + // ======================================================================== + // Query for non-existent subject + // ======================================================================== + + let query_request = Request::builder() + .uri("/v1/query?subject=Nonexistent_Entity&predicate=some_property") + .method("GET") + .body(Body::empty()) + .expect("Failed to build query request"); + + let query_response = app.oneshot(query_request).await.expect("Query request failed"); + + assert_eq!(query_response.status(), StatusCode::OK); + + let query_body = axum::body::to_bytes(query_response.into_body(), usize::MAX) + .await + .expect("Failed to read query response body"); + let query_json: serde_json::Value = + serde_json::from_slice(&query_body).expect("Failed to parse query JSON"); + + assert_eq!(query_json["assertions"], json!([])); + assert_eq!(query_json["total_count"], 0); + assert_eq!(query_json["has_more"], false); +} diff --git a/crates/stemedb-api/tests/integration_tests.rs b/crates/stemedb-api/tests/integration_tests.rs new file mode 100644 index 0000000..c0a7a71 --- /dev/null +++ b/crates/stemedb-api/tests/integration_tests.rs @@ -0,0 +1,691 @@ +//! Integration tests for the StemeDB API. + +#![allow(clippy::expect_used)] + +use axum::{ + body::Body, + http::{Request, StatusCode}, +}; +use ed25519_dalek::{Signer, SigningKey}; +use rand::rngs::OsRng; +use serde_json::json; +use std::sync::Arc; +use tokio::sync::Mutex; +use tower::ServiceExt; // for `oneshot` and `ready` + +use stemedb_api::{create_router, AppState}; +use stemedb_ingest::Ingestor; +use stemedb_storage::SledStore; +use stemedb_wal::Journal; + +/// Test environment that keeps temp directories alive for the test duration. +/// +/// The `_temp_dir` field must be kept alive to prevent the directory from +/// being deleted while the Journal and SledStore are still using it. +struct TestEnvironment { + _temp_dir: tempfile::TempDir, + state: AppState, +} + +/// Test environment with full ingestor for roundtrip tests. +struct TestEnvironmentWithIngestor { + _temp_dir: tempfile::TempDir, + state: AppState, + ingestor: Ingestor, +} + +/// Helper to create a test environment with temporary directories. +async fn create_test_env() -> TestEnvironment { + let temp_dir = tempfile::tempdir().expect("failed to create temp dir"); + let wal_dir = temp_dir.path().join("wal"); + let db_dir = temp_dir.path().join("db"); + + std::fs::create_dir_all(&wal_dir).expect("failed to create wal dir"); + std::fs::create_dir_all(&db_dir).expect("failed to create db dir"); + + let journal = Journal::open(&wal_dir).expect("failed to open journal"); + let store = SledStore::open(&db_dir).expect("failed to open store"); + + let state = AppState::new(journal, store); + + TestEnvironment { _temp_dir: temp_dir, state } +} + +/// Helper to create a test environment with a running ingestor for roundtrip tests. +/// +/// Note: We need to share the same store between AppState and Ingestor. +/// AppState::new() takes ownership, so we need a different approach: +/// we'll create the ingestor first, then construct AppState manually. +async fn create_test_env_with_ingestor() -> TestEnvironmentWithIngestor { + use stemedb_storage::GenericQuotaStore; + + let temp_dir = tempfile::tempdir().expect("failed to create temp dir"); + let wal_dir = temp_dir.path().join("wal"); + let db_dir = temp_dir.path().join("db"); + + std::fs::create_dir_all(&wal_dir).expect("failed to create wal dir"); + std::fs::create_dir_all(&db_dir).expect("failed to create db dir"); + + // Create shared store + let store = Arc::new(SledStore::open(&db_dir).expect("failed to open store")); + + // Journal for API (writing) + let journal_for_api = + Arc::new(Mutex::new(Journal::open(&wal_dir).expect("failed to open journal for API"))); + + // Journal for ingestor (reading) - WAL allows multiple readers + let journal_for_ingestor = + Arc::new(Mutex::new(Journal::open(&wal_dir).expect("failed to open journal for ingestor"))); + + // Create ingestor with shared store + let ingestor = Ingestor::new(journal_for_ingestor, store.clone()) + .await + .expect("failed to create ingestor"); + + // Create quota store for AppState + let quota_store = Arc::new(GenericQuotaStore::new(store.clone())); + + // Construct AppState manually to share the store + let state = AppState { journal: journal_for_api, store, quota_store }; + + TestEnvironmentWithIngestor { _temp_dir: temp_dir, state, ingestor } +} + +#[tokio::test] +async fn test_health_check() { + let env = create_test_env().await; + let app = create_router(env.state); + + let request = Request::builder().uri("/v1/health").method("GET").body(Body::empty()).unwrap(); + + let response = app.oneshot(request).await.unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + + let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + + assert_eq!(json["status"], "healthy"); + assert!(json["version"].is_string()); + assert_eq!(json["assertions_count"], 0); +} + +#[tokio::test] +async fn test_dto_confidence_validation() { + let env = create_test_env().await; + let app = create_router(env.state); + + // Test confidence > 1.0 + let invalid_assertion = json!({ + "subject": "Tesla", + "predicate": "has_revenue", + "object": {"type": "Number", "value": 100.0}, + "confidence": 1.5, + "signatures": [{ + "agent_id": "a".repeat(64), + "signature": "b".repeat(128), + "timestamp": 1234567890 + }], + "source_hash": "c".repeat(64) + }); + + let request = Request::builder() + .uri("/v1/assert") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&invalid_assertion).unwrap())) + .unwrap(); + + let response = app.clone().oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + + let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert!(json["error"].as_str().unwrap().contains("Confidence must be between 0.0 and 1.0")); + + // Test confidence < 0.0 + let invalid_assertion = json!({ + "subject": "Tesla", + "predicate": "has_revenue", + "object": {"type": "Number", "value": 100.0}, + "confidence": -0.5, + "signatures": [{ + "agent_id": "a".repeat(64), + "signature": "b".repeat(128), + "timestamp": 1234567890 + }], + "source_hash": "c".repeat(64) + }); + + let request = Request::builder() + .uri("/v1/assert") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&invalid_assertion).unwrap())) + .unwrap(); + + let response = app.oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + + let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert!(json["error"].as_str().unwrap().contains("Confidence must be between 0.0 and 1.0")); +} + +#[tokio::test] +async fn test_dto_weight_validation() { + let env = create_test_env().await; + let app = create_router(env.state); + + // Test weight > 1.0 + let invalid_vote = json!({ + "assertion_hash": "a".repeat(64), + "agent_id": "b".repeat(64), + "weight": 1.5, + "signature": "c".repeat(128) + }); + + let request = Request::builder() + .uri("/v1/vote") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&invalid_vote).unwrap())) + .unwrap(); + + let response = app.clone().oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + + let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert!(json["error"].as_str().unwrap().contains("Weight must be between 0.0 and 1.0")); + + // Test weight < 0.0 + let invalid_vote = json!({ + "assertion_hash": "a".repeat(64), + "agent_id": "b".repeat(64), + "weight": -0.5, + "signature": "c".repeat(128) + }); + + let request = Request::builder() + .uri("/v1/vote") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&invalid_vote).unwrap())) + .unwrap(); + + let response = app.oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + + let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert!(json["error"].as_str().unwrap().contains("Weight must be between 0.0 and 1.0")); +} + +#[tokio::test] +async fn test_hex_decode_wrong_length() { + let env = create_test_env().await; + let app = create_router(env.state); + + // Test assertion with wrong-length source_hash + let invalid_assertion = json!({ + "subject": "Tesla", + "predicate": "has_revenue", + "object": {"type": "Number", "value": 100.0}, + "confidence": 0.9, + "signatures": [{ + "agent_id": "a".repeat(64), + "signature": "b".repeat(128), + "timestamp": 1234567890 + }], + "source_hash": "abc" // Too short + }); + + let request = Request::builder() + .uri("/v1/assert") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&invalid_assertion).unwrap())) + .unwrap(); + + let response = app.oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + + let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + let error_msg = json["error"].as_str().unwrap(); + assert!(error_msg.contains("Expected 64 hex characters")); + assert!(error_msg.contains("got 3")); +} + +#[tokio::test] +async fn test_hex_decode_valid() { + let env = create_test_env().await; + let app = create_router(env.state); + + // Test assertion with valid hex lengths + // Note: This will succeed in parsing/validation but may fail in the ingest worker + // We're primarily testing that hex validation accepts correct-length strings + let valid_assertion = json!({ + "subject": "Tesla", + "predicate": "has_revenue", + "object": {"type": "Number", "value": 100.0}, + "confidence": 0.9, + "signatures": [{ + "agent_id": "a".repeat(64), + "signature": "b".repeat(128), + "timestamp": 1234567890 + }], + "source_hash": "c".repeat(64) + }); + + let request = Request::builder() + .uri("/v1/assert") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&valid_assertion).unwrap())) + .unwrap(); + + let response = app.oneshot(request).await.unwrap(); + + // Accept either 201 (success) or 500 (ingest worker not running in test) + // We're primarily testing that the hex validation doesn't reject valid lengths + assert!( + response.status() == StatusCode::CREATED + || response.status() == StatusCode::INTERNAL_SERVER_ERROR, + "Expected 201 or 500, got {}", + response.status() + ); +} + +#[tokio::test] +async fn test_dto_to_assertion_invalid_hex() { + let env = create_test_env().await; + let app = create_router(env.state); + + // Test assertion with invalid hex characters + let invalid_assertion = json!({ + "subject": "Tesla", + "predicate": "has_revenue", + "object": {"type": "Number", "value": 100.0}, + "confidence": 0.9, + "signatures": [{ + "agent_id": "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", // 'z' is not a valid hex character (64 z's) + "signature": "b".repeat(128), + "timestamp": 1234567890 + }], + "source_hash": "c".repeat(64) + }); + + let request = Request::builder() + .uri("/v1/assert") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&invalid_assertion).unwrap())) + .unwrap(); + + let response = app.oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + + let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + let error = json["error"].as_str().unwrap(); + // The error could be "Invalid hex encoding" or similar - just check it's a bad request error + assert!(!error.is_empty(), "Error message should not be empty"); +} + +#[tokio::test] +async fn test_query_empty_results() { + let env = create_test_env().await; + let app = create_router(env.state); + + let request = Request::builder() + .uri("/v1/query?subject=nonexistent") + .method("GET") + .body(Body::empty()) + .unwrap(); + + let response = app.oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + + let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + + assert_eq!(json["assertions"], json!([])); + assert_eq!(json["total_count"], 0); + assert_eq!(json["has_more"], false); +} + +// ============================================================================ +// Epoch Endpoint Integration Tests +// ============================================================================ + +#[tokio::test] +async fn test_create_epoch_success() { + let env = create_test_env().await; + let app = create_router(env.state); + + let epoch = json!({ + "name": "GAAP-2024", + "start_timestamp": 1704067200 + }); + + let request = Request::builder() + .uri("/v1/epoch") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&epoch).unwrap())) + .unwrap(); + + let response = app.oneshot(request).await.unwrap(); + let status = response.status(); + + let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + + assert_eq!(status, StatusCode::CREATED, "Body: {:?}", json); + + assert_eq!(json["status"], "created"); + // BLAKE3 hash = 32 bytes = 64 hex characters + assert_eq!(json["hash"].as_str().unwrap().len(), 64); +} + +#[tokio::test] +async fn test_create_epoch_empty_name_fails() { + let env = create_test_env().await; + let app = create_router(env.state); + + let epoch = json!({ + "name": "", + "start_timestamp": 1704067200 + }); + + let request = Request::builder() + .uri("/v1/epoch") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&epoch).unwrap())) + .unwrap(); + + let response = app.oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + + let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert!(json["error"].as_str().unwrap().contains("cannot be empty")); +} + +#[tokio::test] +async fn test_create_epoch_whitespace_name_fails() { + let env = create_test_env().await; + let app = create_router(env.state); + + let epoch = json!({ + "name": " ", + "start_timestamp": 1704067200 + }); + + let request = Request::builder() + .uri("/v1/epoch") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&epoch).unwrap())) + .unwrap(); + + let response = app.oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + + let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert!(json["error"].as_str().unwrap().contains("cannot be empty")); +} + +#[tokio::test] +async fn test_create_epoch_with_supersedes() { + let env = create_test_env().await; + let app = create_router(env.state); + + // Supersession requires both supersedes hash AND supersession_type + let epoch = json!({ + "name": "GAAP-2025", + "supersedes": "a".repeat(64), + "supersession_type": "Temporal", + "start_timestamp": 1735689600 + }); + + let request = Request::builder() + .uri("/v1/epoch") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&epoch).unwrap())) + .unwrap(); + + let response = app.oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::CREATED); + + let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(json["status"], "created"); +} + +#[tokio::test] +async fn test_create_epoch_supersedes_without_type_fails() { + let env = create_test_env().await; + let app = create_router(env.state); + + // Providing supersedes but NOT supersession_type should fail + let epoch = json!({ + "name": "GAAP-2025", + "supersedes": "a".repeat(64), + // Missing supersession_type! + "start_timestamp": 1735689600 + }); + + let request = Request::builder() + .uri("/v1/epoch") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&epoch).unwrap())) + .unwrap(); + + let response = app.oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + + let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert!(json["error"].as_str().unwrap().contains("supersession_type is required")); +} + +#[tokio::test] +async fn test_create_epoch_invalid_supersedes_hex() { + let env = create_test_env().await; + let app = create_router(env.state); + + let epoch = json!({ + "name": "GAAP-2025", + "supersedes": "invalid", // Too short, should be 64 hex chars + "supersession_type": "Invalidate", + "start_timestamp": 1735689600 + }); + + let request = Request::builder() + .uri("/v1/epoch") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&epoch).unwrap())) + .unwrap(); + + let response = app.oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + + let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + // Should complain about hex length + assert!(json["error"].as_str().unwrap().contains("Expected 64 hex characters")); +} + +#[tokio::test] +async fn test_create_epoch_deterministic_id() { + let env = create_test_env().await; + let app = create_router(env.state); + + // Create the same epoch twice - should get the same ID + let epoch = json!({ + "name": "Deterministic-Test", + "start_timestamp": 1000 + }); + + let request1 = Request::builder() + .uri("/v1/epoch") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&epoch).unwrap())) + .unwrap(); + + let response1 = app.clone().oneshot(request1).await.unwrap(); + assert_eq!(response1.status(), StatusCode::CREATED); + let body1 = axum::body::to_bytes(response1.into_body(), usize::MAX).await.unwrap(); + let json1: serde_json::Value = serde_json::from_slice(&body1).unwrap(); + let hash1 = json1["hash"].as_str().unwrap(); + + let request2 = Request::builder() + .uri("/v1/epoch") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&epoch).unwrap())) + .unwrap(); + + let response2 = app.oneshot(request2).await.unwrap(); + assert_eq!(response2.status(), StatusCode::CREATED); + let body2 = axum::body::to_bytes(response2.into_body(), usize::MAX).await.unwrap(); + let json2: serde_json::Value = serde_json::from_slice(&body2).unwrap(); + let hash2 = json2["hash"].as_str().unwrap(); + + // Same input should produce same ID + assert_eq!(hash1, hash2, "Same epoch input should produce deterministic ID"); +} + +#[tokio::test] +async fn test_create_epoch_defaults_timestamp() { + let env = create_test_env().await; + let app = create_router(env.state); + + // Omit start_timestamp - should default to current time + let epoch = json!({ + "name": "Default-Timestamp-Test" + }); + + let request = Request::builder() + .uri("/v1/epoch") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&epoch).unwrap())) + .unwrap(); + + let response = app.oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::CREATED); + + // If we got 201, the timestamp defaulted successfully + let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(json["status"], "created"); +} + +// ============================================================================ +// Full Pipeline Integration Tests (POST → Ingest → GET roundtrip) +// ============================================================================ + +/// Create a properly signed assertion for testing. +fn create_signed_assertion_json(subject: &str, predicate: &str, value: f64) -> serde_json::Value { + let mut csprng = OsRng; + let signing_key = SigningKey::generate(&mut csprng); + let verifying_key = signing_key.verifying_key(); + + let message = format!("{}:{}", subject, predicate); + let signature = signing_key.sign(message.as_bytes()); + + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + + json!({ + "subject": subject, + "predicate": predicate, + "object": {"type": "Number", "value": value}, + "confidence": 0.95, + "source_class": "Expert", + "lifecycle": "Proposed", + "signatures": [{ + "agent_id": hex::encode(verifying_key.to_bytes()), + "signature": hex::encode(signature.to_bytes()), + "timestamp": timestamp + }], + "source_hash": "0".repeat(64), + "timestamp": timestamp + }) +} + +/// Test full assertion roundtrip: POST → Ingest → GET +/// +/// This test validates the complete pipeline: +/// 1. POST an assertion to /v1/assert (writes to WAL) +/// 2. Run the ingestor to process the WAL entry +/// 3. GET /v1/query to verify the assertion is queryable +#[tokio::test] +async fn test_assertion_roundtrip_with_ingestor() { + let env = create_test_env_with_ingestor().await; + let app = create_router(env.state.clone()); + + let subject = "RoundtripTest_Entity"; + let predicate = "test_property"; + let value = 42.0; + + // 1. POST the assertion + let assertion = create_signed_assertion_json(subject, predicate, value); + + let request = Request::builder() + .uri("/v1/assert") + .method("POST") + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&assertion).unwrap())) + .unwrap(); + + let response = app.clone().oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::CREATED, "POST should succeed with 201"); + + let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let post_result: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(post_result["status"], "created"); + let assertion_hash = post_result["hash"].as_str().expect("hash should be present"); + assert_eq!(assertion_hash.len(), 64, "hash should be 64 hex chars"); + + // 2. Run the ingestor to process the pending record (synchronous for testing) + let bytes_processed = env.ingestor.process_pending().await.expect("ingestor should process"); + assert!(bytes_processed > 0, "Should have processed WAL bytes"); + + // 3. GET the assertion via query + let request = Request::builder() + .uri(format!("/v1/query?subject={}&predicate={}", subject, predicate)) + .method("GET") + .body(Body::empty()) + .unwrap(); + + let response = app.oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + + let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let query_result: serde_json::Value = serde_json::from_slice(&body).unwrap(); + + // Verify the assertion is returned correctly + assert_eq!(query_result["total_count"], 1, "Should find exactly 1 assertion"); + let assertions = query_result["assertions"].as_array().expect("assertions array"); + assert_eq!(assertions.len(), 1); + + let found = &assertions[0]; + assert_eq!(found["subject"], subject); + assert_eq!(found["predicate"], predicate); + assert_eq!(found["object"]["type"], "Number"); + assert!((found["object"]["value"].as_f64().unwrap() - value).abs() < 0.001); + assert_eq!(found["confidence"], 0.95); +} diff --git a/crates/stemedb-core/src/lib.rs b/crates/stemedb-core/src/lib.rs index fa5542d..8ba0723 100644 --- a/crates/stemedb-core/src/lib.rs +++ b/crates/stemedb-core/src/lib.rs @@ -3,6 +3,10 @@ //! This crate defines the fundamental data structures like `Assertion`, //! `SignatureEntry`, and the core traits for the knowledge graph. +/// Zero-copy serialization utilities. +pub mod serde; +/// Shared test helpers (builders, factories) for the workspace. +pub mod testing; /// Core data types for StemeDB assertions and signatures. pub mod types; @@ -14,7 +18,10 @@ pub fn hello_world() -> String { #[cfg(test)] mod tests { use super::*; - use crate::types::{Assertion, Epoch, ObjectValue, SignatureEntry, SupersessionType, Vote}; + use crate::types::{ + Assertion, Epoch, LifecycleStage, ObjectValue, SignatureEntry, SourceClass, Supersession, + SupersessionType, Vote, + }; use rkyv::check_archived_root; use rkyv::ser::serializers::AllocSerializer; use rkyv::ser::Serializer; @@ -33,8 +40,10 @@ mod tests { object: ObjectValue::Number(96.7), parent_hash: None, source_hash: [0u8; 32], + source_class: SourceClass::Clinical, visual_hash: Some([1u8; 8]), epoch: Some([2u8; 32]), + lifecycle: LifecycleStage::Approved, signatures: vec![SignatureEntry { agent_id: [2u8; 32], signature: [3u8; 64], @@ -62,6 +71,58 @@ mod tests { assert_eq!(deserialized.subject, "Tesla_Inc"); assert_eq!(deserialized.visual_hash, Some([1u8; 8])); assert_eq!(deserialized.epoch, Some([2u8; 32])); + assert_eq!(deserialized.lifecycle, LifecycleStage::Approved); + } + + #[test] + fn test_lifecycle_stage_serialization_roundtrip() { + // Test all lifecycle stages survive serialization + let stages = [ + LifecycleStage::Proposed, + LifecycleStage::UnderReview, + LifecycleStage::Approved, + LifecycleStage::Deprecated, + LifecycleStage::Rejected, + ]; + + for stage in stages { + let assertion = Assertion { + subject: "test".to_string(), + predicate: "lifecycle_test".to_string(), + object: ObjectValue::Text(format!("{:?}", stage)), + parent_hash: None, + source_hash: [0u8; 32], + source_class: SourceClass::Expert, + visual_hash: None, + epoch: None, + lifecycle: stage, + signatures: vec![], + confidence: 1.0, + timestamp: 0, + vector: None, + }; + + let mut serializer = AllocSerializer::<4096>::default(); + serializer.serialize_value(&assertion).expect("Failed to serialize"); + let bytes = serializer.into_serializer().into_inner(); + + let archived = check_archived_root::(&bytes) + .expect("Failed to validate archived assertion"); + let deserialized: Assertion = + archived.deserialize(&mut rkyv::Infallible).expect("Failed to deserialize"); + + assert_eq!( + deserialized.lifecycle, stage, + "Lifecycle stage {:?} should survive round-trip", + stage + ); + } + } + + #[test] + fn test_lifecycle_stage_default() { + // Verify that Default gives us Proposed (the safe default) + assert_eq!(LifecycleStage::default(), LifecycleStage::Proposed); } #[test] @@ -93,6 +154,77 @@ mod tests { assert_eq!(deserialized.supersession_type, Some(SupersessionType::Refinement)); } + #[test] + fn test_supersession_serialization_roundtrip() { + let supersession = Supersession { + target_hash: [1u8; 32], + supersession_type: SupersessionType::Invalidate, + reason: "Proposal treated as approved. See incident INC-2024-001".to_string(), + new_hash: Some([2u8; 32]), + timestamp: 1704067200, + agent_id: [3u8; 32], + signature: [4u8; 64], + }; + + // Serialize + let mut serializer = AllocSerializer::<4096>::default(); + serializer.serialize_value(&supersession).expect("Failed to serialize"); + let bytes = serializer.into_serializer().into_inner(); + + // Validate + let archived = check_archived_root::(&bytes) + .expect("Failed to validate archived supersession"); + + // Deserialize + let deserialized: Supersession = + archived.deserialize(&mut rkyv::Infallible).expect("Failed to deserialize"); + + assert_eq!(supersession, deserialized); + assert_eq!(deserialized.target_hash, [1u8; 32]); + assert_eq!(deserialized.supersession_type, SupersessionType::Invalidate); + assert_eq!(deserialized.reason, "Proposal treated as approved. See incident INC-2024-001"); + assert_eq!(deserialized.new_hash, Some([2u8; 32])); + } + + #[test] + fn test_supersession_type_all_variants() { + // Test all supersession types survive serialization + let types = [ + SupersessionType::Invalidate, + SupersessionType::Temporal, + SupersessionType::Refinement, + SupersessionType::RequiresReview, + SupersessionType::Additive, + ]; + + for stype in types { + let supersession = Supersession { + target_hash: [0u8; 32], + supersession_type: stype, + reason: format!("{:?} test", stype), + new_hash: None, + timestamp: 0, + agent_id: [0u8; 32], + signature: [0u8; 64], + }; + + let mut serializer = AllocSerializer::<4096>::default(); + serializer.serialize_value(&supersession).expect("Failed to serialize"); + let bytes = serializer.into_serializer().into_inner(); + + let archived = check_archived_root::(&bytes) + .expect("Failed to validate archived supersession"); + let deserialized: Supersession = + archived.deserialize(&mut rkyv::Infallible).expect("Failed to deserialize"); + + assert_eq!( + deserialized.supersession_type, stype, + "SupersessionType {:?} should survive round-trip", + stype + ); + } + } + #[test] fn test_vote_serialization_roundtrip() { let vote = Vote { diff --git a/crates/stemedb-core/src/serde.rs b/crates/stemedb-core/src/serde.rs new file mode 100644 index 0000000..0bc697c --- /dev/null +++ b/crates/stemedb-core/src/serde.rs @@ -0,0 +1,247 @@ +//! Zero-copy serialization utilities for StemeDB types. +//! +//! This module provides the canonical serialization/deserialization functions +//! for all rkyv-enabled types in the system. **All production code must use +//! these helpers instead of raw `AllocSerializer` usage.** +//! +//! # Design Philosophy +//! +//! Following the "Deep Module" principle, these functions hide the complexity +//! of rkyv's serialization machinery behind simple interfaces. +//! +//! # Example +//! +//! ``` +//! use stemedb_core::serde::{serialize, deserialize}; +//! use stemedb_core::types::Vote; +//! +//! let vote = Vote { +//! assertion_hash: [0u8; 32], +//! agent_id: [1u8; 32], +//! weight: 0.8, +//! signature: [2u8; 64], +//! timestamp: 1000, +//! }; +//! +//! // Serialize +//! let bytes = serialize(&vote).expect("serialization failed"); +//! +//! // Deserialize +//! let recovered: Vote = deserialize(&bytes).expect("deserialization failed"); +//! assert_eq!(vote, recovered); +//! ``` +//! +//! # Performance +//! +//! Uses a 4096-byte scratch buffer which is sufficient for most assertions. +//! Larger payloads will cause reallocation but still work correctly. + +use rkyv::ser::serializers::AllocSerializer; +use rkyv::ser::Serializer; +use rkyv::validation::validators::DefaultValidator; +use rkyv::{Archive, CheckBytes, Deserialize, Serialize}; +use thiserror::Error; + +/// Default scratch buffer size for serialization. +/// +/// 4KB is sufficient for most assertions. Larger payloads will trigger +/// reallocation but the operation will still succeed. +pub const DEFAULT_SCRATCH_SIZE: usize = 4096; + +/// Errors that can occur during serialization/deserialization. +#[derive(Debug, Error)] +pub enum SerdeError { + /// Failed to serialize the value. + #[error("Serialization error: {0}")] + Serialization(String), + /// Failed to validate or deserialize the archived data. + #[error("Deserialization error: {0}")] + Deserialization(String), +} + +/// Serialize a value to bytes using rkyv zero-copy serialization. +/// +/// This is the canonical way to serialize StemeDB types. All production +/// code should use this instead of raw `AllocSerializer`. +/// +/// # Type Requirements +/// +/// The type `T` must implement rkyv's `Serialize` trait, which all StemeDB +/// core types do. +/// +/// # Example +/// +/// ``` +/// use stemedb_core::serde::serialize; +/// use stemedb_core::types::Assertion; +/// # use stemedb_core::types::{ObjectValue, LifecycleStage, SourceClass}; +/// +/// let assertion = Assertion { +/// subject: "test".to_string(), +/// predicate: "is".to_string(), +/// object: ObjectValue::Boolean(true), +/// parent_hash: None, +/// source_hash: [0u8; 32], +/// source_class: SourceClass::Expert, +/// visual_hash: None, +/// epoch: None, +/// lifecycle: LifecycleStage::Proposed, +/// signatures: vec![], +/// confidence: 1.0, +/// timestamp: 0, +/// vector: None, +/// }; +/// +/// let bytes = serialize(&assertion).expect("serialize"); +/// assert!(!bytes.is_empty()); +/// ``` +pub fn serialize(value: &T) -> Result, SerdeError> +where + T: Serialize>, +{ + let mut serializer = AllocSerializer::::default(); + serializer.serialize_value(value).map_err(|e| SerdeError::Serialization(e.to_string()))?; + Ok(serializer.into_serializer().into_inner().to_vec()) +} + +/// Deserialize bytes back to a value using rkyv zero-copy deserialization. +/// +/// This is the canonical way to deserialize StemeDB types. All production +/// code should use this instead of raw `check_archived_root`. +/// +/// # Type Requirements +/// +/// The type `T` must implement rkyv's `Archive` and `Deserialize` traits, +/// and its archived form must implement `CheckBytes` for validation. +/// +/// # Safety +/// +/// This function validates the archived data before deserialization, +/// ensuring memory safety even with untrusted input. +/// +/// # Example +/// +/// ``` +/// use stemedb_core::serde::{serialize, deserialize}; +/// use stemedb_core::types::Vote; +/// +/// let vote = Vote { +/// assertion_hash: [0u8; 32], +/// agent_id: [1u8; 32], +/// weight: 0.8, +/// signature: [2u8; 64], +/// timestamp: 1000, +/// }; +/// +/// let bytes = serialize(&vote).expect("serialize"); +/// let recovered: Vote = deserialize(&bytes).expect("deserialize"); +/// assert_eq!(vote, recovered); +/// ``` +pub fn deserialize(data: &[u8]) -> Result +where + T: Archive, + T::Archived: for<'a> CheckBytes> + Deserialize, +{ + let archived = rkyv::check_archived_root::(data) + .map_err(|e| SerdeError::Deserialization(e.to_string()))?; + + archived + .deserialize(&mut rkyv::Infallible) + .map_err(|e| SerdeError::Deserialization(e.to_string())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::types::{ + Assertion, Epoch, LifecycleStage, ObjectValue, SignatureEntry, SourceClass, Vote, + }; + + #[test] + fn test_serialize_deserialize_assertion() { + let assertion = Assertion { + subject: "Tesla_Inc".to_string(), + predicate: "has_revenue".to_string(), + object: ObjectValue::Number(96.7), + parent_hash: None, + source_hash: [0u8; 32], + source_class: SourceClass::Clinical, + visual_hash: Some([1u8; 8]), + epoch: Some([2u8; 32]), + lifecycle: LifecycleStage::Approved, + signatures: vec![SignatureEntry { + agent_id: [2u8; 32], + signature: [3u8; 64], + timestamp: 123456789, + }], + confidence: 0.95, + timestamp: 123456789, + vector: Some(vec![0.1, 0.2, 0.3]), + }; + + let bytes = serialize(&assertion).expect("serialize"); + let recovered: Assertion = deserialize(&bytes).expect("deserialize"); + assert_eq!(assertion, recovered); + } + + #[test] + fn test_serialize_deserialize_vote() { + let vote = Vote { + assertion_hash: [1u8; 32], + agent_id: [2u8; 32], + weight: 0.8, + signature: [3u8; 64], + timestamp: 123456789, + }; + + let bytes = serialize(&vote).expect("serialize"); + let recovered: Vote = deserialize(&bytes).expect("deserialize"); + assert_eq!(vote, recovered); + } + + #[test] + fn test_serialize_deserialize_epoch() { + let epoch = Epoch { + id: [1u8; 32], + name: "Test Epoch".to_string(), + supersedes: None, + supersession_type: None, + start_timestamp: 1000, + end_timestamp: None, + }; + + let bytes = serialize(&epoch).expect("serialize"); + let recovered: Epoch = deserialize(&bytes).expect("deserialize"); + assert_eq!(epoch, recovered); + } + + #[test] + fn test_deserialize_invalid_data() { + let garbage = vec![0u8, 1, 2, 3, 4, 5]; + let result: Result = deserialize(&garbage); + assert!(result.is_err()); + } + + #[test] + fn test_serialize_empty_assertion() { + let assertion = Assertion { + subject: String::new(), + predicate: String::new(), + object: ObjectValue::Boolean(false), + parent_hash: None, + source_hash: [0u8; 32], + source_class: SourceClass::Expert, + visual_hash: None, + epoch: None, + lifecycle: LifecycleStage::Proposed, + signatures: vec![], + confidence: 0.0, + timestamp: 0, + vector: None, + }; + + let bytes = serialize(&assertion).expect("serialize"); + let recovered: Assertion = deserialize(&bytes).expect("deserialize"); + assert_eq!(assertion, recovered); + } +} diff --git a/crates/stemedb-core/src/testing.rs b/crates/stemedb-core/src/testing.rs new file mode 100644 index 0000000..29fcc43 --- /dev/null +++ b/crates/stemedb-core/src/testing.rs @@ -0,0 +1,320 @@ +//! Shared test helpers for the Episteme workspace. +//! +//! Provides [`AssertionBuilder`] and factory functions to eliminate duplicate +//! test assertion construction across crates. Import via: +//! +//! ```rust,ignore +//! use stemedb_core::testing::{AssertionBuilder, test_vote, test_epoch}; +//! ``` + +use crate::types::{ + Assertion, Epoch, LifecycleStage, ObjectValue, SignatureEntry, SourceClass, SupersessionType, + Vote, +}; + +/// Builder for constructing test [`Assertion`] instances. +/// +/// Every field has a sensible default so callers only override what they need. +/// +/// # Examples +/// +/// ```rust,ignore +/// // Minimal +/// let a = AssertionBuilder::new().build(); +/// +/// // Override subject + timestamp +/// let a = AssertionBuilder::new() +/// .subject("Tesla") +/// .timestamp(2000) +/// .build(); +/// +/// // Full control +/// let a = AssertionBuilder::new() +/// .subject("Tesla") +/// .predicate("revenue") +/// .object_number(96.7) +/// .confidence(0.8) +/// .lifecycle(LifecycleStage::Proposed) +/// .agent_id([5u8; 32]) +/// .timestamp(3000) +/// .build(); +/// ``` +pub struct AssertionBuilder { + subject: String, + predicate: String, + object: ObjectValue, + parent_hash: Option<[u8; 32]>, + source_hash: [u8; 32], + source_class: SourceClass, + visual_hash: Option<[u8; 8]>, + epoch: Option<[u8; 32]>, + lifecycle: LifecycleStage, + signatures: Option>, + agent_id: [u8; 32], + confidence: f32, + timestamp: u64, + vector: Option>, +} + +impl Default for AssertionBuilder { + fn default() -> Self { + Self::new() + } +} + +impl AssertionBuilder { + /// Create a new builder with sensible test defaults. + pub fn new() -> Self { + Self { + subject: "test_subject".to_string(), + predicate: "test_predicate".to_string(), + object: ObjectValue::Number(100.0), + parent_hash: None, + source_hash: [0u8; 32], + source_class: SourceClass::Expert, // Default to middle tier for tests + visual_hash: None, + epoch: None, + lifecycle: LifecycleStage::Approved, + signatures: None, // Will use agent_id to build default + agent_id: [1u8; 32], + confidence: 0.9, + timestamp: 1000, + vector: None, + } + } + + /// Set the subject. + pub fn subject(mut self, subject: &str) -> Self { + self.subject = subject.to_string(); + self + } + + /// Set the predicate. + pub fn predicate(mut self, predicate: &str) -> Self { + self.predicate = predicate.to_string(); + self + } + + /// Set the object to a numeric value. + pub fn object_number(mut self, value: f64) -> Self { + self.object = ObjectValue::Number(value); + self + } + + /// Set the object to a text value. + pub fn object_text(mut self, value: &str) -> Self { + self.object = ObjectValue::Text(value.to_string()); + self + } + + /// Set the object to an arbitrary ObjectValue. + pub fn object(mut self, value: ObjectValue) -> Self { + self.object = value; + self + } + + /// Set the confidence (0.0 to 1.0). + pub fn confidence(mut self, confidence: f32) -> Self { + self.confidence = confidence; + self + } + + /// Set the timestamp. + pub fn timestamp(mut self, timestamp: u64) -> Self { + self.timestamp = timestamp; + self + } + + /// Set the lifecycle stage. + pub fn lifecycle(mut self, lifecycle: LifecycleStage) -> Self { + self.lifecycle = lifecycle; + self + } + + /// Set the agent_id used in the default signature. + pub fn agent_id(mut self, agent_id: [u8; 32]) -> Self { + self.agent_id = agent_id; + self + } + + /// Set the source hash. + pub fn source_hash(mut self, hash: [u8; 32]) -> Self { + self.source_hash = hash; + self + } + + /// Set the source class (authority tier). + pub fn source_class(mut self, source_class: SourceClass) -> Self { + self.source_class = source_class; + self + } + + /// Set the parent hash. + pub fn parent_hash(mut self, hash: [u8; 32]) -> Self { + self.parent_hash = Some(hash); + self + } + + /// Set the visual hash. + pub fn visual_hash(mut self, hash: [u8; 8]) -> Self { + self.visual_hash = Some(hash); + self + } + + /// Set the epoch. + pub fn epoch(mut self, epoch: [u8; 32]) -> Self { + self.epoch = Some(epoch); + self + } + + /// Set the vector embedding. + pub fn vector(mut self, vector: Vec) -> Self { + self.vector = Some(vector); + self + } + + /// Provide explicit signatures (overrides the default single-signature behavior). + pub fn signatures(mut self, signatures: Vec) -> Self { + self.signatures = Some(signatures); + self + } + + /// Build the [`Assertion`]. + pub fn build(self) -> Assertion { + let signatures = self.signatures.unwrap_or_else(|| { + vec![SignatureEntry { + agent_id: self.agent_id, + signature: [2u8; 64], + timestamp: self.timestamp, + }] + }); + + Assertion { + subject: self.subject, + predicate: self.predicate, + object: self.object, + parent_hash: self.parent_hash, + source_hash: self.source_hash, + source_class: self.source_class, + visual_hash: self.visual_hash, + epoch: self.epoch, + lifecycle: self.lifecycle, + signatures, + confidence: self.confidence, + timestamp: self.timestamp, + vector: self.vector, + } + } +} + +/// Create a test [`Vote`] with the given parameters. +pub fn test_vote( + assertion_hash: [u8; 32], + agent_id: [u8; 32], + weight: f32, + timestamp: u64, +) -> Vote { + Vote { assertion_hash, agent_id, weight, signature: [0u8; 64], timestamp } +} + +/// Create a test [`Epoch`] with defaults. +pub fn test_epoch() -> Epoch { + Epoch { + id: [4u8; 32], + name: "Test Epoch".to_string(), + supersedes: None, + supersession_type: None, + start_timestamp: 1000, + end_timestamp: None, + } +} + +/// Create a test [`Epoch`] with a supersession relationship. +pub fn test_epoch_with_supersession( + id: [u8; 32], + name: &str, + supersedes: [u8; 32], + supersession_type: SupersessionType, +) -> Epoch { + Epoch { + id, + name: name.to_string(), + supersedes: Some(supersedes), + supersession_type: Some(supersession_type), + start_timestamp: 1000, + end_timestamp: None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_builder_defaults() { + let a = AssertionBuilder::new().build(); + assert_eq!(a.subject, "test_subject"); + assert_eq!(a.predicate, "test_predicate"); + assert_eq!(a.lifecycle, LifecycleStage::Approved); + assert!((a.confidence - 0.9).abs() < f32::EPSILON); + assert_eq!(a.timestamp, 1000); + assert_eq!(a.signatures.len(), 1); + assert_eq!(a.signatures[0].agent_id, [1u8; 32]); + } + + #[test] + fn test_builder_overrides() { + let a = AssertionBuilder::new() + .subject("Tesla") + .predicate("revenue") + .object_number(96.7) + .confidence(0.85) + .timestamp(5000) + .lifecycle(LifecycleStage::Proposed) + .agent_id([5u8; 32]) + .build(); + + assert_eq!(a.subject, "Tesla"); + assert_eq!(a.predicate, "revenue"); + assert_eq!(a.object, ObjectValue::Number(96.7)); + assert!((a.confidence - 0.85).abs() < f32::EPSILON); + assert_eq!(a.timestamp, 5000); + assert_eq!(a.lifecycle, LifecycleStage::Proposed); + assert_eq!(a.signatures[0].agent_id, [5u8; 32]); + } + + #[test] + fn test_builder_custom_signatures() { + let sigs = vec![ + SignatureEntry { agent_id: [10u8; 32], signature: [11u8; 64], timestamp: 100 }, + SignatureEntry { agent_id: [20u8; 32], signature: [21u8; 64], timestamp: 200 }, + ]; + + let a = AssertionBuilder::new().signatures(sigs).build(); + assert_eq!(a.signatures.len(), 2); + assert_eq!(a.signatures[0].agent_id, [10u8; 32]); + } + + #[test] + fn test_builder_text_object() { + let a = AssertionBuilder::new().object_text("hello").build(); + assert_eq!(a.object, ObjectValue::Text("hello".to_string())); + } + + #[test] + fn test_vote_factory() { + let v = test_vote([1u8; 32], [2u8; 32], 0.8, 3000); + assert_eq!(v.assertion_hash, [1u8; 32]); + assert_eq!(v.agent_id, [2u8; 32]); + assert!((v.weight - 0.8).abs() < f32::EPSILON); + assert_eq!(v.timestamp, 3000); + } + + #[test] + fn test_epoch_factory() { + let e = test_epoch(); + assert_eq!(e.id, [4u8; 32]); + assert_eq!(e.name, "Test Epoch"); + assert!(e.supersedes.is_none()); + } +} diff --git a/crates/stemedb-core/src/types.rs b/crates/stemedb-core/src/types.rs index bdeb589..2d03f4c 100644 --- a/crates/stemedb-core/src/types.rs +++ b/crates/stemedb-core/src/types.rs @@ -15,6 +15,121 @@ pub type RelationId = String; /// A unique identifier for an Epoch (Paradigm). pub type EpochId = Hash; +/// The lifecycle stage of an assertion. +/// +/// Assertions progress through lifecycle stages to distinguish proposals +/// from decisions. This enables queries to filter "production-ready truth" +/// from "work-in-progress speculation." +/// +/// # State Transitions +/// +/// ```text +/// Proposed → UnderReview → Approved → Deprecated +/// ↘ Rejected +/// ``` +/// +/// Transitions are new assertions (append-only), not mutations. +#[derive(Archive, Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq, Default)] +#[archive(check_bytes)] +pub enum LifecycleStage { + /// Initial proposal, idea, or RFC. Safe for research, not for implementation. + #[default] + Proposed, + /// Under active review or debate. Gathering votes and feedback. + UnderReview, + /// Accepted as current truth. Production ready, safe for implementation. + Approved, + /// Was true, now superseded by a newer assertion. Historical reference only. + Deprecated, + /// Considered and explicitly declined. Not to be implemented. + Rejected, +} + +/// Classification of the source's authority and reliability tier. +/// +/// Sources are tiered from most authoritative (Regulatory) to least (Anecdotal). +/// This enables: +/// - **Indexing**: Query "show me only regulatory sources" +/// - **Decay rates**: Anecdotal claims decay faster than clinical evidence +/// - **Trust weighting**: Tier 0 sources carry more weight in conflict resolution +/// +/// # Consumer Health Tiers +/// +/// | Tier | Class | Example | +/// |------|-------|---------| +/// | 0 | Regulatory | FDA approval letters, EMA assessments | +/// | 1 | Clinical | Phase III trials, peer-reviewed RCTs | +/// | 2 | Observational | Real-world evidence, cohort studies | +/// | 3 | Expert | Medical professional opinions, guidelines | +/// | 4 | Community | Curated forums, patient advocacy groups | +/// | 5 | Anecdotal | Reddit posts, individual testimonials | +#[derive(Archive, Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq, Default)] +#[archive(check_bytes)] +pub enum SourceClass { + /// Tier 0: Regulatory bodies (FDA, EMA, WHO). + /// Highest authority. Assertions rarely decay. + Regulatory, + /// Tier 1: Clinical trials, peer-reviewed research. + /// High authority. Slow decay unless superseded by new studies. + Clinical, + /// Tier 2: Observational studies, real-world evidence. + /// Medium-high authority. Moderate decay. + Observational, + /// Tier 3: Expert opinions, medical guidelines. + /// Medium authority. Faster decay as guidelines update. + #[default] + Expert, + /// Tier 4: Curated community knowledge. + /// Medium-low authority. Community-moderated content. + Community, + /// Tier 5: Individual reports, testimonials, social media. + /// Lowest authority. Fast decay, high volume. + Anecdotal, +} + +impl SourceClass { + /// Returns the tier number (0-5) for this source class. + pub fn tier(&self) -> u8 { + match self { + SourceClass::Regulatory => 0, + SourceClass::Clinical => 1, + SourceClass::Observational => 2, + SourceClass::Expert => 3, + SourceClass::Community => 4, + SourceClass::Anecdotal => 5, + } + } + + /// Returns the default decay half-life in days for this source class. + /// + /// Higher tiers decay faster. Regulatory sources essentially never decay, + /// while anecdotal claims have a 30-day half-life. + pub fn default_decay_days(&self) -> Option { + match self { + SourceClass::Regulatory => None, // Never decays + SourceClass::Clinical => Some(730), // 2 years + SourceClass::Observational => Some(365), // 1 year + SourceClass::Expert => Some(180), // 6 months + SourceClass::Community => Some(90), // 3 months + SourceClass::Anecdotal => Some(30), // 1 month + } + } + + /// Returns a weight multiplier for conflict resolution. + /// + /// Used by lenses to weight sources by authority tier. + pub fn authority_weight(&self) -> f32 { + match self { + SourceClass::Regulatory => 1.0, + SourceClass::Clinical => 0.9, + SourceClass::Observational => 0.7, + SourceClass::Expert => 0.5, + SourceClass::Community => 0.3, + SourceClass::Anecdotal => 0.1, + } + } +} + /// The atomic unit of knowledge in StemeDB. #[derive(Archive, Deserialize, Serialize, Debug, Clone, PartialEq)] #[archive(check_bytes)] @@ -32,10 +147,15 @@ pub struct Assertion { pub parent_hash: Option, /// The hash of the source evidence (PDF, URL, Log). pub source_hash: Hash, + /// The authority tier of the source (Regulatory, Clinical, Anecdotal, etc.). + /// Enables indexing by tier and tier-based decay rates. + pub source_class: SourceClass, /// The perceptual hash for visual anchoring (if applicable). pub visual_hash: Option, /// The epoch this assertion belongs to (if any). pub epoch: Option, + /// The lifecycle stage (Proposed, UnderReview, Approved, Deprecated, Rejected). + pub lifecycle: LifecycleStage, // 3. Meta-Cognition (The "Who" and "How sure") /// List of agent signatures vouching for this assertion. @@ -74,16 +194,94 @@ pub struct SignatureEntry { pub timestamp: u64, } -/// Defines the nature of a paradigm shift. -#[derive(Archive, Deserialize, Serialize, Debug, Clone, PartialEq)] +/// Defines the nature of a paradigm shift or error correction. +/// +/// Used for both Epoch supersession and individual Assertion supersession. +/// The type determines how the old knowledge should be treated: +/// +/// # Use Cases +/// +/// | Type | Old Knowledge | New Knowledge | Example | +/// |------|---------------|---------------|---------| +/// | Invalidate | Wrong, hide | Correct | Agent deployed bad config | +/// | Temporal | Was true, historical | Now true | "President is Obama" → "President is Biden" | +/// | Refinement | Simplification | More precise | Newtonian → Relativity | +/// | RequiresReview | Uncertain | Pending | Flagged for human review | +/// | Additive | Still valid | Adds context | Original + clarification | +#[derive(Archive, Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)] #[archive(check_bytes)] pub enum SupersessionType { - /// The old epoch was factually incorrect (e.g., "Earth is flat"). - Invalidation, - /// The old epoch was correct but is now outdated (e.g., "President is Obama"). + /// The old assertion was factually incorrect and should be hidden/ignored. + /// Example: Agent deployed wrong config, need to invalidate that decision. + Invalidate, + /// The old assertion was correct at the time but is now outdated. + /// Example: "President is Obama" (2015) → "President is Biden" (2024). Temporal, - /// The old epoch was a simplification (e.g., Newtonian Physics vs Relativity). + /// The old assertion was a simplification; the new one is more precise. + /// Example: Newtonian Physics → Relativity. Refinement, + /// The old assertion needs human review before trusting. + /// Example: Flagged by automated check, pending supervisor decision. + RequiresReview, + /// The new assertion adds context without invalidating the old one. + /// Example: Original claim + clarifying note. + Additive, +} + +/// A record of one assertion superseding another. +/// +/// Supersession enables error correction without violating append-only semantics. +/// Instead of mutating an assertion, we create a supersession record that points +/// from the old (target) to the new (replacement) assertion. +/// +/// # Storage Layout +/// +/// | Key Pattern | Value | Purpose | +/// |-------------|-------|---------| +/// | `SUP:{target_hash}` | Serialized Supersession | Quick lookup: "Is this superseded?" | +/// | `SUP:IDX:{agent_id}:{timestamp}` | target_hash | Audit: "What did this agent supersede?" | +/// +/// # Use Case: 3am Incident Investigation +/// +/// 1. SRE finds agent deployed bad config +/// 2. Trace shows agent queried assertion X with hash `abc123` +/// 3. Supervisor creates supersession: `abc123` → `new_hash` (Invalidate) +/// 4. Future queries skip `abc123` automatically +/// 5. Audit trail preserved: "Who fixed it? When? Why?" +/// +/// # Example +/// +/// ```ignore +/// let supersession = Supersession { +/// target_hash: bad_assertion_hash, +/// supersession_type: SupersessionType::Invalidate, +/// reason: "Proposal treated as approved. See incident INC-2024-001".to_string(), +/// new_hash: Some(corrected_assertion_hash), +/// timestamp: now(), +/// agent_id: supervisor_public_key, +/// signature: supervisor_signature, +/// }; +/// ``` +#[derive(Archive, Deserialize, Serialize, Debug, Clone, PartialEq)] +#[archive(check_bytes)] +pub struct Supersession { + /// Hash of the assertion being superseded (the "old" or "bad" one). + pub target_hash: Hash, + /// How the target is being superseded. + pub supersession_type: SupersessionType, + /// Human-readable explanation (for audit trail). + /// Example: "Proposal treated as approved. See incident INC-2024-001" + pub reason: String, + /// Hash of the replacement assertion (if any). + /// None for RequiresReview (flagging, not replacing) or pure invalidation. + pub new_hash: Option, + /// Unix timestamp when the supersession was created. + pub timestamp: u64, + /// Ed25519 public key of the agent creating the supersession. + pub agent_id: [u8; 32], + /// Ed25519 signature over the supersession content. + /// Signs: BLAKE3(target_hash || type || reason || new_hash || timestamp) + pub signature: [u8; 64], } /// Represents a distinct period of truth or a specific worldview. @@ -104,6 +302,25 @@ pub struct Epoch { pub end_timestamp: Option, } +/// A pre-computed resolution stored at `MV:{subject}:{predicate}`. +/// +/// The Materializer writes these to enable O(1) reads for standard lenses. +/// Each view captures the winning assertion plus resolution metadata for provenance. +#[derive(Archive, Deserialize, Serialize, Debug, Clone, PartialEq)] +#[archive(check_bytes)] +pub struct MaterializedView { + /// The winning assertion from lens resolution. + pub winner: Assertion, + /// Which lens produced this result (e.g., "VoteAwareConsensus"). + pub lens_name: String, + /// Confidence in the resolution (0.0 to 1.0). + pub resolution_confidence: f32, + /// Number of candidate assertions that were considered. + pub candidates_count: usize, + /// Unix timestamp when this view was last materialized. + pub materialized_at: u64, +} + /// A vote cast by an agent on an existing assertion. /// /// This enables high-velocity consensus gathering without modifying the immutable assertion itself. @@ -121,3 +338,341 @@ pub struct Vote { /// The timestamp when the vote was cast (Unix epoch). pub timestamp: u64, } + +// ============================================================================ +// Query Audit Trail +// ============================================================================ + +/// A unique identifier for a query audit record. +pub type QueryId = Hash; + +/// An audit record for a query operation. +/// +/// Stored at `AUD:{query_id}` to enable "Why did you think that?" debugging. +/// Every read operation is logged with full provenance for incident investigation. +/// +/// # Use Case +/// +/// At 3am, production is broken. An agent deployed wrong config. +/// The SRE needs to know: What did the agent query? What result did it get? +/// What assertions contributed to that answer? +/// +/// # Example +/// +/// ```ignore +/// // Trace an agent's decision +/// GET /v1/audit/queries?agent_id=deployment-agent&from=1704067200 +/// +/// // Get full reasoning trace for a specific query +/// GET /v1/audit/query/{query_id} +/// ``` +#[derive(Archive, Deserialize, Serialize, Debug, Clone, PartialEq)] +#[archive(check_bytes)] +pub struct QueryAudit { + /// Unique identifier for this query (content-addressed hash of serialized params + timestamp). + pub query_id: QueryId, + /// The Ed25519 Public Key of the querying agent (extracted from request header, if present). + pub agent_id: Option<[u8; 32]>, + /// Unix timestamp when the query was executed. + pub timestamp: u64, + /// The query parameters that were used. + pub params: QueryParams, + /// Hash of the winning assertion (None if no results). + pub result_hash: Option, + /// Confidence score of the resolution (0.0 to 1.0). + pub result_confidence: f32, + /// The assertions that contributed to this result, with their influence weights. + pub contributing_assertions: Vec, +} + +/// Query parameters captured for audit purposes. +/// +/// This mirrors the query filters that were applied during resolution. +#[derive(Archive, Deserialize, Serialize, Debug, Clone, PartialEq)] +#[archive(check_bytes)] +pub struct QueryParams { + /// Filter by subject entity. + pub subject: Option, + /// Filter by predicate/relation. + pub predicate: Option, + /// Filter by lifecycle stage. + pub lifecycle: Option, + /// Filter by epoch (if specified). + pub epoch: Option, + /// Which lens was used for conflict resolution. + pub lens: Option, +} + +/// An assertion that contributed to a query result. +/// +/// Captures not just which assertions were considered, but how much +/// each one influenced the final answer. +#[derive(Archive, Deserialize, Serialize, Debug, Clone, PartialEq)] +#[archive(check_bytes)] +pub struct ContributingAssertion { + /// Hash of the assertion. + pub assertion_hash: Hash, + /// How much this assertion influenced the result (0.0 to 1.0). + /// For the winner, this is typically 1.0. + /// For candidates in vote-based lenses, this is the normalized vote weight. + pub weight: f32, + /// Hash of the source evidence for this assertion. + pub source_hash: Hash, + /// Lifecycle stage of this assertion at query time. + pub lifecycle: LifecycleStage, +} + +// ============================================================================ +// Conflict Analysis ("Trust but Verify") +// ============================================================================ + +/// Resolution status indicating the level of agreement among claims. +/// +/// Used by SkepticLens to communicate whether a fact is settled or disputed. +/// +/// # Thresholds +/// +/// Based on normalized Shannon entropy of claim weights: +/// - `Unanimous`: entropy < 0.1 (>95% weight on one claim) +/// - `Agreed`: entropy < 0.4 (~75%+ weight on one claim) +/// - `Contested`: entropy >= 0.4 (significant disagreement) +#[derive(Archive, Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)] +#[archive(check_bytes)] +pub enum ResolutionStatus { + /// All assertions agree on the same value, or near-zero entropy. + Unanimous, + /// Strong majority (>75% weight) agrees on one value. + Agreed, + /// No clear consensus; significant disagreement exists. + Contested, +} + +impl ResolutionStatus { + /// Determine status from conflict score and claim count. + /// + /// # Arguments + /// * `conflict_score` - Normalized Shannon entropy (0.0 to 1.0) + /// * `claim_count` - Number of distinct claims + pub fn from_conflict_score(conflict_score: f32, claim_count: usize) -> Self { + match (conflict_score, claim_count) { + (_, 0 | 1) => ResolutionStatus::Unanimous, + (s, _) if s < 0.1 => ResolutionStatus::Unanimous, + (s, _) if s < 0.4 => ResolutionStatus::Agreed, + _ => ResolutionStatus::Contested, + } + } +} + +/// Result of conflict analysis from SkepticLens. +/// +/// Unlike `Resolution` which picks a winner, `ConflictAnalysis` maps the +/// entire conflict landscape. It answers: "What are the competing claims +/// and how much do they disagree?" +/// +/// # Use Case +/// +/// A medical researcher queries "Semaglutide muscle_effect" and gets: +/// - Status: Contested (conflict_score: 0.72) +/// - Claim A: "Significant loss" (45% weight, 12 sources) +/// - Claim B: "Minimal loss" (35% weight, 3 sources) +/// - Claim C: "No effect" (20% weight, 2 sources) +/// +/// This enables "Trust but Verify" UX where users see the disagreement. +#[derive(Archive, Deserialize, Serialize, Debug, Clone, PartialEq)] +#[archive(check_bytes)] +pub struct ConflictAnalysis { + /// Overall resolution status (Unanimous, Agreed, Contested). + pub status: ResolutionStatus, + /// Conflict score using normalized Shannon entropy. + /// - 0.0 = unanimous (all weight on one claim) + /// - 1.0 = maximum chaos (equal weight across all claims) + pub conflict_score: f32, + /// All distinct claims, ranked by weight_share descending. + pub claims: Vec, + /// Total number of candidate assertions considered. + pub candidates_count: usize, +} + +impl ConflictAnalysis { + /// Create an empty analysis (no candidates). + pub fn empty() -> Self { + Self { + status: ResolutionStatus::Unanimous, + conflict_score: 0.0, + claims: Vec::new(), + candidates_count: 0, + } + } +} + +/// Summary of a single claim (unique object value) in the knowledge base. +/// +/// Groups all assertions that claim the same value for a subject+predicate, +/// providing aggregate statistics for "Trust but Verify" analysis. +#[derive(Archive, Deserialize, Serialize, Debug, Clone, PartialEq)] +#[archive(check_bytes)] +pub struct ClaimSummary { + /// The claimed value (what this group asserts). + pub value: ObjectValue, + /// Normalized weight (0.0 to 1.0) relative to all claims. + /// This is the claim's share of total support, not confidence in the claim. + pub weight_share: f32, + /// Number of assertions making this exact claim. + pub assertion_count: u32, + /// Hash of the highest-confidence assertion for this claim (for drill-down). + pub representative_hash: Hash, + /// Source provenance for the representative assertion. + pub source: SourceSummary, + /// Agents who signed assertions for this claim (for "who said this?"). + pub supporting_agents: Vec, +} + +/// Minimal source info for provenance ("where did this come from?"). +/// +/// Enables the "show me the proof" UX where users can trace a claim +/// back to its original source document. +#[derive(Archive, Deserialize, Serialize, Debug, Clone, PartialEq)] +#[archive(check_bytes)] +pub struct SourceSummary { + /// Hash of the source document (PDF, URL, etc.). + pub source_hash: Hash, + /// Visual anchor hash for the source (e.g., screenshot of table). + pub visual_hash: Option, +} + +/// Minimal agent info for attribution ("who said this?"). +/// +/// Used in ClaimSummary to show which agents support a particular claim. +#[derive(Archive, Deserialize, Serialize, Debug, Clone, PartialEq)] +#[archive(check_bytes)] +pub struct AgentSummary { + /// Agent's Ed25519 public key. + pub agent_id: [u8; 32], + /// Trust score at query time (from TrustRankStore). + /// Range: 0.0 (untrusted) to 1.0 (fully trusted). + pub trust_score: f32, +} + +// ============================================================================ +// TrustPack ("App Store for Trust") +// ============================================================================ + +/// Content-addressed identifier for a TrustPack. +pub type PackId = Hash; + +/// A curated list of trusted agents for filtering consensus. +/// +/// Trust Packs are the "App Store for Trust" - users subscribe to packs +/// curated by domain experts to filter reality through trusted lenses. +/// +/// # Storage Layout +/// +/// | Key Pattern | Value | Purpose | +/// |-------------|-------|---------| +/// | `TP:{pack_id}` | Serialized TrustPack | Pack definition and agent list | +/// +/// # Example +/// +/// ```ignore +/// let pack = TrustPack::new([1u8; 32], "Science_Pack".to_string(), maintainer_key); +/// pack.add_agent(agent_key_1); +/// pack.add_agent(agent_key_2); +/// +/// // Query with pack filter +/// GET /query?lens=Authority&trust_pack=Science_Pack +/// ``` +#[derive(Archive, Deserialize, Serialize, Debug, Clone, PartialEq)] +#[archive(check_bytes)] +pub struct TrustPack { + /// Content-addressed pack ID (BLAKE3 hash). + pub id: PackId, + + /// Human-readable name (e.g., "Mayo_Clinic_Experts"). + pub name: String, + + /// Ed25519 public key of the pack maintainer/curator. + pub maintainer: [u8; 32], + + /// Agent public keys in this pack. + /// Future optimization: Replace with RoaringBitmap for O(1) membership. + pub agents: Vec<[u8; 32]>, + + /// Unix timestamp when pack was created. + pub created_at: u64, + + /// Unix timestamp of last modification. + pub updated_at: u64, +} + +impl TrustPack { + /// Create a new TrustPack with the given ID, name, and maintainer. + /// + /// # Arguments + /// * `id` - Content-addressed pack ID (BLAKE3 hash) + /// * `name` - Human-readable name + /// * `maintainer` - Ed25519 public key of the curator + /// + /// # Returns + /// A new TrustPack with current timestamp and empty agent list + pub fn new(id: PackId, name: String, maintainer: [u8; 32]) -> Self { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + + Self { id, name, maintainer, agents: Vec::new(), created_at: now, updated_at: now } + } + + /// Add an agent to this pack (idempotent). + /// + /// If the agent is already in the pack, this is a no-op. + /// Updates the `updated_at` timestamp. + /// + /// # Arguments + /// * `agent_id` - Ed25519 public key of the agent to add + pub fn add_agent(&mut self, agent_id: [u8; 32]) { + if !self.agents.contains(&agent_id) { + self.agents.push(agent_id); + self.updated_at = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + } + } + + /// Remove an agent from this pack. + /// + /// If the agent is not in the pack, this is a no-op. + /// Updates the `updated_at` timestamp if an agent was removed. + /// + /// # Arguments + /// * `agent_id` - Ed25519 public key of the agent to remove + pub fn remove_agent(&mut self, agent_id: &[u8; 32]) { + if let Some(pos) = self.agents.iter().position(|id| id == agent_id) { + self.agents.remove(pos); + self.updated_at = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + } + } + + /// Check if an agent is a member of this pack. + /// + /// # Arguments + /// * `agent_id` - Ed25519 public key to check + /// + /// # Returns + /// `true` if the agent is in the pack, `false` otherwise + pub fn contains_agent(&self, agent_id: &[u8; 32]) -> bool { + self.agents.contains(agent_id) + } + + /// Get the number of agents in this pack. + /// + /// # Returns + /// The count of agents in the pack + pub fn agent_count(&self) -> usize { + self.agents.len() + } +} diff --git a/crates/stemedb-ingest/Cargo.toml b/crates/stemedb-ingest/Cargo.toml index 062aac7..fb11ce4 100644 --- a/crates/stemedb-ingest/Cargo.toml +++ b/crates/stemedb-ingest/Cargo.toml @@ -12,12 +12,14 @@ workspace = true stemedb-core = { path = "../stemedb-core" } stemedb-wal = { path = "../stemedb-wal" } stemedb-storage = { path = "../stemedb-storage" } -tokio = { version = "1.36", features = ["full"] } +tokio = { version = "1", features = ["full"] } tracing = "0.1" rkyv = { version = "0.7", features = ["validation"] } thiserror = "1.0" blake3 = "1.5" hex = "0.4" +ed25519-dalek = { version = "2.1", features = ["rand_core"] } [dev-dependencies] -tempfile = "3.10" \ No newline at end of file +tempfile = "3.10" +rand = "0.8" \ No newline at end of file diff --git a/crates/stemedb-ingest/src/error.rs b/crates/stemedb-ingest/src/error.rs index 417bdd3..8b16921 100644 --- a/crates/stemedb-ingest/src/error.rs +++ b/crates/stemedb-ingest/src/error.rs @@ -23,4 +23,12 @@ pub enum IngestError { /// Worker task panicked or failed. #[error("Worker error: {0}")] Worker(String), + + /// Invalid cryptographic signature on assertion. + #[error("Invalid signature: {0}")] + InvalidSignature(String), + + /// Input validation failed (e.g., out-of-range values, oversized fields). + #[error("Input validation failed: {0}")] + InputValidation(String), } diff --git a/crates/stemedb-ingest/src/ingestor.rs b/crates/stemedb-ingest/src/ingestor.rs index eed09ac..30ca8a8 100644 --- a/crates/stemedb-ingest/src/ingestor.rs +++ b/crates/stemedb-ingest/src/ingestor.rs @@ -14,11 +14,11 @@ pub struct Ingestor { } impl Ingestor { - /// Create a new Ingestor. - pub fn new(journal: Arc>, store: Arc) -> Self { - let worker = Arc::new(Mutex::new(IngestWorker::new(journal, store))); + /// Create a new Ingestor, loading the persisted cursor if available. + pub async fn new(journal: Arc>, store: Arc) -> Result { + let worker = Arc::new(Mutex::new(IngestWorker::new(journal, store).await?)); debug!("Ingestor created"); - Self { worker, handle: None } + Ok(Self { worker, handle: None }) } /// Start the background ingestion task. diff --git a/crates/stemedb-ingest/src/worker.rs b/crates/stemedb-ingest/src/worker.rs index 59bfd3f..892a8b7 100644 --- a/crates/stemedb-ingest/src/worker.rs +++ b/crates/stemedb-ingest/src/worker.rs @@ -12,15 +12,14 @@ //! - `S:{subject}` - Subject adjacency index (list of assertion hashes) use crate::error::{IngestError, Result}; -use rkyv::ser::serializers::AllocSerializer; -use rkyv::ser::Serializer; -use rkyv::Deserialize; +use ed25519_dalek::{Signature, Verifier, VerifyingKey}; use std::sync::Arc; -use stemedb_core::types::{Assertion, Epoch, Vote}; -use stemedb_storage::KVStore; +use stemedb_core::serde::{deserialize, serialize}; +use stemedb_core::types::{Assertion, Epoch, Hash, Vote}; +use stemedb_storage::{GenericIndexStore, GenericVoteStore, IndexStore, KVStore, VoteStore}; use stemedb_wal::{Journal, HEADER_SIZE}; -use tokio::sync::Mutex; -use tracing::{debug, error, info}; +use tokio::sync::{Mutex, Notify}; +use tracing::{debug, error, info, warn}; /// Record type discriminator. /// @@ -57,9 +56,7 @@ impl TryFrom for RecordType { /// /// Uses an 8-byte header to maintain rkyv alignment requirements. pub fn serialize_assertion(assertion: &Assertion) -> Result> { - let mut serializer = AllocSerializer::<4096>::default(); - serializer.serialize_value(assertion).map_err(|e| IngestError::Serialization(e.to_string()))?; - let bytes = serializer.into_serializer().into_inner(); + let bytes = serialize(assertion).map_err(|e| IngestError::Serialization(e.to_string()))?; let mut payload = Vec::with_capacity(RECORD_HEADER_SIZE + bytes.len()); // 8-byte header: [type, 0, 0, 0, 0, 0, 0, 0] @@ -71,9 +68,7 @@ pub fn serialize_assertion(assertion: &Assertion) -> Result> { /// Serialize a vote with its record type header. pub fn serialize_vote(vote: &Vote) -> Result> { - let mut serializer = AllocSerializer::<4096>::default(); - serializer.serialize_value(vote).map_err(|e| IngestError::Serialization(e.to_string()))?; - let bytes = serializer.into_serializer().into_inner(); + let bytes = serialize(vote).map_err(|e| IngestError::Serialization(e.to_string()))?; let mut payload = Vec::with_capacity(RECORD_HEADER_SIZE + bytes.len()); payload.push(RecordType::Vote as u8); @@ -84,9 +79,7 @@ pub fn serialize_vote(vote: &Vote) -> Result> { /// Serialize an epoch with its record type header. pub fn serialize_epoch(epoch: &Epoch) -> Result> { - let mut serializer = AllocSerializer::<4096>::default(); - serializer.serialize_value(epoch).map_err(|e| IngestError::Serialization(e.to_string()))?; - let bytes = serializer.into_serializer().into_inner(); + let bytes = serialize(epoch).map_err(|e| IngestError::Serialization(e.to_string()))?; let mut payload = Vec::with_capacity(RECORD_HEADER_SIZE + bytes.len()); payload.push(RecordType::Epoch as u8); @@ -95,21 +88,67 @@ pub fn serialize_epoch(epoch: &Epoch) -> Result> { Ok(payload) } +/// Key used to persist the ingestion cursor offset in the KV store. +/// +/// The cursor tracks how far into the WAL the ingestor has processed, +/// allowing recovery to resume from the last checkpoint instead of +/// replaying the entire log. +const CURSOR_KEY: &[u8] = b"__CURSOR__:ingest"; + /// Background worker that tails the WAL and updates the KV store. pub struct IngestWorker { journal: Arc>, store: Arc, + index_store: GenericIndexStore>, + vote_store: GenericVoteStore>, current_offset: u64, + /// Optional notification channel for event-driven materialization. + /// When set, the worker signals this after each successful ingestion + /// so downstream consumers (e.g., the Materializer) can react immediately. + notify: Option>, } -impl IngestWorker { - /// Create a new ingest worker. - pub fn new(journal: Arc>, store: Arc) -> Self { - Self { - journal, - store, - current_offset: HEADER_SIZE as u64, // Skip file header - } +impl IngestWorker { + /// Create a new ingest worker, resuming from the last persisted cursor. + /// + /// If a cursor checkpoint exists in the KV store, the worker resumes + /// from that offset. Otherwise, it starts from the beginning of the WAL + /// (after the file header). + pub async fn new(journal: Arc>, store: Arc) -> Result { + let index_store = GenericIndexStore::new(store.clone()); + let vote_store = GenericVoteStore::new(store.clone()); + let current_offset = match store.get(CURSOR_KEY).await? { + Some(bytes) if bytes.len() == 8 => { + let offset = + u64::from_le_bytes(bytes.try_into().map_err(|_| { + IngestError::Serialization("Invalid cursor bytes".to_string()) + })?); + info!(offset, "Resuming ingestion from persisted cursor"); + offset + } + Some(bytes) => { + warn!( + len = bytes.len(), + "Corrupt cursor value (expected 8 bytes), starting from beginning" + ); + HEADER_SIZE as u64 + } + None => { + debug!("No cursor found, starting from WAL header"); + HEADER_SIZE as u64 + } + }; + Ok(Self { journal, store, index_store, vote_store, current_offset, notify: None }) + } + + /// Attach a notification channel for event-driven downstream consumers. + /// + /// After each successful record ingestion, the worker will signal this + /// `Notify` so consumers like the Materializer can react immediately + /// instead of polling on a fixed interval. + pub fn with_notify(mut self, notify: Arc) -> Self { + self.notify = Some(notify); + self } /// Run a single iteration of the ingestion loop. @@ -151,25 +190,47 @@ impl IngestWorker { RecordType::Epoch => self.ingest_epoch(data).await?, } + let prev_offset = self.current_offset; self.current_offset += bytes_read; + + // Persist the cursor so recovery can skip already-processed records. + // This is safe even if it fails: the write path is idempotent + // (content-addressed keys), so re-processing a record is a no-op. + self.store.put(CURSOR_KEY, &self.current_offset.to_le_bytes()).await?; + info!( record_type = ?record_type, - offset = self.current_offset - bytes_read, + offset = prev_offset, new_offset = self.current_offset, "Ingested record" ); + // Signal downstream consumers (e.g., Materializer) that new data is available + if let Some(ref notify) = self.notify { + notify.notify_one(); + } + Ok(bytes_read) } - /// Ingest an assertion into the KV store. - async fn ingest_assertion(&self, data: &[u8]) -> Result<()> { - let archived = rkyv::check_archived_root::(data) - .map_err(|e| IngestError::Serialization(e.to_string()))?; + /// Maximum allowed subject length in bytes. + const MAX_SUBJECT_LEN: usize = 1024; + /// Maximum allowed predicate length in bytes. + const MAX_PREDICATE_LEN: usize = 256; - let assertion: Assertion = archived - .deserialize(&mut rkyv::Infallible) - .map_err(|e| IngestError::Serialization(e.to_string()))?; + /// Ingest an assertion into the KV store. + /// + /// Validates input bounds and verifies all Ed25519 signatures before storing. + /// Rejects assertions with invalid or missing signatures. + async fn ingest_assertion(&self, data: &[u8]) -> Result<()> { + let assertion: Assertion = + deserialize(data).map_err(|e| IngestError::Serialization(e.to_string()))?; + + // Validate input bounds before proceeding + self.validate_assertion(&assertion)?; + + // Verify all signatures before storing + self.verify_assertion_signatures(&assertion)?; // Content-addressed key: H:{BLAKE3_hash} let hash = blake3::hash(data); @@ -179,54 +240,141 @@ impl IngestWorker { subject = %assertion.subject, predicate = %assertion.predicate, hash = %hash.to_hex(), - "Ingesting assertion" + signature_count = assertion.signatures.len(), + "Ingesting verified assertion" ); // Store the assertion self.store.put(&key, data).await?; - // Update subject index: S:{subject} -> list of assertion hashes - // For now, we store the hash directly (in a real system, this would be a list) - let index_key = format!("S:{}", assertion.subject).into_bytes(); - self.store.put(&index_key, hash.as_bytes()).await?; + // Update indexes: S:{subject} and SP:{subject}:{predicate} + let assertion_hash: Hash = *hash.as_bytes(); + self.index_store + .add_to_indexes(&assertion.subject, &assertion.predicate, &assertion_hash) + .await?; Ok(()) } - /// Ingest a vote into the KV store. + /// Validate assertion input bounds before storage. + /// + /// Rejects assertions with: + /// - Confidence outside [0.0, 1.0] + /// - Subject exceeding MAX_SUBJECT_LEN bytes + /// - Predicate exceeding MAX_PREDICATE_LEN bytes + fn validate_assertion(&self, assertion: &Assertion) -> Result<()> { + if assertion.confidence < 0.0 || assertion.confidence > 1.0 { + return Err(IngestError::InputValidation(format!( + "confidence {} out of range [0.0, 1.0]", + assertion.confidence + ))); + } + + if assertion.subject.len() > Self::MAX_SUBJECT_LEN { + return Err(IngestError::InputValidation(format!( + "subject exceeds {} bytes (got {})", + Self::MAX_SUBJECT_LEN, + assertion.subject.len() + ))); + } + + if assertion.predicate.len() > Self::MAX_PREDICATE_LEN { + return Err(IngestError::InputValidation(format!( + "predicate exceeds {} bytes (got {})", + Self::MAX_PREDICATE_LEN, + assertion.predicate.len() + ))); + } + + Ok(()) + } + + /// Verify all Ed25519 signatures on an assertion. + /// + /// The message being signed is `"{subject}:{predicate}"`. + /// All signatures must be valid for the assertion to be accepted. + fn verify_assertion_signatures(&self, assertion: &Assertion) -> Result<()> { + if assertion.signatures.is_empty() { + warn!( + subject = %assertion.subject, + predicate = %assertion.predicate, + "Assertion has no signatures" + ); + return Err(IngestError::InvalidSignature( + "Assertion must have at least one signature".to_string(), + )); + } + + // The signed message is the subject:predicate pair + let message = format!("{}:{}", assertion.subject, assertion.predicate); + let message_bytes = message.as_bytes(); + + for (idx, sig_entry) in assertion.signatures.iter().enumerate() { + // Reconstruct the verifying key from the stored agent_id + let verifying_key = VerifyingKey::from_bytes(&sig_entry.agent_id).map_err(|e| { + IngestError::InvalidSignature(format!( + "Invalid public key for signature {}: {}", + idx, e + )) + })?; + + // Reconstruct the signature + let signature = Signature::from_bytes(&sig_entry.signature); + + // Verify the signature + verifying_key.verify(message_bytes, &signature).map_err(|e| { + IngestError::InvalidSignature(format!( + "Signature {} failed verification: {}", + idx, e + )) + })?; + + debug!( + agent_id = %hex::encode(&sig_entry.agent_id[..8]), + signature_idx = idx, + "Signature verified" + ); + } + + Ok(()) + } + + /// Ingest a vote into the KV store via VoteStore. + /// + /// Validates vote weight bounds and uses VoteStore to maintain vote count + /// and aggregate weight caches automatically. This ensures + /// VoteAwareConsensusLens has accurate data. async fn ingest_vote(&self, data: &[u8]) -> Result<()> { - let archived = rkyv::check_archived_root::(data) - .map_err(|e| IngestError::Serialization(e.to_string()))?; + let vote: Vote = + deserialize(data).map_err(|e| IngestError::Serialization(e.to_string()))?; - let vote: Vote = archived - .deserialize(&mut rkyv::Infallible) - .map_err(|e| IngestError::Serialization(e.to_string()))?; - - // Vote key: V:{assertion_hash}:{vote_hash} - let vote_hash = blake3::hash(data); - let assertion_hash_hex = hex::encode(vote.assertion_hash); - let key = format!("V:{}:{}", assertion_hash_hex, vote_hash.to_hex()).into_bytes(); + // Validate vote weight bounds + if vote.weight < 0.0 || vote.weight > 1.0 { + return Err(IngestError::InputValidation(format!( + "weight {} out of range [0.0, 1.0]", + vote.weight + ))); + } debug!( - assertion_hash = %assertion_hash_hex, - vote_hash = %vote_hash.to_hex(), + assertion_hash = %hex::encode(vote.assertion_hash), weight = vote.weight, - "Ingesting vote" + "Ingesting vote via VoteStore" ); - self.store.put(&key, data).await?; + // Delegate to VoteStore which handles: + // 1. Content-addressed storage at V:{assertion_hash}:{vote_hash} + // 2. Vote count cache at VC:{assertion_hash} + // 3. Aggregate weight cache at VW:{assertion_hash} + self.vote_store.put_vote(&vote).await?; Ok(()) } /// Ingest an epoch into the KV store. async fn ingest_epoch(&self, data: &[u8]) -> Result<()> { - let archived = rkyv::check_archived_root::(data) - .map_err(|e| IngestError::Serialization(e.to_string()))?; - - let epoch: Epoch = archived - .deserialize(&mut rkyv::Infallible) - .map_err(|e| IngestError::Serialization(e.to_string()))?; + let epoch: Epoch = + deserialize(data).map_err(|e| IngestError::Serialization(e.to_string()))?; // Epoch key: E:{epoch_id_hash} let epoch_id_hex = hex::encode(epoch.id); @@ -267,50 +415,52 @@ impl IngestWorker { #[cfg(test)] mod tests { use super::*; - use stemedb_core::types::{ObjectValue, SignatureEntry}; + use ed25519_dalek::{Signer, SigningKey}; + use rand::rngs::OsRng; + use stemedb_core::testing::{self, AssertionBuilder}; + use stemedb_core::types::{LifecycleStage, ObjectValue, SignatureEntry, SourceClass}; use stemedb_storage::SledStore; use stemedb_wal::Journal; use tempfile::tempdir; + /// Create a properly signed test assertion. + /// + /// Generates a fresh Ed25519 keypair and signs the subject:predicate message. fn create_test_assertion() -> Assertion { - Assertion { - subject: "Tesla_Inc".to_string(), - predicate: "has_revenue".to_string(), - object: ObjectValue::Number(96.7), - parent_hash: None, - source_hash: [0u8; 32], - visual_hash: None, - epoch: None, - signatures: vec![SignatureEntry { - agent_id: [1u8; 32], - signature: [2u8; 64], + create_signed_assertion("Tesla_Inc", "has_revenue") + } + + /// Create a signed assertion with custom subject and predicate. + fn create_signed_assertion(subject: &str, predicate: &str) -> Assertion { + let mut csprng = OsRng; + let signing_key = SigningKey::generate(&mut csprng); + let verifying_key = signing_key.verifying_key(); + + let message = format!("{}:{}", subject, predicate); + let signature = signing_key.sign(message.as_bytes()); + + AssertionBuilder::new() + .subject(subject) + .predicate(predicate) + .object_number(96.7) + .confidence(0.95) + .lifecycle(LifecycleStage::Proposed) + .signatures(vec![SignatureEntry { + agent_id: verifying_key.to_bytes(), + signature: signature.to_bytes(), timestamp: 1000, - }], - confidence: 0.95, - timestamp: 1000, - vector: None, - } + }]) + .build() } fn create_test_vote() -> Vote { - Vote { - assertion_hash: [1u8; 32], - agent_id: [2u8; 32], - weight: 0.8, - signature: [3u8; 64], - timestamp: 2000, - } + testing::test_vote([1u8; 32], [2u8; 32], 0.8, 2000) } fn create_test_epoch() -> Epoch { - Epoch { - id: [4u8; 32], - name: "Test Epoch".to_string(), - supersedes: None, - supersession_type: None, - start_timestamp: 3000, - end_timestamp: None, - } + let mut epoch = testing::test_epoch(); + epoch.start_timestamp = 3000; + epoch } #[tokio::test] @@ -331,7 +481,8 @@ mod tests { // Create worker and process let journal = Arc::new(Mutex::new(journal)); let store = Arc::new(store); - let mut worker = IngestWorker::new(journal, store.clone()); + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("Failed to create worker"); let bytes = worker.step().await.expect("Failed to step"); assert!(bytes > 0, "Should have processed data"); @@ -360,7 +511,8 @@ mod tests { let journal = Arc::new(Mutex::new(journal)); let store = Arc::new(store); - let mut worker = IngestWorker::new(journal, store.clone()); + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("Failed to create worker"); let bytes = worker.step().await.expect("Failed to step"); assert!(bytes > 0); @@ -385,7 +537,8 @@ mod tests { let journal = Arc::new(Mutex::new(journal)); let store = Arc::new(store); - let mut worker = IngestWorker::new(journal, store.clone()); + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("Failed to create worker"); let bytes = worker.step().await.expect("Failed to step"); assert!(bytes > 0); @@ -415,7 +568,8 @@ mod tests { let journal = Arc::new(Mutex::new(journal)); let store = Arc::new(store); - let mut worker = IngestWorker::new(journal, store.clone()); + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("Failed to create worker"); // Process all records let mut total = 0; @@ -476,7 +630,8 @@ mod tests { let journal = Arc::new(Mutex::new(journal)); let store = Arc::new(store); - let mut worker = IngestWorker::new(journal, store.clone()); + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("Failed to create worker"); // Process all pending records loop { @@ -525,7 +680,8 @@ mod tests { let journal = Arc::new(Mutex::new(journal)); let store = Arc::new(store); - let mut worker = IngestWorker::new(journal, store.clone()); + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("Failed to create worker"); // Ingest all records while worker.step().await.expect("step") > 0 {} @@ -557,8 +713,9 @@ mod tests { // Write new data and crash { let mut journal = Journal::open(&wal_dir).expect("Failed to open journal"); - let mut assertion = create_test_assertion(); - assertion.subject = format!("Subject_Cycle_{}", cycle); + // Create a properly signed assertion for each cycle + let assertion = + create_signed_assertion(&format!("Subject_Cycle_{}", cycle), "has_property"); journal.append(serialize_assertion(&assertion).expect("ser")).expect("append"); } @@ -569,7 +726,9 @@ mod tests { let journal = Arc::new(Mutex::new(journal)); let store = Arc::new(store); - let mut worker = IngestWorker::new(journal, store.clone()); + let mut worker = IngestWorker::new(journal, store.clone()) + .await + .expect("Failed to create worker"); while worker.step().await.expect("step") > 0 {} @@ -616,7 +775,8 @@ mod tests { let journal = Arc::new(Mutex::new(journal)); let store = Arc::new(store); - let mut worker = IngestWorker::new(journal, store.clone()); + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("Failed to create worker"); while worker.step().await.expect("step") > 0 {} @@ -631,4 +791,679 @@ mod tests { assert_eq!(assertions.len(), 1, "Assertion should persist in KV store across restarts"); } } + + // ======================================================================== + // SIGNATURE VERIFICATION TESTS + // ======================================================================== + + /// Test: Assertions with invalid signatures are rejected. + #[tokio::test] + async fn test_rejects_invalid_signature() { + let dir = tempdir().expect("Failed to create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + // Create an assertion with an invalid signature (all zeros) + let assertion = Assertion { + subject: "Test".to_string(), + predicate: "invalid_sig".to_string(), + object: ObjectValue::Text("test".to_string()), + parent_hash: None, + source_hash: [0u8; 32], + source_class: SourceClass::Expert, + visual_hash: None, + epoch: None, + lifecycle: LifecycleStage::Proposed, + signatures: vec![SignatureEntry { + agent_id: [1u8; 32], // Invalid: not a valid Ed25519 public key + signature: [2u8; 64], // Invalid: not a valid signature + timestamp: 1000, + }], + confidence: 0.95, + timestamp: 1000, + vector: None, + }; + + let mut journal = Journal::open(&wal_dir).expect("Failed to open journal"); + let store = SledStore::open(&db_dir).expect("Failed to open store"); + + journal.append(serialize_assertion(&assertion).expect("ser")).expect("append"); + + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(store); + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("Failed to create worker"); + + // Step should fail with InvalidSignature error + let result = worker.step().await; + assert!(result.is_err(), "Should reject invalid signature"); + + let err = result.unwrap_err(); + assert!( + matches!(err, IngestError::InvalidSignature(_)), + "Error should be InvalidSignature, got: {:?}", + err + ); + + // Verify no assertion was stored + let assertions = store.scan_prefix(b"H:").await.expect("scan"); + assert_eq!(assertions.len(), 0, "No assertion should be stored"); + } + + /// Test: Assertions with no signatures are rejected. + #[tokio::test] + async fn test_rejects_unsigned_assertion() { + let dir = tempdir().expect("Failed to create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + // Create an assertion with no signatures + let assertion = Assertion { + subject: "Test".to_string(), + predicate: "unsigned".to_string(), + object: ObjectValue::Text("test".to_string()), + parent_hash: None, + source_hash: [0u8; 32], + source_class: SourceClass::Expert, + visual_hash: None, + epoch: None, + lifecycle: LifecycleStage::Proposed, + signatures: vec![], // No signatures! + confidence: 0.95, + timestamp: 1000, + vector: None, + }; + + let mut journal = Journal::open(&wal_dir).expect("Failed to open journal"); + let store = SledStore::open(&db_dir).expect("Failed to open store"); + + journal.append(serialize_assertion(&assertion).expect("ser")).expect("append"); + + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(store); + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("Failed to create worker"); + + let result = worker.step().await; + assert!(result.is_err(), "Should reject unsigned assertion"); + + let err = result.unwrap_err(); + assert!( + matches!(err, IngestError::InvalidSignature(_)), + "Error should be InvalidSignature, got: {:?}", + err + ); + } + + /// Test: Multi-signature assertions require all signatures to be valid. + #[tokio::test] + async fn test_multisig_all_must_be_valid() { + let dir = tempdir().expect("Failed to create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + // Create an assertion with one valid and one invalid signature + let mut csprng = OsRng; + let signing_key = SigningKey::generate(&mut csprng); + let verifying_key = signing_key.verifying_key(); + let message = "Test:multisig"; + let valid_signature = signing_key.sign(message.as_bytes()); + + let assertion = Assertion { + subject: "Test".to_string(), + predicate: "multisig".to_string(), + object: ObjectValue::Text("test".to_string()), + parent_hash: None, + source_hash: [0u8; 32], + source_class: SourceClass::Expert, + visual_hash: None, + epoch: None, + lifecycle: LifecycleStage::Proposed, + signatures: vec![ + // Valid signature + SignatureEntry { + agent_id: verifying_key.to_bytes(), + signature: valid_signature.to_bytes(), + timestamp: 1000, + }, + // Invalid signature + SignatureEntry { agent_id: [1u8; 32], signature: [2u8; 64], timestamp: 1001 }, + ], + confidence: 0.95, + timestamp: 1000, + vector: None, + }; + + let mut journal = Journal::open(&wal_dir).expect("Failed to open journal"); + let store = SledStore::open(&db_dir).expect("Failed to open store"); + + journal.append(serialize_assertion(&assertion).expect("ser")).expect("append"); + + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(store); + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("Failed to create worker"); + + let result = worker.step().await; + assert!(result.is_err(), "Should reject when any signature is invalid"); + } + + // ======================================================================== + // PERSISTENT CURSOR TESTS + // ======================================================================== + + /// Test: Cursor is persisted after ingestion and restored on restart. + /// + /// After ingesting records, a new worker should resume from where the + /// previous one left off instead of replaying the entire WAL. + #[tokio::test] + async fn test_cursor_persists_across_restarts() { + let dir = tempdir().expect("Failed to create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + let mut journal = Journal::open(&wal_dir).expect("Failed to open journal"); + let store = SledStore::open(&db_dir).expect("Failed to open store"); + + // Write two assertions to the WAL + let a1 = create_signed_assertion("Entity_A", "has_prop"); + let a2 = create_signed_assertion("Entity_B", "has_prop"); + journal.append(serialize_assertion(&a1).expect("ser")).expect("append"); + journal.append(serialize_assertion(&a2).expect("ser")).expect("append"); + + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(store); + + // Worker 1: ingest both records + { + let mut worker = + IngestWorker::new(journal.clone(), store.clone()).await.expect("create worker"); + while worker.step().await.expect("step") > 0 {} + } + + // Worker 2: should have nothing to process (cursor was persisted) + { + let mut worker = + IngestWorker::new(journal.clone(), store.clone()).await.expect("create worker"); + let bytes = worker.step().await.expect("step"); + assert_eq!(bytes, 0, "Second worker should find no new records"); + } + + // Verify both assertions are present + let assertions = store.scan_prefix(b"H:").await.expect("scan"); + assert_eq!(assertions.len(), 2, "Both assertions should exist"); + } + + /// Test: Crash recovery with persistent cursor only processes new records. + /// + /// Simulates: write 2 records -> ingest -> crash -> write 1 more -> recover. + /// The recovery should only process the new record, not replay the first two. + #[tokio::test] + async fn test_crash_recovery_resumes_from_cursor() { + let dir = tempdir().expect("Failed to create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + // Phase 1: Write and ingest 2 records + { + let mut journal = Journal::open(&wal_dir).expect("open journal"); + let store = SledStore::open(&db_dir).expect("open store"); + + let a1 = create_signed_assertion("Phase1_A", "prop"); + let a2 = create_signed_assertion("Phase1_B", "prop"); + journal.append(serialize_assertion(&a1).expect("ser")).expect("append"); + journal.append(serialize_assertion(&a2).expect("ser")).expect("append"); + + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(store); + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("create worker"); + while worker.step().await.expect("step") > 0 {} + + store.flush().await.expect("flush"); + // Drop everything — simulates crash + } + + // Phase 2: Write 1 more record to WAL, then recover + { + let mut journal = Journal::open(&wal_dir).expect("reopen journal"); + let a3 = create_signed_assertion("Phase2_C", "prop"); + journal.append(serialize_assertion(&a3).expect("ser")).expect("append"); + + let store = SledStore::open(&db_dir).expect("reopen store"); + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(store); + + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("create worker"); + + // Should only process the ONE new record from Phase 2 + let mut steps = 0; + while worker.step().await.expect("step") > 0 { + steps += 1; + } + assert_eq!(steps, 1, "Should only process the one new record, not replay all 3"); + + // All 3 assertions should be present + let assertions = store.scan_prefix(b"H:").await.expect("scan"); + assert_eq!(assertions.len(), 3, "All 3 assertions should be present"); + } + } + + /// Test: Partial crash recovery verifies cursor offset precisely. + /// + /// This test is more explicit about verifying cursor behavior: + /// 1. Writes 5 assertions to WAL + /// 2. Ingests only 2 (calls step() twice, not run()) + /// 3. Records cursor offset + /// 4. Drops worker (simulates crash) + /// 5. Creates new worker + /// 6. Verifies new worker resumes from exact cursor position + /// 7. Ingests remaining 3 + /// 8. Verifies total 5 assertions in storage + #[tokio::test] + async fn test_cursor_partial_crash_recovery() { + let dir = tempdir().expect("Failed to create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + let mut journal = Journal::open(&wal_dir).expect("Failed to open journal"); + let store = SledStore::open(&db_dir).expect("Failed to open store"); + + // Write 5 assertions to the WAL + let assertions: Vec = + (0..5).map(|i| create_signed_assertion(&format!("Entity_{}", i), "property")).collect(); + + for assertion in &assertions { + journal.append(serialize_assertion(assertion).expect("ser")).expect("append"); + } + + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(store); + + // Create worker and ingest only 2 records + let cursor_after_two = { + let mut worker = + IngestWorker::new(journal.clone(), store.clone()).await.expect("create worker"); + + // Step 1 + let bytes1 = worker.step().await.expect("step 1"); + assert!(bytes1 > 0, "First step should process data"); + + // Step 2 + let bytes2 = worker.step().await.expect("step 2"); + assert!(bytes2 > 0, "Second step should process data"); + + // Worker dropped here - simulates crash + worker.current_offset + }; + + // Verify exactly 2 assertions in store + let stored_count = store.scan_prefix(b"H:").await.expect("scan").len(); + assert_eq!(stored_count, 2, "Should have exactly 2 assertions after partial ingestion"); + + // Create new worker and verify it resumes from correct cursor + { + let mut worker = + IngestWorker::new(journal.clone(), store.clone()).await.expect("create new worker"); + + // Verify cursor matches what we recorded + assert_eq!( + worker.current_offset, cursor_after_two, + "New worker should resume from cursor offset {} (got {})", + cursor_after_two, worker.current_offset + ); + + // Ingest remaining 3 records + let mut remaining_steps = 0; + loop { + let bytes = worker.step().await.expect("step"); + if bytes == 0 { + break; + } + remaining_steps += 1; + } + + assert_eq!(remaining_steps, 3, "Should have processed exactly 3 remaining records"); + } + + // Verify all 5 assertions are now in store + let final_count = store.scan_prefix(b"H:").await.expect("scan").len(); + assert_eq!(final_count, 5, "All 5 assertions should be in store after full recovery"); + + // Verify subject indexes for all 5 entities + for i in 0..5 { + let prefix = format!("S:Entity_{}", i); + let indexes = store.scan_prefix(prefix.as_bytes()).await.expect("scan"); + assert_eq!(indexes.len(), 1, "Entity_{} should have 1 index entry", i); + } + } + + /// Test: Cursor value is stored correctly in the KV store. + #[tokio::test] + async fn test_cursor_stored_in_kv() { + let dir = tempdir().expect("Failed to create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + let mut journal = Journal::open(&wal_dir).expect("Failed to open journal"); + let store = SledStore::open(&db_dir).expect("Failed to open store"); + + let assertion = create_test_assertion(); + journal.append(serialize_assertion(&assertion).expect("ser")).expect("append"); + + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(store); + + // Before ingestion: no cursor + let cursor_before = store.get(CURSOR_KEY).await.expect("get"); + assert!(cursor_before.is_none(), "No cursor should exist before ingestion"); + + // After ingestion: cursor should be set + let mut worker = IngestWorker::new(journal, store.clone()).await.expect("create worker"); + worker.step().await.expect("step"); + + let cursor_after = store.get(CURSOR_KEY).await.expect("get"); + assert!(cursor_after.is_some(), "Cursor should exist after ingestion"); + + let offset_bytes = cursor_after.expect("cursor should be present"); + let offset = u64::from_le_bytes(offset_bytes.try_into().expect("cursor should be 8 bytes")); + assert!(offset > HEADER_SIZE as u64, "Cursor should be beyond header: got {}", offset); + } + + // ======================================================================== + // INPUT VALIDATION TESTS + // ======================================================================== + + /// Test: Assertions with out-of-range confidence are rejected. + #[tokio::test] + async fn test_rejects_invalid_confidence() { + let dir = tempdir().expect("Failed to create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + // Create assertion with confidence > 1.0 + let mut csprng = OsRng; + let signing_key = SigningKey::generate(&mut csprng); + let verifying_key = signing_key.verifying_key(); + let message = "Test:invalid_confidence"; + let signature = signing_key.sign(message.as_bytes()); + + let assertion = Assertion { + subject: "Test".to_string(), + predicate: "invalid_confidence".to_string(), + object: ObjectValue::Text("test".to_string()), + parent_hash: None, + source_hash: [0u8; 32], + source_class: SourceClass::Expert, + visual_hash: None, + epoch: None, + lifecycle: LifecycleStage::Proposed, + signatures: vec![SignatureEntry { + agent_id: verifying_key.to_bytes(), + signature: signature.to_bytes(), + timestamp: 1000, + }], + confidence: 1.5, // Invalid: > 1.0 + timestamp: 1000, + vector: None, + }; + + let mut journal = Journal::open(&wal_dir).expect("Failed to open journal"); + let store = SledStore::open(&db_dir).expect("Failed to open store"); + + journal.append(serialize_assertion(&assertion).expect("ser")).expect("append"); + + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(store); + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("Failed to create worker"); + + let result = worker.step().await; + assert!(result.is_err(), "Should reject confidence > 1.0"); + + let err = result.unwrap_err(); + assert!( + matches!(err, IngestError::InputValidation(_)), + "Error should be InputValidation, got: {:?}", + err + ); + assert!(err.to_string().contains("confidence")); + } + + /// Test: Assertions with negative confidence are rejected. + #[tokio::test] + async fn test_rejects_negative_confidence() { + let dir = tempdir().expect("Failed to create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + let mut csprng = OsRng; + let signing_key = SigningKey::generate(&mut csprng); + let verifying_key = signing_key.verifying_key(); + let message = "Test:negative"; + let signature = signing_key.sign(message.as_bytes()); + + let assertion = Assertion { + subject: "Test".to_string(), + predicate: "negative".to_string(), + object: ObjectValue::Text("test".to_string()), + parent_hash: None, + source_hash: [0u8; 32], + source_class: SourceClass::Expert, + visual_hash: None, + epoch: None, + lifecycle: LifecycleStage::Proposed, + signatures: vec![SignatureEntry { + agent_id: verifying_key.to_bytes(), + signature: signature.to_bytes(), + timestamp: 1000, + }], + confidence: -0.5, // Invalid: < 0.0 + timestamp: 1000, + vector: None, + }; + + let mut journal = Journal::open(&wal_dir).expect("Failed to open journal"); + let store = SledStore::open(&db_dir).expect("Failed to open store"); + + journal.append(serialize_assertion(&assertion).expect("ser")).expect("append"); + + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(store); + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("Failed to create worker"); + + let result = worker.step().await; + assert!(result.is_err(), "Should reject confidence < 0.0"); + + let err = result.unwrap_err(); + assert!(matches!(err, IngestError::InputValidation(_))); + } + + /// Test: Votes with out-of-range weight are rejected. + #[tokio::test] + async fn test_rejects_invalid_vote_weight() { + let dir = tempdir().expect("Failed to create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + // Create vote with weight > 1.0 + let vote = Vote { + assertion_hash: [1u8; 32], + agent_id: [2u8; 32], + weight: 1.5, // Invalid: > 1.0 + signature: [3u8; 64], + timestamp: 1000, + }; + + let mut journal = Journal::open(&wal_dir).expect("Failed to open journal"); + let store = SledStore::open(&db_dir).expect("Failed to open store"); + + journal.append(serialize_vote(&vote).expect("ser")).expect("append"); + + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(store); + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("Failed to create worker"); + + let result = worker.step().await; + assert!(result.is_err(), "Should reject vote weight > 1.0"); + + let err = result.unwrap_err(); + assert!( + matches!(err, IngestError::InputValidation(_)), + "Error should be InputValidation, got: {:?}", + err + ); + assert!(err.to_string().contains("weight")); + } + + /// Test: Votes with negative weight are rejected. + #[tokio::test] + async fn test_rejects_negative_vote_weight() { + let dir = tempdir().expect("Failed to create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + let vote = Vote { + assertion_hash: [1u8; 32], + agent_id: [2u8; 32], + weight: -0.5, // Invalid: < 0.0 + signature: [3u8; 64], + timestamp: 1000, + }; + + let mut journal = Journal::open(&wal_dir).expect("Failed to open journal"); + let store = SledStore::open(&db_dir).expect("Failed to open store"); + + journal.append(serialize_vote(&vote).expect("ser")).expect("append"); + + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(store); + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("Failed to create worker"); + + let result = worker.step().await; + assert!(result.is_err(), "Should reject vote weight < 0.0"); + + let err = result.unwrap_err(); + assert!(matches!(err, IngestError::InputValidation(_))); + } + + /// Test: Assertions with oversized subject are rejected. + #[tokio::test] + async fn test_rejects_oversized_subject() { + let dir = tempdir().expect("Failed to create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + // Create a subject that exceeds MAX_SUBJECT_LEN (1024 bytes) + let oversized_subject = "x".repeat(1025); + + let mut csprng = OsRng; + let signing_key = SigningKey::generate(&mut csprng); + let verifying_key = signing_key.verifying_key(); + let message = format!("{}:pred", oversized_subject); + let signature = signing_key.sign(message.as_bytes()); + + let assertion = Assertion { + subject: oversized_subject, + predicate: "pred".to_string(), + object: ObjectValue::Text("test".to_string()), + parent_hash: None, + source_hash: [0u8; 32], + source_class: SourceClass::Expert, + visual_hash: None, + epoch: None, + lifecycle: LifecycleStage::Proposed, + signatures: vec![SignatureEntry { + agent_id: verifying_key.to_bytes(), + signature: signature.to_bytes(), + timestamp: 1000, + }], + confidence: 0.9, + timestamp: 1000, + vector: None, + }; + + let mut journal = Journal::open(&wal_dir).expect("Failed to open journal"); + let store = SledStore::open(&db_dir).expect("Failed to open store"); + + journal.append(serialize_assertion(&assertion).expect("ser")).expect("append"); + + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(store); + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("Failed to create worker"); + + let result = worker.step().await; + assert!(result.is_err(), "Should reject oversized subject"); + + let err = result.unwrap_err(); + assert!( + matches!(err, IngestError::InputValidation(_)), + "Error should be InputValidation, got: {:?}", + err + ); + assert!(err.to_string().contains("subject")); + } + + /// Test: Assertions with oversized predicate are rejected. + #[tokio::test] + async fn test_rejects_oversized_predicate() { + let dir = tempdir().expect("Failed to create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + // Create a predicate that exceeds MAX_PREDICATE_LEN (256 bytes) + let oversized_predicate = "y".repeat(257); + + let mut csprng = OsRng; + let signing_key = SigningKey::generate(&mut csprng); + let verifying_key = signing_key.verifying_key(); + let message = format!("subj:{}", oversized_predicate); + let signature = signing_key.sign(message.as_bytes()); + + let assertion = Assertion { + subject: "subj".to_string(), + predicate: oversized_predicate, + object: ObjectValue::Text("test".to_string()), + parent_hash: None, + source_hash: [0u8; 32], + source_class: SourceClass::Expert, + visual_hash: None, + epoch: None, + lifecycle: LifecycleStage::Proposed, + signatures: vec![SignatureEntry { + agent_id: verifying_key.to_bytes(), + signature: signature.to_bytes(), + timestamp: 1000, + }], + confidence: 0.9, + timestamp: 1000, + vector: None, + }; + + let mut journal = Journal::open(&wal_dir).expect("Failed to open journal"); + let store = SledStore::open(&db_dir).expect("Failed to open store"); + + journal.append(serialize_assertion(&assertion).expect("ser")).expect("append"); + + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(store); + let mut worker = + IngestWorker::new(journal, store.clone()).await.expect("Failed to create worker"); + + let result = worker.step().await; + assert!(result.is_err(), "Should reject oversized predicate"); + + let err = result.unwrap_err(); + assert!( + matches!(err, IngestError::InputValidation(_)), + "Error should be InputValidation, got: {:?}", + err + ); + assert!(err.to_string().contains("predicate")); + } } diff --git a/crates/stemedb-lens/Cargo.toml b/crates/stemedb-lens/Cargo.toml new file mode 100644 index 0000000..ac4ab42 --- /dev/null +++ b/crates/stemedb-lens/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "stemedb-lens" +version = "0.1.0" +edition = "2021" +description = "Truth Lenses for resolving conflicting assertions in Episteme" + +# Inherit workspace lints +[lints] +workspace = true + +[dependencies] +stemedb-core = { path = "../stemedb-core" } +stemedb-storage = { path = "../stemedb-storage" } +async-trait = "0.1" +tracing = "0.1" +rkyv = { version = "0.7", features = ["validation"] } +blake3 = "1.5" +hex = "0.4" + +[dev-dependencies] +tokio = { version = "1", features = ["rt", "macros"] } diff --git a/crates/stemedb-lens/src/confidence.rs b/crates/stemedb-lens/src/confidence.rs new file mode 100644 index 0000000..1ceed56 --- /dev/null +++ b/crates/stemedb-lens/src/confidence.rs @@ -0,0 +1,198 @@ +//! Confidence Lens: Highest assertion confidence field wins. +//! +//! This lens selects assertions based on their self-declared `confidence` field. +//! It does NOT consider agent reputation or TrustRank - for reputation-aware +//! resolution, use `TrustAwareAuthorityLens`. +//! +//! # When to Use +//! +//! Use `ConfidenceLens` when: +//! - Assertions have meaningful confidence scores from their sources +//! - You want to prefer high-certainty claims over low-certainty ones +//! - Agent reputation is not a factor (or is handled elsewhere) +//! +//! Use `TrustAwareAuthorityLens` when: +//! - You want to weight by agent reputation (TrustRank) +//! - Agent history matters more than self-declared confidence + +use crate::traits::{Lens, Resolution}; +use stemedb_core::types::Assertion; +use tracing::instrument; + +/// Confidence Lens: Returns the assertion with the highest confidence field. +/// +/// # Resolution Strategy +/// +/// 1. Find assertion with maximum `confidence` field value +/// 2. If tie: prefer most recent (timestamp tiebreaker) +/// +/// # Confidence Calculation +/// +/// Resolution confidence equals the winning assertion's confidence field. +/// +/// # Example +/// +/// ```ignore +/// use stemedb_lens::{ConfidenceLens, Lens}; +/// +/// let lens = ConfidenceLens; +/// let resolution = lens.resolve(&candidates); +/// // Returns assertion with highest confidence field +/// ``` +#[derive(Debug, Clone, Copy, Default)] +pub struct ConfidenceLens; + +impl Lens for ConfidenceLens { + #[instrument(skip(self, candidates), fields(candidates_count = candidates.len(), lens = "Confidence"))] + fn resolve(&self, candidates: &[Assertion]) -> Resolution { + if candidates.is_empty() { + return Resolution::empty(); + } + + if candidates.len() == 1 { + return Resolution::with_winner(candidates[0].clone(), 1, 1.0); + } + + // Find the assertion with the highest confidence + let winner = candidates + .iter() + .max_by(|a, b| { + // Primary: highest confidence + // Tiebreaker: most recent timestamp + a.confidence + .partial_cmp(&b.confidence) + .unwrap_or(std::cmp::Ordering::Equal) + .then_with(|| a.timestamp.cmp(&b.timestamp)) + }) + .cloned(); + + match winner { + Some(w) => { + // Resolution confidence is the winning assertion's confidence + let confidence = w.confidence; + Resolution::with_winner(w, candidates.len(), confidence) + } + None => Resolution::empty(), + } + } + + fn name(&self) -> &'static str { + "Confidence" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use stemedb_core::testing::AssertionBuilder; + + fn create_assertion(subject: &str, confidence: f32, timestamp: u64) -> Assertion { + AssertionBuilder::new().subject(subject).confidence(confidence).timestamp(timestamp).build() + } + + #[test] + fn test_empty_candidates() { + let lens = ConfidenceLens; + let resolution = lens.resolve(&[]); + + assert!(resolution.winner.is_none()); + } + + #[test] + fn test_selects_highest_confidence() { + let lens = ConfidenceLens; + + let low = create_assertion("Low", 0.3, 1000); + let high = create_assertion("High", 0.95, 900); + let medium = create_assertion("Medium", 0.6, 1100); + + let resolution = lens.resolve(&[low, high.clone(), medium]); + + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().map(|a| &a.subject), Some(&"High".to_string())); + } + + #[test] + fn test_tiebreaker_uses_timestamp() { + let lens = ConfidenceLens; + + let older = create_assertion("Older", 0.9, 1000); + let newer = create_assertion("Newer", 0.9, 2000); + + let resolution = lens.resolve(&[older, newer.clone()]); + + // Same confidence, should pick newer + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().map(|a| &a.subject), Some(&"Newer".to_string())); + } + + #[test] + fn test_resolution_confidence_matches_winner() { + let lens = ConfidenceLens; + let high_conf = create_assertion("High", 0.85, 1000); + let low_conf = create_assertion("Low", 0.3, 900); + + let resolution = lens.resolve(&[high_conf, low_conf]); + + // Resolution confidence should match the winning assertion's confidence + assert!((resolution.resolution_confidence - 0.85).abs() < f32::EPSILON); + } + + #[test] + fn test_lens_name() { + let lens = ConfidenceLens; + assert_eq!(lens.name(), "Confidence"); + } + + #[test] + fn test_nan_confidence_falls_back_to_timestamp() { + let lens = ConfidenceLens; + + // NaN compared to any value returns Ordering::Equal via unwrap_or + // So tiebreaker (timestamp) decides the winner + let normal_older = create_assertion("NormalOlder", 0.5, 1000); + let mut nan_newer = create_assertion("NaNNewer", 0.0, 2000); + nan_newer.confidence = f32::NAN; + + let resolution = lens.resolve(&[normal_older.clone(), nan_newer]); + + // NaN == 0.5 (Equal due to unwrap_or), so newer timestamp wins + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().map(|a| &a.subject), Some(&"NaNNewer".to_string())); + } + + #[test] + fn test_nan_confidence_loses_to_newer_normal() { + let lens = ConfidenceLens; + + // When normal assertion has newer timestamp, it wins (NaN treated as equal) + let mut nan_older = create_assertion("NaNOlder", 0.0, 1000); + nan_older.confidence = f32::NAN; + let normal_newer = create_assertion("NormalNewer", 0.5, 2000); + + let resolution = lens.resolve(&[nan_older, normal_newer.clone()]); + + // NaN == 0.5 (Equal), tiebreaker picks newer timestamp + assert!(resolution.winner.is_some()); + assert_eq!( + resolution.winner.as_ref().map(|a| &a.subject), + Some(&"NormalNewer".to_string()) + ); + } + + #[test] + fn test_all_nan_confidence_uses_timestamp() { + let lens = ConfidenceLens; + + let mut older_nan = create_assertion("OlderNaN", 0.0, 1000); + older_nan.confidence = f32::NAN; + let mut newer_nan = create_assertion("NewerNaN", 0.0, 2000); + newer_nan.confidence = f32::NAN; + + let resolution = lens.resolve(&[older_nan, newer_nan.clone()]); + + // When all are NaN (equal), tiebreaker should pick newer timestamp + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().map(|a| &a.subject), Some(&"NewerNaN".to_string())); + } +} diff --git a/crates/stemedb-lens/src/consensus.rs b/crates/stemedb-lens/src/consensus.rs new file mode 100644 index 0000000..1c7a8ed --- /dev/null +++ b/crates/stemedb-lens/src/consensus.rs @@ -0,0 +1,170 @@ +//! Consensus Lens: Most common value wins. +//! +//! This lens selects assertions based on how many agents agree on the same value. +//! In Phase 2, this counts identical object values across assertions. +//! In Phase 4, this will integrate with the Ballot Box vote counts. + +use crate::traits::{Lens, Resolution}; +use std::collections::HashMap; +use stemedb_core::types::Assertion; +use tracing::instrument; + +/// Consensus Lens: Returns the assertion representing the most common value. +/// +/// # Current Implementation (Phase 2 Stub) +/// +/// Groups assertions by their `object` field (string representation) and +/// returns a representative from the largest group. +/// +/// # Future Implementation (Phase 4) +/// +/// Will integrate with VoteStore to: +/// - Count explicit votes per assertion +/// - Weight by agent TrustRank +/// - Consider multi-sig counts +/// +/// # Resolution Strategy +/// +/// 1. Group assertions by object value +/// 2. Select the group with the most members +/// 3. From that group, pick the most recent assertion +#[derive(Debug, Clone, Copy, Default)] +pub struct ConsensusLens; + +impl Lens for ConsensusLens { + #[instrument(skip(self, candidates), fields(candidates_count = candidates.len(), lens = "Consensus"))] + fn resolve(&self, candidates: &[Assertion]) -> Resolution { + if candidates.is_empty() { + return Resolution::empty(); + } + + if candidates.len() == 1 { + return Resolution::with_winner(candidates[0].clone(), 1, 1.0); + } + + // Group assertions by their object value + // We use Debug format as a simple equality proxy + let mut groups: HashMap> = HashMap::new(); + + for assertion in candidates { + let key = format!("{:?}", assertion.object); + groups.entry(key).or_default().push(assertion); + } + + // Find the largest group + let largest_group = groups.values().max_by_key(|v| v.len()); + + match largest_group { + Some(group) => { + // From the largest group, pick the most recent + let winner = group.iter().max_by_key(|a| a.timestamp).cloned().cloned(); + + match winner { + Some(w) => { + let group_size = group.len(); + let total = candidates.len(); + + // Confidence = proportion of candidates that agree + let confidence = group_size as f32 / total as f32; + + Resolution::with_winner(w, total, confidence) + } + None => Resolution::empty(), + } + } + None => Resolution::empty(), + } + } + + fn name(&self) -> &'static str { + "Consensus" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use stemedb_core::testing::AssertionBuilder; + use stemedb_core::types::ObjectValue; + + fn create_assertion(subject: &str, value: f64, timestamp: u64) -> Assertion { + AssertionBuilder::new().subject(subject).object_number(value).timestamp(timestamp).build() + } + + #[test] + fn test_empty_candidates() { + let lens = ConsensusLens; + let resolution = lens.resolve(&[]); + + assert!(resolution.winner.is_none()); + } + + #[test] + fn test_selects_most_common_value() { + let lens = ConsensusLens; + + // Three assertions say 100.0, one says 200.0 + let a1 = create_assertion("Agent1", 100.0, 1000); + let a2 = create_assertion("Agent2", 100.0, 1100); + let a3 = create_assertion("Agent3", 100.0, 1200); + let outlier = create_assertion("Outlier", 200.0, 1300); + + let resolution = lens.resolve(&[a1, a2, a3, outlier]); + + assert!(resolution.winner.is_some()); + // Winner should have value 100.0 + match &resolution.winner.as_ref().map(|a| &a.object) { + Some(ObjectValue::Number(v)) => assert!((*v - 100.0).abs() < f64::EPSILON), + _ => panic!("Expected Number"), + } + } + + #[test] + fn test_selects_newest_from_consensus_group() { + let lens = ConsensusLens; + + let old = create_assertion("Old", 100.0, 1000); + let new = create_assertion("New", 100.0, 2000); + + let resolution = lens.resolve(&[old, new.clone()]); + + // Both have same value, should pick newer + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().map(|a| &a.subject), Some(&"New".to_string())); + } + + #[test] + fn test_confidence_reflects_agreement() { + let lens = ConsensusLens; + + // 3 out of 4 agree + let a1 = create_assertion("A1", 100.0, 1000); + let a2 = create_assertion("A2", 100.0, 1100); + let a3 = create_assertion("A3", 100.0, 1200); + let outlier = create_assertion("Outlier", 200.0, 1300); + + let resolution = lens.resolve(&[a1, a2, a3, outlier]); + + // Confidence should be 3/4 = 0.75 + assert!((resolution.resolution_confidence - 0.75).abs() < f32::EPSILON); + } + + #[test] + fn test_full_consensus() { + let lens = ConsensusLens; + + let a1 = create_assertion("A1", 100.0, 1000); + let a2 = create_assertion("A2", 100.0, 1100); + + let resolution = lens.resolve(&[a1, a2]); + + // Full consensus = 1.0 confidence + assert!((resolution.resolution_confidence - 1.0).abs() < f32::EPSILON); + } + + #[test] + fn test_lens_name() { + let lens = ConsensusLens; + assert_eq!(lens.name(), "Consensus"); + } +} diff --git a/crates/stemedb-lens/src/epoch_aware.rs b/crates/stemedb-lens/src/epoch_aware.rs new file mode 100644 index 0000000..b57f9b9 --- /dev/null +++ b/crates/stemedb-lens/src/epoch_aware.rs @@ -0,0 +1,677 @@ +//! Epoch-Aware Lens: Filters superseded epochs before resolution. +//! +//! This lens implements the "Paradigm" concept from the architecture: epochs +//! can supersede each other, and assertions from superseded epochs should be +//! excluded from query results. +//! +//! # Design Philosophy +//! +//! Follows the "Deep Module" principle: +//! - Simple interface: `resolve_async(&[Assertion])` returns winner +//! - Complex implementation: Walks epoch supersession chains, filters candidates +//! - Composable: Wraps any inner lens for final resolution +//! +//! # Resolution Strategy +//! +//! 1. Collect all unique epoch IDs from candidate assertions +//! 2. For each epoch, read `E:{epoch_id}` from store +//! 3. Walk the `supersedes` chain to build a set of superseded epoch IDs +//! 4. Filter candidates: exclude any assertion whose epoch is superseded +//! 5. Delegate filtered candidates to inner lens for final winner selection +//! +//! # Fail-Open Semantics +//! +//! Missing or corrupted epoch records do NOT cause assertion exclusion: +//! - Assertion references epoch X, but `E:X` doesn't exist → include assertion +//! - Epoch record fails to deserialize → include assertion +//! - Cycle detected in supersession chain → stop walking, include assertions +//! +//! This ensures data availability is not compromised by metadata issues. +//! +//! # Example +//! +//! ```ignore +//! use stemedb_lens::{EpochAwareLens, RecencyLens}; +//! use stemedb_storage::SledStore; +//! use std::sync::Arc; +//! +//! let store = Arc::new(SledStore::open("./data").expect("store")); +//! let lens = EpochAwareLens::with_recency(store); +//! +//! let resolution = lens.resolve_async(&candidates).await; +//! ``` + +use crate::recency::RecencyLens; +use crate::traits::{Lens, Resolution}; +use crate::vote_aware_consensus::AsyncLens; +use async_trait::async_trait; +use std::collections::HashSet; +use std::sync::Arc; +use stemedb_core::serde::deserialize; +use stemedb_core::types::{Assertion, Epoch, EpochId}; +use stemedb_storage::KVStore; +use tracing::{debug, instrument, warn}; + +/// Wrapper to use a sync Lens with EpochAwareLens. +/// +/// This allows using synchronous lenses (like `RecencyLens`, `ConsensusLens`) +/// with the async `EpochAwareLens`. +pub struct SyncLensWrapper(pub L); + +#[async_trait] +impl AsyncLens for SyncLensWrapper { + async fn resolve_async(&self, candidates: &[Assertion]) -> Resolution { + self.0.resolve(candidates) + } + + fn name(&self) -> &'static str { + self.0.name() + } +} + +/// Maximum depth for walking supersession chains. +/// +/// Prevents infinite loops and excessive I/O for pathological chains. +/// In practice, epoch chains should be much shorter (3-7 levels). +const MAX_SUPERSESSION_DEPTH: usize = 100; + +/// Epoch-Aware Lens: Filters assertions from superseded epochs before delegation. +/// +/// This is a decorator/wrapper lens that: +/// 1. Reads epoch records to determine which epochs are superseded +/// 2. Filters out assertions from superseded epochs +/// 3. Delegates remaining candidates to an inner lens +/// +/// # Type Parameters +/// +/// - `S`: The KVStore implementation for reading epoch records +/// - `L`: The inner lens for final resolution after filtering +pub struct EpochAwareLens { + store: Arc, + inner: L, +} + +impl EpochAwareLens> { + /// Create an EpochAwareLens with RecencyLens as the inner resolution strategy. + /// + /// This is the common case: filter superseded epochs, then pick the most recent. + pub fn with_recency(store: Arc) -> Self { + Self { store, inner: SyncLensWrapper(RecencyLens) } + } +} + +impl EpochAwareLens { + /// Create an EpochAwareLens with a custom inner lens. + /// + /// # Arguments + /// + /// * `store` - Arc to KVStore for reading `E:{epoch_id}` keys + /// * `inner` - Inner lens to delegate to after filtering superseded epochs + pub fn new(store: Arc, inner: L) -> Self { + Self { store, inner } + } + + /// Build the key for reading an epoch record. + /// + /// Format: `E:{epoch_id_hex}` + fn epoch_key(epoch_id: &EpochId) -> Vec { + format!("E:{}", hex::encode(epoch_id)).into_bytes() + } + + /// Read an epoch record from the store. + /// + /// Returns `None` if the epoch doesn't exist or fails to deserialize. + async fn read_epoch(&self, epoch_id: &EpochId) -> Option { + let key = Self::epoch_key(epoch_id); + + match self.store.get(&key).await { + Ok(Some(bytes)) => match deserialize::(&bytes) { + Ok(epoch) => Some(epoch), + Err(e) => { + warn!( + epoch_id = %hex::encode(epoch_id), + error = %e, + "Failed to deserialize epoch record, treating as missing" + ); + None + } + }, + Ok(None) => { + debug!( + epoch_id = %hex::encode(epoch_id), + "Epoch record not found in store" + ); + None + } + Err(e) => { + warn!( + epoch_id = %hex::encode(epoch_id), + error = %e, + "Failed to read epoch from store, treating as missing" + ); + None + } + } + } + + /// Compute the set of superseded epoch IDs. + /// + /// For each epoch in `epochs`, walks the supersession chain and collects + /// all epoch IDs that are superseded (transitively). + /// + /// # Algorithm + /// + /// For epoch E that supersedes P which supersedes G: + /// - E.supersedes = Some(P) → P is superseded + /// - P.supersedes = Some(G) → G is superseded + /// - Result: {P, G} are superseded + /// + /// # Safety + /// + /// - Cycle detection via visited set + /// - Max depth guard (100 levels) + /// - Missing epochs are skipped (fail-open) + async fn compute_superseded_epochs(&self, epochs: &HashSet) -> HashSet { + let mut superseded = HashSet::new(); + let mut visited = HashSet::new(); + + for epoch_id in epochs { + self.walk_supersession_chain(epoch_id, &mut superseded, &mut visited).await; + } + + superseded + } + + /// Walk the supersession chain starting from `epoch_id`. + /// + /// Adds all superseded epoch IDs to the `superseded` set. + async fn walk_supersession_chain( + &self, + start_epoch_id: &EpochId, + superseded: &mut HashSet, + visited: &mut HashSet, + ) { + let mut current_id = *start_epoch_id; + let mut depth = 0; + + loop { + // Cycle detection + if !visited.insert(current_id) { + debug!( + epoch_id = %hex::encode(current_id), + "Cycle detected in supersession chain, stopping walk" + ); + break; + } + + // Max depth guard + if depth >= MAX_SUPERSESSION_DEPTH { + warn!( + start_epoch = %hex::encode(start_epoch_id), + depth, + "Supersession chain exceeded max depth, stopping walk" + ); + break; + } + + // Read epoch record + let epoch = match self.read_epoch(¤t_id).await { + Some(e) => e, + None => break, // Missing epoch - stop walking + }; + + // Check for supersession + match epoch.supersedes { + Some(superseded_id) => { + // This epoch supersedes another - add the superseded one to the set + superseded.insert(superseded_id); + current_id = superseded_id; + depth += 1; + } + None => break, // End of chain + } + } + } +} + +#[async_trait] +impl AsyncLens for EpochAwareLens { + #[instrument(skip(self, candidates), fields( + candidates_count = candidates.len(), + lens = "EpochAware" + ))] + async fn resolve_async(&self, candidates: &[Assertion]) -> Resolution { + if candidates.is_empty() { + return Resolution::empty(); + } + + // Fast path: single candidate passes through + if candidates.len() == 1 { + return self.inner.resolve_async(candidates).await; + } + + // Collect unique epochs from candidates + let epochs: HashSet = candidates.iter().filter_map(|a| a.epoch).collect(); + + // If no assertions have epochs, delegate directly to inner lens + if epochs.is_empty() { + debug!("No epochs in candidates, delegating directly to inner lens"); + return self.inner.resolve_async(candidates).await; + } + + debug!(unique_epochs = epochs.len(), "Computing superseded epochs"); + + // Build the superseded set + let superseded = self.compute_superseded_epochs(&epochs).await; + + debug!(superseded_count = superseded.len(), "Found superseded epochs"); + + // Filter candidates: exclude assertions from superseded epochs + let filtered: Vec<&Assertion> = candidates + .iter() + .filter(|a| { + match a.epoch { + // No epoch: always include + None => true, + // Has epoch: include if NOT superseded + Some(epoch_id) => !superseded.contains(&epoch_id), + } + }) + .collect(); + + let filtered_count = filtered.len(); + let excluded_count = candidates.len() - filtered_count; + + debug!(filtered_count, excluded_count, "Filtered candidates by epoch supersession"); + + // Handle case where all candidates were filtered + if filtered.is_empty() { + debug!("All candidates were from superseded epochs, returning empty resolution"); + return Resolution::empty(); + } + + // Clone filtered assertions for delegation to inner lens + let filtered_owned: Vec = filtered.into_iter().cloned().collect(); + + // Delegate to inner lens + self.inner.resolve_async(&filtered_owned).await + } + + fn name(&self) -> &'static str { + "EpochAware" + } +} + +impl EpochAwareLens> { + /// Create an EpochAwareLens wrapping a synchronous lens. + /// + /// This allows using any `Lens` implementation (like `ConsensusLens`) + /// with epoch-aware filtering. + pub fn with_sync_lens(store: Arc, inner: L) -> Self { + Self { store, inner: SyncLensWrapper(inner) } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::consensus::ConsensusLens; + use stemedb_core::serde::serialize; + use stemedb_core::testing::{test_epoch_with_supersession, AssertionBuilder}; + use stemedb_core::types::SupersessionType; + use stemedb_storage::SledStore; + + /// Store an epoch in the KV store. + async fn store_epoch(store: &SledStore, epoch: &Epoch) { + let key = format!("E:{}", hex::encode(epoch.id)).into_bytes(); + let bytes = serialize(epoch).expect("serialize epoch"); + store.put(&key, &bytes).await.expect("put epoch"); + } + + /// Create a simple epoch without supersession. + fn create_epoch(id: [u8; 32], name: &str) -> Epoch { + Epoch { + id, + name: name.to_string(), + supersedes: None, + supersession_type: None, + start_timestamp: 1000, + end_timestamp: None, + } + } + + #[tokio::test] + async fn test_empty_candidates() { + let store = Arc::new(SledStore::open_temp().expect("store")); + let lens = EpochAwareLens::with_recency(store); + + let resolution = lens.resolve_async(&[]).await; + + assert!(resolution.winner.is_none()); + assert_eq!(resolution.candidates_count, 0); + } + + #[tokio::test] + async fn test_single_candidate() { + let store = Arc::new(SledStore::open_temp().expect("store")); + let lens = EpochAwareLens::with_recency(store); + + let assertion = AssertionBuilder::new().subject("Tesla").timestamp(1000).build(); + + let resolution = lens.resolve_async(std::slice::from_ref(&assertion)).await; + + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().map(|a| &a.subject), Some(&"Tesla".to_string())); + } + + #[tokio::test] + async fn test_epoch_aware_no_epochs_passes_all() { + let store = Arc::new(SledStore::open_temp().expect("store")); + let lens = EpochAwareLens::with_recency(store); + + // Create assertions without epochs + let a1 = AssertionBuilder::new().subject("A").timestamp(1000).build(); + let a2 = AssertionBuilder::new().subject("B").timestamp(2000).build(); + + let resolution = lens.resolve_async(&[a1, a2]).await; + + // RecencyLens picks the newest timestamp + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().map(|a| &a.subject), Some(&"B".to_string())); + assert_eq!(resolution.candidates_count, 2); + } + + #[tokio::test] + async fn test_epoch_aware_excludes_superseded() { + let store = Arc::new(SledStore::open_temp().expect("store")); + + // Create epochs: B supersedes A + let epoch_a = create_epoch([1u8; 32], "Epoch A"); + let epoch_b = test_epoch_with_supersession( + [2u8; 32], + "Epoch B", + [1u8; 32], // supersedes A + SupersessionType::Temporal, + ); + + store_epoch(&store, &epoch_a).await; + store_epoch(&store, &epoch_b).await; + + let lens = EpochAwareLens::with_recency(Arc::clone(&store)); + + // Create assertions: one in A (should be excluded), one in B (should be included) + let a_assertion = + AssertionBuilder::new().subject("InEpochA").epoch([1u8; 32]).timestamp(3000).build(); + + let b_assertion = + AssertionBuilder::new().subject("InEpochB").epoch([2u8; 32]).timestamp(1000).build(); + + let resolution = lens.resolve_async(&[a_assertion, b_assertion]).await; + + // Should pick the assertion from epoch B (even though A has higher timestamp) + // because A is superseded + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().map(|a| &a.subject), Some(&"InEpochB".to_string())); + } + + #[tokio::test] + async fn test_epoch_aware_chain_supersession() { + let store = Arc::new(SledStore::open_temp().expect("store")); + + // Create chain: C supersedes B, B supersedes A + let epoch_a = create_epoch([1u8; 32], "Epoch A"); + let epoch_b = test_epoch_with_supersession( + [2u8; 32], + "Epoch B", + [1u8; 32], // supersedes A + SupersessionType::Temporal, + ); + let epoch_c = test_epoch_with_supersession( + [3u8; 32], + "Epoch C", + [2u8; 32], // supersedes B + SupersessionType::Temporal, + ); + + store_epoch(&store, &epoch_a).await; + store_epoch(&store, &epoch_b).await; + store_epoch(&store, &epoch_c).await; + + let lens = EpochAwareLens::with_recency(Arc::clone(&store)); + + // Create assertions in all three epochs + let a_assertion = + AssertionBuilder::new().subject("InEpochA").epoch([1u8; 32]).timestamp(3000).build(); + + let b_assertion = + AssertionBuilder::new().subject("InEpochB").epoch([2u8; 32]).timestamp(2000).build(); + + let c_assertion = + AssertionBuilder::new().subject("InEpochC").epoch([3u8; 32]).timestamp(1000).build(); + + let resolution = lens.resolve_async(&[a_assertion, b_assertion, c_assertion]).await; + + // Only epoch C should survive (A and B are superseded) + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().map(|a| &a.subject), Some(&"InEpochC".to_string())); + } + + #[tokio::test] + async fn test_epoch_aware_missing_epoch_record_includes() { + let store = Arc::new(SledStore::open_temp().expect("store")); + + // Only store epoch B which supersedes A, but DON'T store epoch A + let epoch_b = test_epoch_with_supersession( + [2u8; 32], + "Epoch B", + [1u8; 32], // supersedes A (which doesn't exist) + SupersessionType::Temporal, + ); + store_epoch(&store, &epoch_b).await; + + let lens = EpochAwareLens::with_recency(Arc::clone(&store)); + + // Create assertions: one references missing epoch [99], one in B + let missing_epoch_assertion = AssertionBuilder::new() + .subject("MissingEpoch") + .epoch([99u8; 32]) // This epoch doesn't exist in store + .timestamp(3000) + .build(); + + let b_assertion = + AssertionBuilder::new().subject("InEpochB").epoch([2u8; 32]).timestamp(1000).build(); + + let resolution = lens.resolve_async(&[missing_epoch_assertion, b_assertion]).await; + + // Missing epoch assertion should be included (fail-open) + // RecencyLens picks the most recent timestamp + assert!(resolution.winner.is_some()); + assert_eq!( + resolution.winner.as_ref().map(|a| &a.subject), + Some(&"MissingEpoch".to_string()) + ); + } + + #[tokio::test] + async fn test_epoch_aware_cycle_detection() { + let store = Arc::new(SledStore::open_temp().expect("store")); + + // Create circular supersession: A supersedes B, B supersedes A + let epoch_a = Epoch { + id: [1u8; 32], + name: "Epoch A".to_string(), + supersedes: Some([2u8; 32]), // A supersedes B + supersession_type: Some(SupersessionType::Temporal), + start_timestamp: 1000, + end_timestamp: None, + }; + let epoch_b = Epoch { + id: [2u8; 32], + name: "Epoch B".to_string(), + supersedes: Some([1u8; 32]), // B supersedes A (cycle!) + supersession_type: Some(SupersessionType::Temporal), + start_timestamp: 1000, + end_timestamp: None, + }; + + store_epoch(&store, &epoch_a).await; + store_epoch(&store, &epoch_b).await; + + let lens = EpochAwareLens::with_recency(Arc::clone(&store)); + + // Create assertions in both epochs + let a_assertion = + AssertionBuilder::new().subject("InEpochA").epoch([1u8; 32]).timestamp(2000).build(); + + let b_assertion = + AssertionBuilder::new().subject("InEpochB").epoch([2u8; 32]).timestamp(1000).build(); + + // Should not hang or panic - cycle detection should kick in. + // If cycle detection fails, this would hang forever (test timeout would catch it). + let resolution = lens.resolve_async(&[a_assertion, b_assertion]).await; + + // In a mutual supersession cycle (A supersedes B, B supersedes A): + // - Walking from A: A.supersedes = B, so B is added to superseded set + // - Walking from B: B.supersedes = A, so A is added to superseded set + // - Both epochs end up in the superseded set + // - All candidates are filtered out + // - Result is empty resolution + // + // This is the correct behavior for pathological data: mutual supersession + // means "both are obsolete" which results in no valid candidates. + assert!(resolution.winner.is_none(), "mutual supersession should filter all candidates"); + assert_eq!(resolution.candidates_count, 0, "empty resolution has 0 candidates_count"); + } + + #[tokio::test] + async fn test_epoch_aware_with_consensus_lens() { + let store = Arc::new(SledStore::open_temp().expect("store")); + + // Create epochs: B supersedes A + let epoch_a = create_epoch([1u8; 32], "Epoch A"); + let epoch_b = test_epoch_with_supersession( + [2u8; 32], + "Epoch B", + [1u8; 32], + SupersessionType::Temporal, + ); + + store_epoch(&store, &epoch_a).await; + store_epoch(&store, &epoch_b).await; + + // Use ConsensusLens as inner lens + let lens = EpochAwareLens::with_sync_lens(Arc::clone(&store), ConsensusLens); + + // Create multiple assertions with same value in epoch B (consensus) + let b1 = AssertionBuilder::new() + .subject("B1") + .object_number(100.0) + .epoch([2u8; 32]) + .timestamp(1000) + .build(); + + let b2 = AssertionBuilder::new() + .subject("B2") + .object_number(100.0) + .epoch([2u8; 32]) + .timestamp(2000) + .build(); + + // Assertion in superseded epoch A + let a1 = AssertionBuilder::new() + .subject("A1") + .object_number(200.0) + .epoch([1u8; 32]) + .timestamp(3000) + .build(); + + let resolution = lens.resolve_async(&[b1, b2, a1]).await; + + // Should exclude A1 (superseded epoch), then ConsensusLens picks from B1, B2 + assert!(resolution.winner.is_some()); + // ConsensusLens groups by object value - both B1 and B2 have 100.0 + // The winner should be from epoch B + let winner = resolution.winner.as_ref().expect("winner"); + assert!(winner.epoch == Some([2u8; 32])); + } + + #[tokio::test] + async fn test_epoch_aware_mixed_epochs_and_no_epochs() { + let store = Arc::new(SledStore::open_temp().expect("store")); + + // Create epochs: B supersedes A + let epoch_a = create_epoch([1u8; 32], "Epoch A"); + let epoch_b = test_epoch_with_supersession( + [2u8; 32], + "Epoch B", + [1u8; 32], + SupersessionType::Temporal, + ); + + store_epoch(&store, &epoch_a).await; + store_epoch(&store, &epoch_b).await; + + let lens = EpochAwareLens::with_recency(Arc::clone(&store)); + + // Mix of assertions: some with epochs, some without + let no_epoch = AssertionBuilder::new().subject("NoEpoch").timestamp(1000).build(); + + let in_a = AssertionBuilder::new().subject("InA").epoch([1u8; 32]).timestamp(3000).build(); + + let in_b = AssertionBuilder::new().subject("InB").epoch([2u8; 32]).timestamp(2000).build(); + + let resolution = lens.resolve_async(&[no_epoch, in_a, in_b]).await; + + // NoEpoch should pass (no epoch = always included) + // InA should be excluded (superseded) + // InB should pass + // RecencyLens picks InB (timestamp 2000) over NoEpoch (timestamp 1000) + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().map(|a| &a.subject), Some(&"InB".to_string())); + } + + #[tokio::test] + async fn test_only_old_epoch_assertions_not_filtered_without_new() { + // This test documents an important design decision: + // Epoch filtering only happens when assertions from the superseding epoch + // are present in the candidates. This is fail-open behavior: + // if there's no "new" data, we don't hide the "old" data. + let store = Arc::new(SledStore::open_temp().expect("store")); + + // Create epochs: B supersedes A + let epoch_a = create_epoch([1u8; 32], "Epoch A"); + let epoch_b = test_epoch_with_supersession( + [2u8; 32], + "Epoch B", + [1u8; 32], + SupersessionType::Temporal, + ); + + store_epoch(&store, &epoch_a).await; + store_epoch(&store, &epoch_b).await; + + let lens = EpochAwareLens::with_recency(Arc::clone(&store)); + + // Only assertions from "old" epoch A (no epoch B assertions in candidates) + // Even though B supersedes A, without B-epoch assertions present, + // we don't know to filter A. + let a1 = AssertionBuilder::new().subject("A1").epoch([1u8; 32]).timestamp(1000).build(); + + let a2 = AssertionBuilder::new().subject("A2").epoch([1u8; 32]).timestamp(2000).build(); + + let resolution = lens.resolve_async(&[a1, a2]).await; + + // Without epoch B assertions present, A's assertions pass through + // RecencyLens picks A2 (newer timestamp) + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().map(|a| &a.subject), Some(&"A2".to_string())); + } + + #[tokio::test] + async fn test_lens_name() { + let store = Arc::new(SledStore::open_temp().expect("store")); + let lens = EpochAwareLens::with_recency(store); + + assert_eq!(lens.name(), "EpochAware"); + } +} diff --git a/crates/stemedb-lens/src/lib.rs b/crates/stemedb-lens/src/lib.rs new file mode 100644 index 0000000..d531481 --- /dev/null +++ b/crates/stemedb-lens/src/lib.rs @@ -0,0 +1,62 @@ +//! Truth Lenses for resolving conflicting assertions. +//! +//! In Episteme, multiple assertions can exist for the same subject+predicate. +//! A Lens determines which assertion(s) to return based on a resolution strategy. +//! +//! # Design Philosophy +//! +//! Following "Deep Module" principle: simple `resolve()` interface hides +//! complex resolution logic. Lenses are stateless and deterministic. +//! +//! # Two Types of Lenses +//! +//! | Type | Returns | Purpose | +//! |------|---------|---------| +//! | Resolution Lenses | Single winner | "Give me the answer" | +//! | Analysis Lenses | All claims | "Show me the disagreement" | +//! +//! # Standard Resolution Lenses +//! +//! | Lens | Strategy | Use Case | +//! |------|----------|----------| +//! | Recency | Latest timestamp wins | News, real-time | +//! | Consensus | Most common object value | Democratic truth (basic) | +//! | VoteAwareConsensus | Highest vote weight from VoteStore | Democratic truth (advanced) | +//! | Confidence | Highest assertion confidence field | Source-declared certainty | +//! | TrustAwareAuthority | Weighted by TrustRank reputation | Expert truth (The Hive) | +//! | EpochAware | Filters superseded epochs first | Paradigm-safe queries | +//! +//! # Analysis Lenses +//! +//! | Lens | Strategy | Use Case | +//! |------|----------|----------| +//! | Skeptic | Surfaces all claims with conflict score | "Trust but Verify" dashboards | +//! +//! # Example +//! +//! ``` +//! use stemedb_lens::{Lens, RecencyLens}; +//! use stemedb_core::types::Assertion; +//! +//! let lens = RecencyLens; +//! let assertions: Vec = vec![/* ... */]; +//! let winner = lens.resolve(&assertions); +//! ``` + +mod confidence; +mod consensus; +mod epoch_aware; +mod recency; +mod skeptic; +mod traits; +mod trust_aware_authority; +mod vote_aware_consensus; + +pub use confidence::ConfidenceLens; +pub use consensus::ConsensusLens; +pub use epoch_aware::{EpochAwareLens, SyncLensWrapper}; +pub use recency::RecencyLens; +pub use skeptic::SkepticLens; +pub use traits::{AnalysisLens, Lens, Resolution}; +pub use trust_aware_authority::TrustAwareAuthorityLens; +pub use vote_aware_consensus::{AsyncLens, VoteAwareConsensusLens}; diff --git a/crates/stemedb-lens/src/recency.rs b/crates/stemedb-lens/src/recency.rs new file mode 100644 index 0000000..d1efae0 --- /dev/null +++ b/crates/stemedb-lens/src/recency.rs @@ -0,0 +1,154 @@ +//! Recency Lens: Most recent timestamp wins. +//! +//! This is the simplest lens, useful for scenarios where the latest +//! information is always preferred (news, real-time data). + +use crate::traits::{Lens, Resolution}; +use stemedb_core::types::Assertion; +use tracing::instrument; + +/// Recency Lens: Returns the assertion with the highest timestamp. +/// +/// # Resolution Strategy +/// +/// 1. Find assertion with maximum `timestamp` +/// 2. If tie: prefer assertion with lower `confidence` hash (deterministic tiebreaker) +/// +/// # Confidence Calculation +/// +/// - Single candidate: 1.0 (trivial resolution) +/// - Multiple candidates: Based on timestamp gap to next candidate +#[derive(Debug, Clone, Copy, Default)] +pub struct RecencyLens; + +impl Lens for RecencyLens { + #[instrument(skip(self, candidates), fields(candidates_count = candidates.len(), lens = "Recency"))] + fn resolve(&self, candidates: &[Assertion]) -> Resolution { + if candidates.is_empty() { + return Resolution::empty(); + } + + if candidates.len() == 1 { + return Resolution::with_winner(candidates[0].clone(), 1, 1.0); + } + + // Find the assertion with the highest timestamp + let winner = candidates + .iter() + .max_by(|a, b| { + // Primary: highest timestamp + // Tiebreaker: compare source_hash for determinism + a.timestamp.cmp(&b.timestamp).then_with(|| a.source_hash.cmp(&b.source_hash)) + }) + .cloned(); + + match winner { + Some(w) => { + // Calculate confidence based on how much newer the winner is + let max_ts = w.timestamp; + let second_max = candidates + .iter() + .filter(|a| a.timestamp < max_ts) + .map(|a| a.timestamp) + .max() + .unwrap_or(0); + + // Confidence is higher when the gap is larger + // This is a simple heuristic; real systems might use more sophisticated metrics + let gap = max_ts.saturating_sub(second_max); + let confidence = if gap > 86400 { + // More than a day: high confidence + 0.95 + } else if gap > 3600 { + // More than an hour: good confidence + 0.8 + } else if gap > 60 { + // More than a minute: moderate confidence + 0.6 + } else { + // Very close: low confidence + 0.5 + }; + + Resolution::with_winner(w, candidates.len(), confidence) + } + None => Resolution::empty(), + } + } + + fn name(&self) -> &'static str { + "Recency" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use stemedb_core::testing::AssertionBuilder; + + fn create_assertion(subject: &str, timestamp: u64) -> Assertion { + AssertionBuilder::new().subject(subject).timestamp(timestamp).build() + } + + #[test] + fn test_empty_candidates() { + let lens = RecencyLens; + let resolution = lens.resolve(&[]); + + assert!(resolution.winner.is_none()); + assert_eq!(resolution.candidates_count, 0); + } + + #[test] + fn test_single_candidate() { + let lens = RecencyLens; + let assertion = create_assertion("Tesla", 1000); + let resolution = lens.resolve(std::slice::from_ref(&assertion)); + + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().map(|a| &a.subject), Some(&"Tesla".to_string())); + assert_eq!(resolution.candidates_count, 1); + assert!((resolution.resolution_confidence - 1.0).abs() < f32::EPSILON); + } + + #[test] + fn test_multiple_candidates_selects_newest() { + let lens = RecencyLens; + let old = create_assertion("Old", 1000); + let new = create_assertion("New", 2000); + let older = create_assertion("Older", 500); + + let resolution = lens.resolve(&[old, new.clone(), older]); + + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().map(|a| &a.subject), Some(&"New".to_string())); + assert_eq!(resolution.candidates_count, 3); + } + + #[test] + fn test_deterministic_tiebreaker() { + let lens = RecencyLens; + + let mut a1 = create_assertion("A", 1000); + a1.source_hash = [1u8; 32]; + + let mut a2 = create_assertion("B", 1000); + a2.source_hash = [2u8; 32]; + + // Same timestamp, should use source_hash as tiebreaker + let resolution1 = lens.resolve(&[a1.clone(), a2.clone()]); + let resolution2 = lens.resolve(&[a2.clone(), a1.clone()]); + + // Should be deterministic regardless of input order + assert_eq!( + resolution1.winner.as_ref().map(|a| &a.subject), + resolution2.winner.as_ref().map(|a| &a.subject) + ); + } + + #[test] + fn test_lens_name() { + let lens = RecencyLens; + assert_eq!(lens.name(), "Recency"); + } +} diff --git a/crates/stemedb-lens/src/skeptic.rs b/crates/stemedb-lens/src/skeptic.rs new file mode 100644 index 0000000..fd719d3 --- /dev/null +++ b/crates/stemedb-lens/src/skeptic.rs @@ -0,0 +1,521 @@ +//! Skeptic Lens: Surfaces conflict instead of resolving it. +//! +//! Unlike other lenses that pick a winner, SkepticLens returns the entire +//! conflict landscape. It enables "Trust but Verify" UX where users see +//! competing claims, their relative support, and who disagrees. +//! +//! # Design Philosophy +//! +//! Following the "Deep Module" principle: +//! - Simple interface: `analyze(&[Assertion])` returns conflict analysis +//! - Complex implementation: Groups by value, calculates entropy, ranks claims +//! - Integrates with VoteStore and TrustRankStore for weighted analysis +//! +//! # Conflict Score +//! +//! Uses normalized Shannon entropy to measure disagreement: +//! - 0.0 = unanimous (all weight on one claim) +//! - 1.0 = maximum chaos (equal weight across all claims) +//! +//! # Example +//! +//! ```ignore +//! use stemedb_lens::SkepticLens; +//! use stemedb_storage::{SledStore, GenericVoteStore}; +//! use std::sync::Arc; +//! +//! let store = SledStore::open("./data").await?; +//! let vote_store = Arc::new(GenericVoteStore::new(store)); +//! let lens = SkepticLens::new(vote_store); +//! +//! let analysis = lens.analyze(&candidates).await; +//! println!("Status: {:?}, Conflict: {:.2}", analysis.status, analysis.conflict_score); +//! for claim in &analysis.claims { +//! println!(" {} - {:.0}% support", claim.value, claim.weight_share * 100.0); +//! } +//! ``` + +use crate::traits::AnalysisLens; +use async_trait::async_trait; +use std::collections::HashMap; +use std::sync::Arc; +use stemedb_core::types::{ + AgentSummary, Assertion, ClaimSummary, ConflictAnalysis, Hash, ObjectValue, ResolutionStatus, + SourceSummary, +}; +use stemedb_storage::trust_rank_store::TrustRankStore; +use stemedb_storage::vote_store::VoteStore; +use tracing::{debug, instrument}; + +/// Skeptic Lens: Returns conflict landscape instead of picking a winner. +/// +/// # Resolution Strategy +/// +/// 1. Group assertions by their object value +/// 2. For each group, calculate aggregate vote weight +/// 3. Calculate normalized Shannon entropy as conflict score +/// 4. Build ClaimSummary for each group with supporting agents +/// 5. Return all claims ranked by weight_share +/// +/// # Status Determination +/// +/// | Conflict Score | Status | +/// |----------------|--------| +/// | < 0.1 | Unanimous | +/// | < 0.4 | Agreed | +/// | >= 0.4 | Contested | +pub struct SkepticLens { + vote_store: Arc, + trust_store: Arc, +} + +impl SkepticLens { + /// Create a new SkepticLens with the given VoteStore and TrustRankStore. + pub fn new(vote_store: Arc, trust_store: Arc) -> Self { + Self { vote_store, trust_store } + } + + /// Compute the content-addressed hash of an assertion. + fn compute_assertion_hash(assertion: &Assertion) -> Hash { + let bytes = match stemedb_core::serde::serialize(assertion) { + Ok(b) => b, + Err(_) => return [0u8; 32], + }; + let hash_bytes = blake3::hash(&bytes); + *hash_bytes.as_bytes() + } + + /// Calculate normalized Shannon entropy for conflict score. + /// + /// # Arguments + /// * `weights` - Vector of (ObjectValue, aggregate_weight) tuples + /// + /// # Returns + /// Normalized entropy between 0.0 (unanimous) and 1.0 (maximum chaos) + fn calculate_conflict_score(weights: &[(ObjectValue, f32)]) -> f32 { + if weights.len() <= 1 { + return 0.0; // Unanimous by definition + } + + let total_weight: f32 = weights.iter().map(|(_, w)| w).sum(); + if total_weight <= 0.0 { + return 0.0; + } + + // Shannon entropy: H = -sum(p * log2(p)) + let entropy: f32 = weights + .iter() + .filter(|(_, w)| *w > 0.0) + .map(|(_, w)| { + let p = w / total_weight; + -p * p.log2() + }) + .sum(); + + // Normalize by max possible entropy (log2(n) for n claims) + let max_entropy = (weights.len() as f32).log2(); + if max_entropy <= 0.0 { + return 0.0; + } + + (entropy / max_entropy).min(1.0) + } + + /// Get aggregate vote weight for an assertion. + /// + /// If the assertion has votes, returns the aggregate vote weight. + /// If no votes exist, falls back to the assertion's own confidence score. + async fn get_assertion_weight(&self, assertion: &Assertion) -> f32 { + let hash = Self::compute_assertion_hash(assertion); + match self.vote_store.get_aggregate_weight(&hash).await { + Ok(weight) if weight > 0.0 => weight, + Ok(_) => { + // No votes exist, fall back to assertion confidence + debug!( + assertion_hash = %hex::encode(hash), + confidence = assertion.confidence, + "No votes found, using assertion confidence" + ); + assertion.confidence + } + Err(e) => { + debug!( + assertion_hash = %hex::encode(hash), + error = %e, + "Failed to get vote weight, using assertion confidence" + ); + assertion.confidence + } + } + } + + /// Build a ClaimSummary for a group of assertions with the same object value. + async fn build_claim_summary( + &self, + value: ObjectValue, + weight_share: f32, + assertions: &[&Assertion], + ) -> ClaimSummary { + // Find the representative assertion (highest confidence) + let representative = assertions + .iter() + .max_by(|a, b| { + a.confidence.partial_cmp(&b.confidence).unwrap_or(std::cmp::Ordering::Equal) + }) + .copied(); + + let representative_hash = + representative.map(Self::compute_assertion_hash).unwrap_or([0u8; 32]); + + // Build source summary from representative + let source = representative + .map(|a| SourceSummary { source_hash: a.source_hash, visual_hash: a.visual_hash }) + .unwrap_or(SourceSummary { source_hash: [0u8; 32], visual_hash: None }); + + // Collect unique agents from all assertions in this group + let mut agent_ids: Vec<[u8; 32]> = Vec::new(); + for assertion in assertions { + for sig in &assertion.signatures { + if !agent_ids.contains(&sig.agent_id) { + agent_ids.push(sig.agent_id); + } + } + } + + // Build AgentSummary with trust scores + let mut supporting_agents = Vec::with_capacity(agent_ids.len()); + for agent_id in agent_ids { + let trust_score = match self.trust_store.get_trust_rank(&agent_id).await { + Ok(trust_rank) => trust_rank.score, + Err(_) => 0.5, // Default for unknown agents + }; + supporting_agents.push(AgentSummary { agent_id, trust_score }); + } + + ClaimSummary { + value, + weight_share, + assertion_count: assertions.len() as u32, + representative_hash, + source, + supporting_agents, + } + } +} + +#[async_trait] +impl AnalysisLens for SkepticLens { + #[instrument(skip(self, candidates), fields(candidates_count = candidates.len()))] + async fn analyze(&self, candidates: &[Assertion]) -> ConflictAnalysis { + if candidates.is_empty() { + return ConflictAnalysis::empty(); + } + + // Step 1: Group assertions by object value + let mut groups: HashMap> = HashMap::new(); + for assertion in candidates { + let key = format!("{:?}", assertion.object); + groups.entry(key).or_default().push(assertion); + } + + // Step 2: Calculate aggregate weight for each group + let mut group_weights: Vec<(ObjectValue, f32, Vec<&Assertion>)> = + Vec::with_capacity(groups.len()); + + for assertions in groups.values() { + let mut total_weight = 0.0_f32; + for assertion in assertions { + total_weight += self.get_assertion_weight(assertion).await; + } + + // Use the object value from the first assertion in the group + if let Some(first) = assertions.first() { + group_weights.push((first.object.clone(), total_weight, assertions.clone())); + } + } + + // Step 3: Calculate conflict score + let weight_pairs: Vec<(ObjectValue, f32)> = + group_weights.iter().map(|(v, w, _)| (v.clone(), *w)).collect(); + let conflict_score = Self::calculate_conflict_score(&weight_pairs); + let status = ResolutionStatus::from_conflict_score(conflict_score, groups.len()); + + debug!( + conflict_score, + claim_count = groups.len(), + status = ?status, + "Calculated conflict analysis" + ); + + // Step 4: Calculate total weight for normalization + let total_weight: f32 = group_weights.iter().map(|(_, w, _)| w).sum(); + + // Step 5: Build ClaimSummaries + let mut claims = Vec::with_capacity(group_weights.len()); + for (value, weight, assertions) in group_weights { + let weight_share = if total_weight > 0.0 { weight / total_weight } else { 0.0 }; + let claim = self.build_claim_summary(value, weight_share, &assertions).await; + claims.push(claim); + } + + // Step 6: Sort claims by weight_share descending + claims.sort_by(|a, b| { + b.weight_share.partial_cmp(&a.weight_share).unwrap_or(std::cmp::Ordering::Equal) + }); + + ConflictAnalysis { status, conflict_score, claims, candidates_count: candidates.len() } + } + + fn name(&self) -> &'static str { + "Skeptic" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use stemedb_core::testing::AssertionBuilder; + use stemedb_core::types::Vote; + use stemedb_storage::{GenericTrustRankStore, GenericVoteStore, SledStore}; + + fn create_assertion(subject: &str, value: f64, confidence: f32) -> Assertion { + AssertionBuilder::new() + .subject(subject) + .predicate("test_predicate") + .object_number(value) + .confidence(confidence) + .build() + } + + fn create_text_assertion(subject: &str, text: &str, confidence: f32) -> Assertion { + AssertionBuilder::new() + .subject(subject) + .predicate("test_predicate") + .object_text(text) + .confidence(confidence) + .build() + } + + #[tokio::test] + async fn test_empty_candidates() { + let store = SledStore::open_temp().expect("store"); + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = SkepticLens::new(vote_store, trust_store); + + let analysis = lens.analyze(&[]).await; + + assert_eq!(analysis.status, ResolutionStatus::Unanimous); + assert!((analysis.conflict_score - 0.0).abs() < f32::EPSILON); + assert!(analysis.claims.is_empty()); + assert_eq!(analysis.candidates_count, 0); + } + + #[tokio::test] + async fn test_single_candidate_is_unanimous() { + let store = SledStore::open_temp().expect("store"); + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = SkepticLens::new(vote_store, trust_store); + + let assertion = create_assertion("Tesla", 100.0, 0.9); + let analysis = lens.analyze(&[assertion]).await; + + assert_eq!(analysis.status, ResolutionStatus::Unanimous); + assert!((analysis.conflict_score - 0.0).abs() < f32::EPSILON); + assert_eq!(analysis.claims.len(), 1); + assert!((analysis.claims[0].weight_share - 1.0).abs() < f32::EPSILON); + } + + #[tokio::test] + async fn test_same_value_is_unanimous() { + let store = SledStore::open_temp().expect("store"); + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = SkepticLens::new(vote_store, trust_store); + + // Three assertions all claiming the same value + let a1 = create_assertion("Tesla", 100.0, 0.9); + let a2 = create_assertion("Tesla", 100.0, 0.8); + let a3 = create_assertion("Tesla", 100.0, 0.7); + let analysis = lens.analyze(&[a1, a2, a3]).await; + + assert_eq!(analysis.status, ResolutionStatus::Unanimous); + assert!((analysis.conflict_score - 0.0).abs() < f32::EPSILON); + assert_eq!(analysis.claims.len(), 1); + assert_eq!(analysis.claims[0].assertion_count, 3); + } + + #[tokio::test] + async fn test_50_50_split_is_contested() { + let store = SledStore::open_temp().expect("store"); + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = SkepticLens::new(vote_store, trust_store); + + // Two claims with equal confidence (no votes) + let a1 = create_assertion("Tesla", 100.0, 0.5); + let a2 = create_assertion("Tesla", 200.0, 0.5); + let analysis = lens.analyze(&[a1, a2]).await; + + // 50/50 split should have max entropy for 2 options = 1.0 + assert_eq!(analysis.status, ResolutionStatus::Contested); + assert!((analysis.conflict_score - 1.0).abs() < 0.01); + assert_eq!(analysis.claims.len(), 2); + } + + #[tokio::test] + async fn test_strong_majority_is_agreed() { + let store = SledStore::open_temp().expect("store"); + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = SkepticLens::new(vote_store, trust_store); + + // 95/5 split - needs to be more extreme to get low entropy + let a1 = create_assertion("Tesla", 100.0, 0.95); + let a2 = create_assertion("Tesla", 200.0, 0.05); + let analysis = lens.analyze(&[a1, a2]).await; + + // 95/5 split has entropy ≈ 0.286, which is < 0.4 (Agreed) + assert!(analysis.conflict_score < 0.4); + assert!( + analysis.status == ResolutionStatus::Agreed + || analysis.status == ResolutionStatus::Unanimous + ); + } + + #[tokio::test] + async fn test_claims_sorted_by_weight() { + let store = SledStore::open_temp().expect("store"); + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = SkepticLens::new(vote_store, trust_store); + + let a1 = create_assertion("Tesla", 100.0, 0.3); // Lowest + let a2 = create_assertion("Tesla", 200.0, 0.9); // Highest + let a3 = create_assertion("Tesla", 300.0, 0.5); // Middle + let analysis = lens.analyze(&[a1, a2, a3]).await; + + assert_eq!(analysis.claims.len(), 3); + // Should be sorted descending by weight_share + assert!(analysis.claims[0].weight_share >= analysis.claims[1].weight_share); + assert!(analysis.claims[1].weight_share >= analysis.claims[2].weight_share); + } + + #[tokio::test] + async fn test_text_value_grouping() { + let store = SledStore::open_temp().expect("store"); + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = SkepticLens::new(vote_store, trust_store); + + let a1 = create_text_assertion("Drug", "Effective", 0.6); + let a2 = create_text_assertion("Drug", "Ineffective", 0.4); + let a3 = create_text_assertion("Drug", "Effective", 0.5); // Same as a1 + let analysis = lens.analyze(&[a1, a2, a3]).await; + + // Should group into 2 claims: "Effective" (2 assertions) and "Ineffective" (1) + assert_eq!(analysis.claims.len(), 2); + assert_eq!(analysis.candidates_count, 3); + + // Find the "Effective" claim + let effective_claim = analysis + .claims + .iter() + .find(|c| matches!(&c.value, ObjectValue::Text(t) if t == "Effective")); + assert!(effective_claim.is_some()); + assert_eq!(effective_claim.map(|c| c.assertion_count).unwrap_or(0), 2); + } + + #[tokio::test] + async fn test_conflict_score_calculation() { + // Test the entropy calculation directly + // 50/50 split: max entropy for 2 options = 1.0 + let weights_equal = vec![(ObjectValue::Number(1.0), 0.5), (ObjectValue::Number(2.0), 0.5)]; + let score = SkepticLens::, GenericTrustRankStore>::calculate_conflict_score(&weights_equal); + assert!((score - 1.0).abs() < 0.01); + + // 100/0 split: zero entropy + let weights_unanimous = + vec![(ObjectValue::Number(1.0), 1.0), (ObjectValue::Number(2.0), 0.0)]; + let score = SkepticLens::, GenericTrustRankStore>::calculate_conflict_score(&weights_unanimous); + assert!((score - 0.0).abs() < 0.01); + + // Single claim: unanimous + let weights_single = vec![(ObjectValue::Number(1.0), 1.0)]; + let score = SkepticLens::, GenericTrustRankStore>::calculate_conflict_score(&weights_single); + assert!((score - 0.0).abs() < 0.01); + } + + #[tokio::test] + async fn test_lens_name() { + let store = SledStore::open_temp().expect("store"); + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = SkepticLens::new(vote_store, trust_store); + + assert_eq!(lens.name(), "Skeptic"); + } + + #[tokio::test] + async fn test_with_votes() { + let store = SledStore::open_temp().expect("store"); + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = SkepticLens::new(Arc::clone(&vote_store), trust_store); + + // Create two assertions with different values + let a1 = create_assertion("Tesla", 100.0, 0.5); + let a2 = create_assertion("Tesla", 200.0, 0.5); + + // Add votes to make a1 a strong winner + let hash1 = + SkepticLens::, GenericTrustRankStore>::compute_assertion_hash(&a1); + let hash2 = + SkepticLens::, GenericTrustRankStore>::compute_assertion_hash(&a2); + + // a1 gets 10 votes totaling 9.0 weight (strong majority) + for i in 0..10 { + let vote = Vote { + assertion_hash: hash1, + agent_id: [i as u8; 32], + weight: 0.9, + signature: [0u8; 64], + timestamp: 1000 + i as u64, + }; + vote_store.put_vote(&vote).await.expect("put vote"); + } + + // a2 gets 1 vote with 0.5 weight (minority) + let vote = Vote { + assertion_hash: hash2, + agent_id: [20u8; 32], + weight: 0.5, + signature: [0u8; 64], + timestamp: 2000, + }; + vote_store.put_vote(&vote).await.expect("put vote"); + + let analysis = lens.analyze(&[a1, a2]).await; + + // a1 should have higher weight_share + assert_eq!(analysis.claims.len(), 2); + let first_claim = &analysis.claims[0]; + let second_claim = &analysis.claims[1]; + + assert!( + first_claim.weight_share > second_claim.weight_share, + "First claim ({:.2}) should have higher weight than second ({:.2})", + first_claim.weight_share, + second_claim.weight_share + ); + + // With 9.0 / 9.5 ≈ 0.947 for first claim, entropy should be very low + // Actually: -0.947*log2(0.947) - 0.053*log2(0.053) ≈ 0.296 + assert!( + analysis.conflict_score < 0.4, + "Conflict score {} should be < 0.4 for strong majority", + analysis.conflict_score + ); + } +} diff --git a/crates/stemedb-lens/src/traits.rs b/crates/stemedb-lens/src/traits.rs new file mode 100644 index 0000000..7d3e06b --- /dev/null +++ b/crates/stemedb-lens/src/traits.rs @@ -0,0 +1,125 @@ +//! Core Lens trait and types. +//! +//! The Lens trait is the fundamental abstraction for resolving conflicting +//! assertions into a deterministic answer. +//! +//! # Two Kinds of Lenses +//! +//! | Trait | Purpose | Returns | +//! |-------|---------|---------| +//! | `Lens` / `AsyncLens` | Pick a winner | `Resolution` (single assertion) | +//! | `AnalysisLens` | Map conflict landscape | `ConflictAnalysis` (all claims) | +//! +//! Use `Lens` when you need "the answer". Use `AnalysisLens` when you need +//! "Trust but Verify" - showing users what's contested. + +use async_trait::async_trait; +use stemedb_core::types::{Assertion, ConflictAnalysis}; + +/// The result of a Lens resolution. +#[derive(Debug, Clone)] +pub struct Resolution { + /// The winning assertion, if any candidates were provided. + pub winner: Option, + + /// All candidates that were considered. + pub candidates_count: usize, + + /// Confidence in the resolution (0.0 to 1.0). + /// Higher values indicate stronger consensus or more decisive selection. + pub resolution_confidence: f32, +} + +impl Resolution { + /// Create an empty resolution (no candidates). + pub fn empty() -> Self { + Self { winner: None, candidates_count: 0, resolution_confidence: 0.0 } + } + + /// Create a resolution with a single winner. + pub fn with_winner(winner: Assertion, candidates_count: usize, confidence: f32) -> Self { + Self { winner: Some(winner), candidates_count, resolution_confidence: confidence } + } +} + +/// A Lens resolves conflicting assertions into a deterministic answer. +/// +/// # Contract +/// +/// - **Stateless:** Lenses must not maintain internal state. +/// - **Deterministic:** Same input must produce same output. +/// - **Fast:** Runs on every read, avoid allocations where possible. +/// +/// # Implementation Notes +/// +/// Lenses should handle edge cases gracefully: +/// - Empty input: Return `Resolution::empty()` +/// - Single candidate: Return that candidate (trivial resolution) +/// - Ties: Define a consistent tiebreaker (e.g., lowest hash) +pub trait Lens: Send + Sync { + /// Resolve a set of candidate assertions into a single answer. + /// + /// # Arguments + /// * `candidates` - All assertions matching the query filters + /// + /// # Returns + /// A resolution containing the winning assertion (if any) and metadata. + fn resolve(&self, candidates: &[Assertion]) -> Resolution; + + /// Human-readable name of this lens for logging/debugging. + fn name(&self) -> &'static str; +} + +/// An AnalysisLens maps the conflict landscape instead of picking a winner. +/// +/// Unlike `Lens` which collapses uncertainty into a single answer, `AnalysisLens` +/// surfaces all competing claims with their relative support. This enables +/// "Trust but Verify" UX where users see disagreement explicitly. +/// +/// # Contract +/// +/// - **Stateless:** AnalysisLenses must not maintain internal state. +/// - **Deterministic:** Same input and storage state produces same output. +/// - **Complete:** Returns ALL distinct claims, not just the top one. +/// +/// # When to Use +/// +/// Use `AnalysisLens` when: +/// - User needs to see "who disagrees and why" +/// - Fact is contested and hiding conflict would be misleading +/// - Building a "Living Review" dashboard for research +/// +/// Use regular `Lens` when: +/// - You need a definitive answer for action +/// - Conflict is resolved elsewhere +/// - Performance is critical (Analysis is more expensive) +#[async_trait] +pub trait AnalysisLens: Send + Sync { + /// Analyze a set of candidate assertions and return the conflict landscape. + /// + /// # Arguments + /// * `candidates` - All assertions matching the query filters + /// + /// # Returns + /// A `ConflictAnalysis` containing: + /// - `status`: Unanimous, Agreed, or Contested + /// - `conflict_score`: 0.0 (unanimous) to 1.0 (chaos) + /// - `claims`: All distinct claims ranked by support + async fn analyze(&self, candidates: &[Assertion]) -> ConflictAnalysis; + + /// Human-readable name of this lens for logging/debugging. + fn name(&self) -> &'static str; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_empty_resolution() { + let resolution = Resolution::empty(); + assert!(resolution.winner.is_none()); + assert_eq!(resolution.candidates_count, 0); + assert!((resolution.resolution_confidence - 0.0).abs() < f32::EPSILON); + } +} diff --git a/crates/stemedb-lens/src/trust_aware_authority.rs b/crates/stemedb-lens/src/trust_aware_authority.rs new file mode 100644 index 0000000..a3265bf --- /dev/null +++ b/crates/stemedb-lens/src/trust_aware_authority.rs @@ -0,0 +1,473 @@ +//! TrustRank-Aware Authority Lens: Resolves based on agent reputation. +//! +//! This lens integrates with TrustRank to weight assertions by the reputation +//! of the signing agent. This is the production implementation of the Authority +//! lens for Phase 4 (The Hive). +//! +//! # Design Philosophy +//! +//! Follows the "Deep Module" principle: +//! - Simple interface: `resolve_async(&[Assertion])` returns winner +//! - Complex implementation: Queries TrustRankStore, weights by reputation +//! - O(1) trust lookups via TrustRankStore + +use crate::traits::Resolution; +use async_trait::async_trait; +use stemedb_core::types::Assertion; +use stemedb_storage::trust_rank_store::TrustRankStore; +use tracing::{debug, instrument}; + +/// Async version of the Lens trait for operations requiring I/O. +/// +/// Re-exported from vote_aware_consensus for consistency across async lenses. +pub use crate::vote_aware_consensus::AsyncLens; + +/// TrustRank-Aware Authority Lens: Returns the assertion with the highest reputation-weighted confidence. +/// +/// # Resolution Strategy +/// +/// 1. For each candidate assertion, lookup the primary signer's TrustRank +/// 2. Calculate weighted score: `assertion.confidence * agent.trust_rank` +/// 3. Return the assertion with highest weighted score +/// 4. Tiebreaker: If scores are equal, prefer most recent timestamp +/// 5. Agents with no TrustRank default to 0.5 (neutral reputation) +/// +/// # Multi-Signature Handling +/// +/// Currently uses the first signature's agent_id as the primary authority. +/// Future enhancement: Aggregate multiple signers' TrustRanks. +/// +/// # Confidence Calculation +/// +/// Resolution confidence is the winning assertion's weighted score normalized +/// by the maximum possible score (if the agent had perfect trust rank). +/// +/// # Example +/// +/// ```ignore +/// use stemedb_lens::TrustAwareAuthorityLens; +/// use stemedb_storage::{SledStore, GenericTrustRankStore}; +/// use std::sync::Arc; +/// +/// let store = SledStore::open("./data").await?; +/// let trust_store = Arc::new(GenericTrustRankStore::new(store)); +/// let lens = TrustAwareAuthorityLens::new(trust_store); +/// +/// let resolution = lens.resolve_async(&candidates).await; +/// ``` +pub struct TrustAwareAuthorityLens { + trust_store: std::sync::Arc, +} + +impl TrustAwareAuthorityLens { + /// Create a new TrustAwareAuthorityLens with the given TrustRankStore. + /// + /// The TrustRankStore is wrapped in an Arc for shared ownership, allowing + /// the lens to be used in multiple contexts. + pub fn new(trust_store: std::sync::Arc) -> Self { + Self { trust_store } + } + + /// Extract the primary agent ID from an assertion. + /// + /// Uses the first signature's agent_id. Returns None if no signatures exist. + fn get_primary_agent(assertion: &Assertion) -> Option<[u8; 32]> { + assertion.signatures.first().map(|sig| sig.agent_id) + } +} + +/// Internal struct to track assertion ranking data. +#[derive(Debug)] +struct RankedAssertion<'a> { + assertion: &'a Assertion, + trust_score: f32, + weighted_score: f32, +} + +#[async_trait] +impl AsyncLens for TrustAwareAuthorityLens { + #[instrument(skip(self, candidates), fields(candidates_count = candidates.len()))] + async fn resolve_async(&self, candidates: &[Assertion]) -> Resolution { + if candidates.is_empty() { + return Resolution::empty(); + } + + // Even for single candidate, we need to calculate weighted score + if candidates.len() == 1 { + let assertion = &candidates[0]; + let agent_id = match Self::get_primary_agent(assertion) { + Some(id) => id, + None => { + // No signature, treat as untrusted + return Resolution::with_winner(assertion.clone(), 1, 0.0); + } + }; + + let trust_score = match self.trust_store.get_trust_rank(&agent_id).await { + Ok(trust_rank) => trust_rank.score, + Err(_) => 0.5, // Default trust score + }; + + let weighted_score = assertion.confidence * trust_score; + return Resolution::with_winner(assertion.clone(), 1, weighted_score); + } + + // Collect trust-weighted scores for all candidates + let mut ranked: Vec = Vec::with_capacity(candidates.len()); + + for assertion in candidates { + // Extract primary agent + let agent_id = match Self::get_primary_agent(assertion) { + Some(id) => id, + None => { + debug!( + subject = %assertion.subject, + "Assertion has no signatures, treating as untrusted" + ); + ranked.push(RankedAssertion { + assertion, + trust_score: 0.0, + weighted_score: 0.0, + }); + continue; + } + }; + + // Lookup agent's TrustRank + let trust_score = match self.trust_store.get_trust_rank(&agent_id).await { + Ok(trust_rank) => trust_rank.score, + Err(e) => { + debug!( + agent_id = %hex::encode(agent_id), + error = %e, + "Failed to get TrustRank, using default" + ); + 0.5 // Default trust score for new/unknown agents + } + }; + + // Calculate weighted score: assertion confidence * agent trust + let weighted_score = assertion.confidence * trust_score; + + debug!( + subject = %assertion.subject, + agent_id = %hex::encode(agent_id), + confidence = assertion.confidence, + trust_score, + weighted_score, + "Calculated weighted score" + ); + + ranked.push(RankedAssertion { assertion, trust_score, weighted_score }); + } + + // Sort by weighted score (descending), then by timestamp (descending) for ties + ranked.sort_by(|a, b| { + b.weighted_score + .partial_cmp(&a.weighted_score) + .unwrap_or(std::cmp::Ordering::Equal) + .then_with(|| b.assertion.timestamp.cmp(&a.assertion.timestamp)) + }); + + // Select the winner (highest ranked) + if let Some(winner_ranked) = ranked.first() { + // Resolution confidence is the weighted score + // This represents how much we trust this assertion given both + // the assertion's own confidence and the agent's reputation + let confidence = winner_ranked.weighted_score; + + debug!( + winner_subject = %winner_ranked.assertion.subject, + trust_score = winner_ranked.trust_score, + assertion_confidence = winner_ranked.assertion.confidence, + weighted_score = winner_ranked.weighted_score, + "Resolved via trust-aware authority" + ); + + Resolution::with_winner(winner_ranked.assertion.clone(), candidates.len(), confidence) + } else { + // Should never happen since we checked for empty candidates above + Resolution::empty() + } + } + + fn name(&self) -> &'static str { + "TrustAwareAuthority" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + use stemedb_core::testing::AssertionBuilder; + use stemedb_storage::{GenericTrustRankStore, SledStore, TrustRank, TrustRankStore}; + + fn create_assertion( + subject: &str, + confidence: f32, + agent_id: [u8; 32], + timestamp: u64, + ) -> Assertion { + AssertionBuilder::new() + .subject(subject) + .confidence(confidence) + .agent_id(agent_id) + .timestamp(timestamp) + .build() + } + + #[tokio::test] + async fn test_empty_candidates() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = TrustAwareAuthorityLens::new(trust_store); + + let resolution = lens.resolve_async(&[]).await; + + assert!(resolution.winner.is_none()); + assert_eq!(resolution.candidates_count, 0); + } + + #[tokio::test] + async fn test_single_candidate() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = TrustAwareAuthorityLens::new(trust_store); + + let assertion = create_assertion("Tesla", 0.8, [1u8; 32], 1000); + let resolution = lens.resolve_async(std::slice::from_ref(&assertion)).await; + + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().unwrap().subject, "Tesla"); + // Single candidate with default trust (0.5): 0.8 * 0.5 = 0.4 + assert!((resolution.resolution_confidence - 0.4).abs() < 0.01); + } + + #[tokio::test] + async fn test_selects_highest_weighted_score() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = TrustAwareAuthorityLens::new(Arc::clone(&trust_store)); + + // Set up agents with different trust scores + let agent_low = [1u8; 32]; + let agent_high = [2u8; 32]; + + let mut trust_low = TrustRank::new(agent_low, 1000); + trust_low.score = 0.3; // Low trust + trust_store.put_trust_rank(&trust_low).await.expect("put"); + + let mut trust_high = TrustRank::new(agent_high, 1000); + trust_high.score = 0.9; // High trust + trust_store.put_trust_rank(&trust_high).await.expect("put"); + + // Create assertions with same confidence but different agents + let a1 = create_assertion("LowTrust", 0.8, agent_low, 1000); + let a2 = create_assertion("HighTrust", 0.8, agent_high, 1100); + + // a1: 0.8 * 0.3 = 0.24 + // a2: 0.8 * 0.9 = 0.72 (winner) + + let resolution = lens.resolve_async(&[a1, a2.clone()]).await; + + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().unwrap().subject, "HighTrust"); + + // Confidence should be the weighted score + assert!((resolution.resolution_confidence - 0.72).abs() < 0.01); + } + + #[tokio::test] + async fn test_high_confidence_low_trust_vs_low_confidence_high_trust() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = TrustAwareAuthorityLens::new(Arc::clone(&trust_store)); + + let agent1 = [1u8; 32]; + let agent2 = [2u8; 32]; + + let mut trust1 = TrustRank::new(agent1, 1000); + trust1.score = 0.4; // Low trust + trust_store.put_trust_rank(&trust1).await.expect("put"); + + let mut trust2 = TrustRank::new(agent2, 1000); + trust2.score = 0.9; // High trust + trust_store.put_trust_rank(&trust2).await.expect("put"); + + // High confidence but low trust + let a1 = create_assertion("HighConf", 0.95, agent1, 1000); + // Low confidence but high trust + let a2 = create_assertion("LowConf", 0.5, agent2, 1100); + + // a1: 0.95 * 0.4 = 0.38 + // a2: 0.5 * 0.9 = 0.45 (winner) + + let resolution = lens.resolve_async(&[a1, a2.clone()]).await; + + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().unwrap().subject, "LowConf"); + } + + #[tokio::test] + async fn test_default_trust_for_new_agent() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = TrustAwareAuthorityLens::new(trust_store); + + // Agent with no stored TrustRank (will default to 0.5) + let new_agent = [99u8; 32]; + let assertion = create_assertion("NewAgent", 0.8, new_agent, 1000); + + let resolution = lens.resolve_async(std::slice::from_ref(&assertion)).await; + + assert!(resolution.winner.is_some()); + // 0.8 * 0.5 (default) = 0.4 + assert!((resolution.resolution_confidence - 0.4).abs() < 0.01); + } + + #[tokio::test] + async fn test_no_signatures_treated_as_untrusted() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = TrustAwareAuthorityLens::new(Arc::clone(&trust_store)); + + let agent_trusted = [1u8; 32]; + let mut trust = TrustRank::new(agent_trusted, 1000); + trust.score = 0.8; + trust_store.put_trust_rank(&trust).await.expect("put"); + + let trusted = create_assertion("Trusted", 0.7, agent_trusted, 1000); + + // Create assertion with no signatures + let mut untrusted = create_assertion("Untrusted", 0.9, [0u8; 32], 1100); + untrusted.signatures.clear(); + + let resolution = lens.resolve_async(&[trusted.clone(), untrusted]).await; + + // Should pick the trusted one even though untrusted has higher confidence + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().unwrap().subject, "Trusted"); + } + + #[tokio::test] + async fn test_tie_breaking_by_timestamp() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = TrustAwareAuthorityLens::new(Arc::clone(&trust_store)); + + let agent = [1u8; 32]; + let mut trust = TrustRank::new(agent, 1000); + trust.score = 0.8; + trust_store.put_trust_rank(&trust).await.expect("put"); + + // Same agent, same confidence, different timestamps + let older = create_assertion("Older", 0.7, agent, 1000); + let newer = create_assertion("Newer", 0.7, agent, 2000); + + // Both: 0.7 * 0.8 = 0.56 + let resolution = lens.resolve_async(&[older, newer.clone()]).await; + + // With equal weighted scores, should pick the newer timestamp + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().unwrap().subject, "Newer"); + } + + #[tokio::test] + async fn test_lens_name() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = TrustAwareAuthorityLens::new(trust_store); + + assert_eq!(lens.name(), "TrustAwareAuthority"); + } + + #[tokio::test] + async fn test_multiple_candidates_different_trust_levels() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = TrustAwareAuthorityLens::new(Arc::clone(&trust_store)); + + // Create agents with varying trust levels + let agent_novice = [1u8; 32]; + let agent_expert = [2u8; 32]; + let agent_master = [3u8; 32]; + + let mut trust_novice = TrustRank::new(agent_novice, 1000); + trust_novice.score = 0.2; + trust_store.put_trust_rank(&trust_novice).await.expect("put"); + + let mut trust_expert = TrustRank::new(agent_expert, 1000); + trust_expert.score = 0.7; + trust_store.put_trust_rank(&trust_expert).await.expect("put"); + + let mut trust_master = TrustRank::new(agent_master, 1000); + trust_master.score = 0.95; + trust_store.put_trust_rank(&trust_master).await.expect("put"); + + let a1 = create_assertion("Novice", 0.9, agent_novice, 1000); + let a2 = create_assertion("Expert", 0.8, agent_expert, 1100); + let a3 = create_assertion("Master", 0.75, agent_master, 1200); + + // a1: 0.9 * 0.2 = 0.18 + // a2: 0.8 * 0.7 = 0.56 + // a3: 0.75 * 0.95 = 0.7125 (winner) + + let resolution = lens.resolve_async(&[a1, a2, a3.clone()]).await; + + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().unwrap().subject, "Master"); + assert!((resolution.resolution_confidence - 0.7125).abs() < 0.01); + } + + #[tokio::test] + async fn test_zero_trust_agent() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = TrustAwareAuthorityLens::new(Arc::clone(&trust_store)); + + let agent_banned = [1u8; 32]; + let agent_good = [2u8; 32]; + + // Banned agent with 0 trust (perhaps due to repeated inaccuracies) + let mut trust_banned = TrustRank::new(agent_banned, 1000); + trust_banned.score = 0.0; + trust_store.put_trust_rank(&trust_banned).await.expect("put"); + + let mut trust_good = TrustRank::new(agent_good, 1000); + trust_good.score = 0.6; + trust_store.put_trust_rank(&trust_good).await.expect("put"); + + let banned_assertion = create_assertion("Banned", 1.0, agent_banned, 1000); + let good_assertion = create_assertion("Good", 0.5, agent_good, 1100); + + // banned: 1.0 * 0.0 = 0.0 + // good: 0.5 * 0.6 = 0.3 (winner) + + let resolution = lens.resolve_async(&[banned_assertion, good_assertion.clone()]).await; + + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().unwrap().subject, "Good"); + } + + #[tokio::test] + async fn test_perfect_trust_agent() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = Arc::new(GenericTrustRankStore::new(store)); + let lens = TrustAwareAuthorityLens::new(Arc::clone(&trust_store)); + + let agent_perfect = [1u8; 32]; + + let mut trust_perfect = TrustRank::new(agent_perfect, 1000); + trust_perfect.score = 1.0; + trust_store.put_trust_rank(&trust_perfect).await.expect("put"); + + let assertion = create_assertion("Perfect", 0.85, agent_perfect, 1000); + + let resolution = lens.resolve_async(std::slice::from_ref(&assertion)).await; + + assert!(resolution.winner.is_some()); + // 0.85 * 1.0 = 0.85 + assert!((resolution.resolution_confidence - 0.85).abs() < 0.01); + } +} diff --git a/crates/stemedb-lens/src/vote_aware_consensus.rs b/crates/stemedb-lens/src/vote_aware_consensus.rs new file mode 100644 index 0000000..a69dfdb --- /dev/null +++ b/crates/stemedb-lens/src/vote_aware_consensus.rs @@ -0,0 +1,408 @@ +//! Vote-Aware Consensus Lens: Resolves based on actual vote counts from VoteStore. +//! +//! This lens integrates with the Ballot Box pattern to use real vote counts +//! instead of grouping by object value like the basic ConsensusLens. +//! +//! # Design Philosophy +//! +//! Follows the "Deep Module" principle: +//! - Simple interface: `resolve_async(&[Assertion])` returns winner +//! - Complex implementation: Queries VoteStore, ranks by votes, handles ties +//! - O(1) vote lookups via VoteStore's cached counters + +use crate::traits::Resolution; +use async_trait::async_trait; +use stemedb_core::types::{Assertion, Hash}; +use stemedb_storage::vote_store::VoteStore; +use tracing::{debug, instrument}; + +/// Async version of the Lens trait for operations requiring I/O. +/// +/// # Contract +/// +/// - **Stateless:** AsyncLenses must not maintain internal state. +/// - **Deterministic:** Same input and storage state produces same output. +/// - **Fast:** Uses cached vote counts from VoteStore for O(1) lookups. +/// +/// # Implementation Notes +/// +/// AsyncLenses should handle edge cases gracefully: +/// - Empty input: Return `Resolution::empty()` +/// - Single candidate: Return that candidate (trivial resolution) +/// - Ties: Define a consistent tiebreaker (e.g., highest timestamp) +/// - Assertions with no votes: Treat as 0 votes/weight +#[async_trait] +pub trait AsyncLens: Send + Sync { + /// Resolve a set of candidate assertions into a single answer. + /// + /// # Arguments + /// * `candidates` - All assertions matching the query filters + /// + /// # Returns + /// A resolution containing the winning assertion (if any) and metadata. + async fn resolve_async(&self, candidates: &[Assertion]) -> Resolution; + + /// Human-readable name of this lens for logging/debugging. + fn name(&self) -> &'static str; +} + +/// Vote-Aware Consensus Lens: Returns the assertion with the highest vote count. +/// +/// # Resolution Strategy +/// +/// 1. For each candidate assertion, lookup its vote count and aggregate weight +/// 2. Rank assertions by aggregate weight (sum of all vote weights) +/// 3. Return the assertion with highest aggregate weight +/// 4. Tiebreaker: If weights are equal, prefer most recent timestamp +/// 5. Assertions with no votes are treated as having 0 weight +/// +/// # Confidence Calculation +/// +/// Resolution confidence is based on the winning assertion's vote proportion: +/// - `confidence = winner_weight / total_weight_across_all_candidates` +/// - If no votes exist for any candidate, confidence is 0.0 +/// - If only one candidate has votes, confidence is 1.0 +/// +/// # Example +/// +/// ```ignore +/// use stemedb_lens::VoteAwareConsensusLens; +/// use stemedb_storage::{SledStore, GenericVoteStore}; +/// use std::sync::Arc; +/// +/// let store = SledStore::open("./data").await?; +/// let vote_store = Arc::new(GenericVoteStore::new(store)); +/// let lens = VoteAwareConsensusLens::new(vote_store); +/// +/// let resolution = lens.resolve_async(&candidates).await?; +/// ``` +pub struct VoteAwareConsensusLens { + vote_store: std::sync::Arc, +} + +impl VoteAwareConsensusLens { + /// Create a new VoteAwareConsensusLens with the given VoteStore. + /// + /// The VoteStore is wrapped in an Arc for shared ownership, allowing + /// the lens to be used in multiple contexts. + pub fn new(vote_store: std::sync::Arc) -> Self { + Self { vote_store } + } + + /// Compute the content-addressed hash of an assertion. + /// + /// This matches the logic used by the ingestion pipeline to ensure + /// we lookup votes for the correct assertion hash. + fn compute_assertion_hash(assertion: &Assertion) -> Hash { + // Serialize using the canonical serde module, then hash. + // An empty hash is returned if serialization fails (defensive). + let bytes = match stemedb_core::serde::serialize(assertion) { + Ok(b) => b, + Err(_) => return [0u8; 32], + }; + + let hash_bytes = blake3::hash(&bytes); + *hash_bytes.as_bytes() + } +} + +/// Internal struct to track assertion ranking data. +#[derive(Debug)] +struct RankedAssertion<'a> { + assertion: &'a Assertion, + vote_count: u64, + aggregate_weight: f32, +} + +#[async_trait] +impl AsyncLens for VoteAwareConsensusLens { + #[instrument(skip(self, candidates), fields(candidates_count = candidates.len()))] + async fn resolve_async(&self, candidates: &[Assertion]) -> Resolution { + if candidates.is_empty() { + return Resolution::empty(); + } + + if candidates.len() == 1 { + return Resolution::with_winner(candidates[0].clone(), 1, 1.0); + } + + // Collect vote data for all candidates + let mut ranked: Vec = Vec::with_capacity(candidates.len()); + let mut total_weight = 0.0_f32; + + for assertion in candidates { + let assertion_hash = Self::compute_assertion_hash(assertion); + + // Lookup vote count and aggregate weight from VoteStore + // These are O(1) operations thanks to VoteStore's cached counters + let vote_count = match self.vote_store.get_vote_count(&assertion_hash).await { + Ok(count) => count, + Err(e) => { + debug!( + assertion_hash = %hex::encode(assertion_hash), + error = %e, + "Failed to get vote count, treating as 0" + ); + 0 + } + }; + + let aggregate_weight = match self.vote_store.get_aggregate_weight(&assertion_hash).await + { + Ok(weight) => weight, + Err(e) => { + debug!( + assertion_hash = %hex::encode(assertion_hash), + error = %e, + "Failed to get aggregate weight, treating as 0.0" + ); + 0.0 + } + }; + + total_weight += aggregate_weight; + + ranked.push(RankedAssertion { assertion, vote_count, aggregate_weight }); + } + + // Sort by aggregate weight (descending), then by timestamp (descending) for ties + ranked.sort_by(|a, b| { + b.aggregate_weight + .partial_cmp(&a.aggregate_weight) + .unwrap_or(std::cmp::Ordering::Equal) + .then_with(|| b.assertion.timestamp.cmp(&a.assertion.timestamp)) + }); + + // Select the winner (highest ranked) + if let Some(winner_ranked) = ranked.first() { + let confidence = if total_weight > 0.0 { + winner_ranked.aggregate_weight / total_weight + } else { + // No votes for any candidate + 0.0 + }; + + debug!( + winner_subject = %winner_ranked.assertion.subject, + vote_count = winner_ranked.vote_count, + aggregate_weight = winner_ranked.aggregate_weight, + confidence, + "Resolved via vote-aware consensus" + ); + + Resolution::with_winner(winner_ranked.assertion.clone(), candidates.len(), confidence) + } else { + // Should never happen since we checked for empty candidates above + Resolution::empty() + } + } + + fn name(&self) -> &'static str { + "VoteAwareConsensus" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + use stemedb_core::testing::{self, AssertionBuilder}; + use stemedb_core::types::Vote; + use stemedb_storage::{GenericVoteStore, SledStore}; + + fn create_assertion(subject: &str, value: f64, timestamp: u64) -> Assertion { + AssertionBuilder::new().subject(subject).object_number(value).timestamp(timestamp).build() + } + + fn create_vote(assertion_hash: Hash, agent_id: [u8; 32], weight: f32, timestamp: u64) -> Vote { + testing::test_vote(assertion_hash, agent_id, weight, timestamp) + } + + #[tokio::test] + async fn test_empty_candidates() { + let store = SledStore::open_temp().expect("Failed to create store"); + let vote_store = Arc::new(GenericVoteStore::new(store)); + let lens = VoteAwareConsensusLens::new(vote_store); + + let resolution = lens.resolve_async(&[]).await; + + assert!(resolution.winner.is_none()); + assert_eq!(resolution.candidates_count, 0); + } + + #[tokio::test] + async fn test_single_candidate() { + let store = SledStore::open_temp().expect("Failed to create store"); + let vote_store = Arc::new(GenericVoteStore::new(store)); + let lens = VoteAwareConsensusLens::new(vote_store); + + let assertion = create_assertion("Tesla", 100.0, 1000); + let resolution = lens.resolve_async(std::slice::from_ref(&assertion)).await; + + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().unwrap().subject, "Tesla"); + assert!((resolution.resolution_confidence - 1.0).abs() < f32::EPSILON); + } + + #[tokio::test] + async fn test_selects_highest_vote_weight() { + let store = SledStore::open_temp().expect("Failed to create store"); + let vote_store = Arc::new(GenericVoteStore::new(store)); + let lens = VoteAwareConsensusLens::new(Arc::clone(&vote_store)); + + // Create three assertions + let a1 = create_assertion("Agent1", 100.0, 1000); + let a2 = create_assertion("Agent2", 200.0, 1100); + let a3 = create_assertion("Agent3", 300.0, 1200); + + // Add votes: a1 gets 0.5 weight, a2 gets 1.5 weight (winner), a3 gets 0.3 weight + let hash1 = + VoteAwareConsensusLens::>::compute_assertion_hash(&a1); + let hash2 = + VoteAwareConsensusLens::>::compute_assertion_hash(&a2); + let hash3 = + VoteAwareConsensusLens::>::compute_assertion_hash(&a3); + + vote_store.put_vote(&create_vote(hash1, [1u8; 32], 0.5, 2000)).await.expect("put"); + vote_store.put_vote(&create_vote(hash2, [2u8; 32], 0.8, 2001)).await.expect("put"); + vote_store.put_vote(&create_vote(hash2, [3u8; 32], 0.7, 2002)).await.expect("put"); + vote_store.put_vote(&create_vote(hash3, [4u8; 32], 0.3, 2003)).await.expect("put"); + + let resolution = lens.resolve_async(&[a1, a2.clone(), a3]).await; + + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().unwrap().subject, "Agent2"); + + // Total weight = 0.5 + 0.8 + 0.7 + 0.3 = 2.3 + // Winner weight = 0.8 + 0.7 = 1.5 + // Confidence = 1.5 / 2.3 ≈ 0.652 + let expected_confidence = 1.5 / 2.3; + assert!((resolution.resolution_confidence - expected_confidence).abs() < 0.01); + } + + #[tokio::test] + async fn test_no_votes_returns_most_recent() { + let store = SledStore::open_temp().expect("Failed to create store"); + let vote_store = Arc::new(GenericVoteStore::new(store)); + let lens = VoteAwareConsensusLens::new(vote_store); + + let old = create_assertion("Old", 100.0, 1000); + let new = create_assertion("New", 200.0, 2000); + + let resolution = lens.resolve_async(&[old, new.clone()]).await; + + // When no votes exist, should fall back to timestamp tiebreaker + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().unwrap().subject, "New"); + + // Confidence should be 0.0 since no votes exist + assert!((resolution.resolution_confidence - 0.0).abs() < f32::EPSILON); + } + + #[tokio::test] + async fn test_tie_breaking_by_timestamp() { + let store = SledStore::open_temp().expect("Failed to create store"); + let vote_store = Arc::new(GenericVoteStore::new(store)); + let lens = VoteAwareConsensusLens::new(Arc::clone(&vote_store)); + + let old = create_assertion("Old", 100.0, 1000); + let new = create_assertion("New", 200.0, 2000); + + // Give both the same vote weight + let hash_old = + VoteAwareConsensusLens::>::compute_assertion_hash(&old); + let hash_new = + VoteAwareConsensusLens::>::compute_assertion_hash(&new); + + vote_store.put_vote(&create_vote(hash_old, [1u8; 32], 0.5, 3000)).await.expect("put"); + vote_store.put_vote(&create_vote(hash_new, [2u8; 32], 0.5, 3001)).await.expect("put"); + + let resolution = lens.resolve_async(&[old, new.clone()]).await; + + // With equal weights, should pick the newer timestamp + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().unwrap().subject, "New"); + } + + #[tokio::test] + async fn test_mixed_votes_and_no_votes() { + let store = SledStore::open_temp().expect("Failed to create store"); + let vote_store = Arc::new(GenericVoteStore::new(store)); + let lens = VoteAwareConsensusLens::new(Arc::clone(&vote_store)); + + let with_votes = create_assertion("WithVotes", 100.0, 1000); + let without_votes = create_assertion("NoVotes", 200.0, 2000); + + let hash_with = + VoteAwareConsensusLens::>::compute_assertion_hash( + &with_votes, + ); + + vote_store.put_vote(&create_vote(hash_with, [1u8; 32], 0.8, 3000)).await.expect("put"); + + let resolution = lens.resolve_async(&[with_votes.clone(), without_votes]).await; + + // Assertion with votes should win + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().unwrap().subject, "WithVotes"); + + // Confidence should be 1.0 (all weight is on winner) + assert!((resolution.resolution_confidence - 1.0).abs() < f32::EPSILON); + } + + #[tokio::test] + async fn test_lens_name() { + let store = SledStore::open_temp().expect("Failed to create store"); + let vote_store = Arc::new(GenericVoteStore::new(store)); + let lens = VoteAwareConsensusLens::new(vote_store); + + assert_eq!(lens.name(), "VoteAwareConsensus"); + } + + #[tokio::test] + async fn test_many_votes_on_single_assertion() { + let store = SledStore::open_temp().expect("Failed to create store"); + let vote_store = Arc::new(GenericVoteStore::new(store)); + let lens = VoteAwareConsensusLens::new(Arc::clone(&vote_store)); + + let popular = create_assertion("Popular", 100.0, 1000); + let unpopular = create_assertion("Unpopular", 200.0, 1100); + + let hash_popular = + VoteAwareConsensusLens::>::compute_assertion_hash(&popular); + let hash_unpopular = + VoteAwareConsensusLens::>::compute_assertion_hash( + &unpopular, + ); + + // Popular gets 10 votes + for i in 0..10 { + let agent_id = { + let mut id = [0u8; 32]; + id[0] = i; + id + }; + vote_store + .put_vote(&create_vote(hash_popular, agent_id, 0.5, 2000 + i as u64)) + .await + .expect("put"); + } + + // Unpopular gets 1 vote + vote_store + .put_vote(&create_vote(hash_unpopular, [99u8; 32], 0.5, 2100)) + .await + .expect("put"); + + let resolution = lens.resolve_async(&[popular.clone(), unpopular]).await; + + assert!(resolution.winner.is_some()); + assert_eq!(resolution.winner.as_ref().unwrap().subject, "Popular"); + + // Total weight = 10 * 0.5 + 1 * 0.5 = 5.5 + // Winner weight = 5.0 + // Confidence = 5.0 / 5.5 ≈ 0.909 + let expected_confidence = 5.0 / 5.5; + assert!((resolution.resolution_confidence - expected_confidence).abs() < 0.01); + } +} diff --git a/crates/stemedb-query/Cargo.toml b/crates/stemedb-query/Cargo.toml new file mode 100644 index 0000000..5320ca7 --- /dev/null +++ b/crates/stemedb-query/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "stemedb-query" +version = "0.1.0" +edition = "2021" +description = "Query engine with lifecycle filtering for Episteme" + +# Inherit workspace lints +[lints] +workspace = true + +[dependencies] +stemedb-core = { path = "../stemedb-core" } +stemedb-storage = { path = "../stemedb-storage" } +stemedb-lens = { path = "../stemedb-lens" } +async-trait = "0.1" +thiserror = "1.0" +tracing = "0.1" +tokio = { version = "1", features = ["macros", "rt", "time", "sync"] } +rkyv = { version = "0.7", features = ["validation"] } +hex = "0.4" +blake3 = "1.5" + +[dev-dependencies] +tempfile = "3.10" +stemedb-wal = { path = "../stemedb-wal" } +stemedb-ingest = { path = "../stemedb-ingest" } +ed25519-dalek = { version = "2.1", features = ["rand_core"] } +rand = "0.8" +hex = "0.4" diff --git a/crates/stemedb-query/src/engine.rs b/crates/stemedb-query/src/engine.rs new file mode 100644 index 0000000..90a4719 --- /dev/null +++ b/crates/stemedb-query/src/engine.rs @@ -0,0 +1,790 @@ +//! Query engine for executing queries against the KV store. +//! +//! The QueryEngine provides a simple interface for reading assertions +//! from the knowledge graph with filtering support. + +use std::sync::Arc; +use std::time::{SystemTime, UNIX_EPOCH}; + +use stemedb_core::types::{Assertion, MaterializedView}; +use stemedb_storage::{GenericIndexStore, IndexStore, KVStore}; +use tracing::{debug, instrument}; + +use crate::error::{QueryError, Result}; +use crate::query::{Query, QueryResult}; + +/// The query engine executes queries against the KV store. +/// +/// # Design Philosophy +/// +/// Following the "Deep Module" principle, QueryEngine presents a simple +/// interface (`execute`) that hides the complexity of index lookup, +/// deserialization, and filtering. +pub struct QueryEngine { + store: Arc, + index_store: GenericIndexStore>, +} + +impl QueryEngine { + /// Create a new query engine backed by the given store. + pub fn new(store: Arc) -> Self { + let index_store = GenericIndexStore::new(store.clone()); + Self { store, index_store } + } + + /// Execute a query and return matching assertions. + /// + /// # Query Execution Strategy + /// + /// 0. **Fast path**: If both `subject` and `predicate` are specified, check `MV:{subject}:{predicate}` for a pre-computed winner (O(1)) + /// 1. If both `subject` and `predicate` are specified: Use compound index `SP:{subject}:{predicate}` for O(1) lookup + /// 2. If only `subject` is specified: Use subject index `S:{subject}` for O(1) lookup + /// 3. Otherwise: Full scan of `H:` prefix (O(n), avoid in production) + /// + /// After fetching candidates, apply lifecycle and epoch filters. + #[instrument(skip(self, query), fields( + subject = ?query.subject, + predicate = ?query.predicate, + lifecycle = ?query.lifecycle + ))] + pub async fn execute(&self, query: &Query) -> Result { + // Fast path: check materialized view when both subject and predicate are specified + if let (Some(subject), Some(predicate)) = (&query.subject, &query.predicate) { + if let Some(result) = self.try_fast_path(subject, predicate, query).await? { + debug!(subject, predicate, "Fast path: used materialized view"); + return Ok(result); + } + } + + // Slow path: determine scan strategy based on query filters + let candidates = match (&query.subject, &query.predicate) { + // O(1) compound index lookup + (Some(subject), Some(predicate)) => { + debug!( + subject, + predicate, "Slow path: using compound index SP:{subject}:{predicate}" + ); + self.fetch_by_subject_predicate(subject, predicate).await? + } + // O(1) subject index lookup + (Some(subject), None) => { + debug!(subject, "Using subject index S:{subject}"); + self.fetch_by_subject(subject).await? + } + // O(n) full scan + _ => { + debug!("Using full scan (no subject filter)"); + self.fetch_all_assertions().await? + } + }; + + debug!(candidate_count = candidates.len(), "Fetched candidates"); + + // Apply filters + let mut matching: Vec = + candidates.into_iter().filter(|a| query.matches(a)).collect(); + + let total_count = matching.len(); + + // Apply limit if specified + let has_more = if let Some(limit) = query.limit { + if matching.len() > limit { + matching.truncate(limit); + true + } else { + false + } + } else { + false + }; + + debug!(matched_count = matching.len(), total_count, has_more, "Query complete"); + + Ok(QueryResult { assertions: matching, total_count, has_more }) + } + + /// Try the fast path: read a pre-computed MaterializedView for this subject+predicate. + /// + /// Returns `Some(QueryResult)` if a materialized view exists, is fresh enough, + /// and the winner passes the query's filters. Returns `None` to fall through + /// to the slow path. + /// + /// # Staleness Check + /// + /// If `query.max_stale` is set, the MV's age is checked against this threshold. + /// If the MV is older than `max_stale` seconds, we fall through to the slow path. + async fn try_fast_path( + &self, + subject: &str, + predicate: &str, + query: &Query, + ) -> Result> { + let mv_key = format!("MV:{}:{}", subject, predicate).into_bytes(); + + let data = match self.store.get(&mv_key).await? { + Some(data) => data, + None => return Ok(None), + }; + + let view: MaterializedView = match stemedb_core::serde::deserialize(&data) { + Ok(v) => v, + Err(e) => { + debug!( + subject, + predicate, + error = %e, + "Malformed materialized view, falling back to slow path" + ); + return Ok(None); + } + }; + + // Check staleness if max_stale is specified + if let Some(max_stale) = query.max_stale { + let now = + SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + let age = now.saturating_sub(view.materialized_at); + + if age > max_stale { + debug!( + subject, + predicate, + age_seconds = age, + max_stale_seconds = max_stale, + materialized_at = view.materialized_at, + "Materialized view is stale, falling back to slow path" + ); + return Ok(None); + } + } + + // Apply query filters to the winner + if !query.matches(&view.winner) { + // Winner doesn't match filters (e.g., wrong lifecycle stage). + // Fall through to slow path which considers all candidates. + return Ok(None); + } + + Ok(Some(QueryResult { assertions: vec![view.winner], total_count: 1, has_more: false })) + } + + /// Fetch assertions for a specific subject using the subject index. + async fn fetch_by_subject(&self, subject: &str) -> Result> { + let hash_list = self.index_store.get_by_subject(subject).await?; + + let mut results = Vec::with_capacity(hash_list.len()); + for hash in hash_list { + let assertion_key = format!("H:{}", hex::encode(hash)).into_bytes(); + if let Some(data) = self.store.get(&assertion_key).await? { + match self.deserialize_assertion(&data) { + Ok(assertion) => results.push(assertion), + Err(e) => { + debug!(hash = %hex::encode(hash), "Skipping malformed assertion: {:?}", e); + } + } + } + } + + Ok(results) + } + + /// Fetch assertions for a specific subject and predicate using the compound index. + async fn fetch_by_subject_predicate( + &self, + subject: &str, + predicate: &str, + ) -> Result> { + let hash_list = self.index_store.get_by_subject_predicate(subject, predicate).await?; + + let mut results = Vec::with_capacity(hash_list.len()); + for hash in hash_list { + let assertion_key = format!("H:{}", hex::encode(hash)).into_bytes(); + if let Some(data) = self.store.get(&assertion_key).await? { + match self.deserialize_assertion(&data) { + Ok(assertion) => results.push(assertion), + Err(e) => { + debug!(hash = %hex::encode(hash), "Skipping malformed assertion: {:?}", e); + } + } + } + } + + Ok(results) + } + + /// Fetch all assertions (full scan of H: prefix). + /// + /// This is O(n) and should be avoided for large databases. + /// Use subject/predicate indexes when possible. + async fn fetch_all_assertions(&self) -> Result> { + let entries = self.store.scan_prefix(b"H:").await?; + + let mut assertions = Vec::with_capacity(entries.len()); + for (_key, data) in entries { + match self.deserialize_assertion(&data) { + Ok(assertion) => assertions.push(assertion), + Err(e) => { + debug!("Skipping malformed assertion: {:?}", e); + // Skip malformed entries rather than failing the whole query + } + } + } + + Ok(assertions) + } + + /// Deserialize an assertion using the canonical serde module. + fn deserialize_assertion(&self, data: &[u8]) -> Result { + stemedb_core::serde::deserialize(data) + .map_err(|e| QueryError::Deserialization(e.to_string())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::query::Query; + use rkyv::ser::serializers::AllocSerializer; + use rkyv::ser::Serializer; + use stemedb_core::testing::AssertionBuilder; + use stemedb_core::types::{LifecycleStage, ObjectValue}; + use stemedb_storage::SledStore; + + fn create_test_assertion( + subject: &str, + predicate: &str, + lifecycle: LifecycleStage, + ) -> Assertion { + AssertionBuilder::new() + .subject(subject) + .predicate(predicate) + .confidence(0.95) + .lifecycle(lifecycle) + .build() + } + + async fn store_assertion(store: &SledStore, assertion: &Assertion) { + use stemedb_storage::{GenericIndexStore, IndexStore}; + + let mut serializer = AllocSerializer::<4096>::default(); + serializer.serialize_value(assertion).expect("serialize"); + let bytes = serializer.into_serializer().into_inner(); + + let hash = blake3::hash(&bytes); + let key = format!("H:{}", hash.to_hex()).into_bytes(); + store.put(&key, &bytes).await.expect("put"); + + // Update indexes using IndexStore + let index_store = GenericIndexStore::new(store.clone()); + let assertion_hash: [u8; 32] = *hash.as_bytes(); + index_store + .add_to_indexes(&assertion.subject, &assertion.predicate, &assertion_hash) + .await + .expect("add to indexes"); + } + + #[tokio::test] + async fn test_query_empty_store() { + let store = SledStore::open_temp().expect("store"); + let engine = QueryEngine::new(Arc::new(store)); + + let query = Query::builder().subject("Tesla").build(); + let result = engine.execute(&query).await.expect("execute"); + + assert!(result.assertions.is_empty()); + assert_eq!(result.total_count, 0); + } + + #[tokio::test] + async fn test_query_by_subject() { + let store = SledStore::open_temp().expect("store"); + + let tesla = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + let apple = create_test_assertion("Apple", "revenue", LifecycleStage::Approved); + + store_assertion(&store, &tesla).await; + store_assertion(&store, &apple).await; + + let engine = QueryEngine::new(Arc::new(store)); + + let query = Query::builder().subject("Tesla").build(); + let result = engine.execute(&query).await.expect("execute"); + + assert_eq!(result.assertions.len(), 1); + assert_eq!(result.assertions[0].subject, "Tesla"); + } + + #[tokio::test] + async fn test_query_by_lifecycle() { + let store = SledStore::open_temp().expect("store"); + + let approved = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + let proposed = create_test_assertion("Tesla", "profit", LifecycleStage::Proposed); + + store_assertion(&store, &approved).await; + store_assertion(&store, &proposed).await; + + let engine = QueryEngine::new(Arc::new(store)); + + // Query only approved + let query = Query::builder().subject("Tesla").lifecycle(LifecycleStage::Approved).build(); + let result = engine.execute(&query).await.expect("execute"); + + assert_eq!(result.assertions.len(), 1); + assert_eq!(result.assertions[0].lifecycle, LifecycleStage::Approved); + } + + #[tokio::test] + async fn test_query_with_limit() { + let store = SledStore::open_temp().expect("store"); + + // Store multiple assertions + for i in 0..5 { + let assertion = create_test_assertion( + &format!("Entity_{}", i), + "property", + LifecycleStage::Approved, + ); + store_assertion(&store, &assertion).await; + } + + let engine = QueryEngine::new(Arc::new(store)); + + let query = Query::builder().limit(2).build(); + let result = engine.execute(&query).await.expect("execute"); + + assert_eq!(result.assertions.len(), 2); + assert_eq!(result.total_count, 5); + assert!(result.has_more); + } + + #[tokio::test] + async fn test_query_all_filters() { + let store = SledStore::open_temp().expect("store"); + + let target = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + let wrong_subject = create_test_assertion("Apple", "revenue", LifecycleStage::Approved); + let wrong_predicate = create_test_assertion("Tesla", "profit", LifecycleStage::Approved); + let wrong_lifecycle = create_test_assertion("Tesla", "revenue", LifecycleStage::Proposed); + + store_assertion(&store, &target).await; + store_assertion(&store, &wrong_subject).await; + store_assertion(&store, &wrong_predicate).await; + store_assertion(&store, &wrong_lifecycle).await; + + let engine = QueryEngine::new(Arc::new(store)); + + let query = Query::builder() + .subject("Tesla") + .predicate("revenue") + .lifecycle(LifecycleStage::Approved) + .build(); + + let result = engine.execute(&query).await.expect("execute"); + + assert_eq!(result.assertions.len(), 1); + assert_eq!(result.assertions[0].subject, "Tesla"); + assert_eq!(result.assertions[0].predicate, "revenue"); + assert_eq!(result.assertions[0].lifecycle, LifecycleStage::Approved); + } + + // ======================================================================== + // COMPOUND INDEX TESTS + // ======================================================================== + + #[tokio::test] + async fn test_compound_index_lookup() { + let store = SledStore::open_temp().expect("store"); + + // Create multiple assertions with different subject/predicate combinations + let tesla_revenue = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + let tesla_profit = create_test_assertion("Tesla", "profit", LifecycleStage::Approved); + let apple_revenue = create_test_assertion("Apple", "revenue", LifecycleStage::Approved); + + store_assertion(&store, &tesla_revenue).await; + store_assertion(&store, &tesla_profit).await; + store_assertion(&store, &apple_revenue).await; + + let engine = QueryEngine::new(Arc::new(store)); + + // Query with both subject and predicate should use compound index + let query = Query::builder().subject("Tesla").predicate("revenue").build(); + + let result = engine.execute(&query).await.expect("execute"); + + assert_eq!(result.assertions.len(), 1); + assert_eq!(result.assertions[0].subject, "Tesla"); + assert_eq!(result.assertions[0].predicate, "revenue"); + } + + #[tokio::test] + async fn test_compound_index_multiple_assertions() { + let store = SledStore::open_temp().expect("store"); + + // Store multiple assertions with same subject+predicate but different values/timestamps + let mut assertion1 = create_test_assertion("Tesla", "revenue", LifecycleStage::Proposed); + assertion1.timestamp = 1000; + + let mut assertion2 = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + assertion2.timestamp = 2000; + + let mut assertion3 = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + assertion3.object = ObjectValue::Number(200.0); // Different value to ensure different hash + + store_assertion(&store, &assertion1).await; + store_assertion(&store, &assertion2).await; + store_assertion(&store, &assertion3).await; + + let engine = QueryEngine::new(Arc::new(store)); + + // Should find all three assertions + let query = Query::builder().subject("Tesla").predicate("revenue").build(); + + let result = engine.execute(&query).await.expect("execute"); + + assert_eq!(result.assertions.len(), 3); + for assertion in &result.assertions { + assert_eq!(assertion.subject, "Tesla"); + assert_eq!(assertion.predicate, "revenue"); + } + } + + #[tokio::test] + async fn test_subject_only_index_still_works() { + let store = SledStore::open_temp().expect("store"); + + let tesla_revenue = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + let tesla_profit = create_test_assertion("Tesla", "profit", LifecycleStage::Approved); + + store_assertion(&store, &tesla_revenue).await; + store_assertion(&store, &tesla_profit).await; + + let engine = QueryEngine::new(Arc::new(store)); + + // Query with only subject should use subject index + let query = Query::builder().subject("Tesla").build(); + + let result = engine.execute(&query).await.expect("execute"); + + assert_eq!(result.assertions.len(), 2); + for assertion in &result.assertions { + assert_eq!(assertion.subject, "Tesla"); + } + } + + #[tokio::test] + async fn test_compound_index_empty_result() { + let store = SledStore::open_temp().expect("store"); + + let tesla_revenue = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + + store_assertion(&store, &tesla_revenue).await; + + let engine = QueryEngine::new(Arc::new(store)); + + // Query for non-existent combination + let query = Query::builder().subject("Tesla").predicate("nonexistent").build(); + + let result = engine.execute(&query).await.expect("execute"); + + assert_eq!(result.assertions.len(), 0); + } + + // ======================================================================== + // FAST PATH (MATERIALIZED VIEW) TESTS + // ======================================================================== + + /// Helper to store a materialized view directly in the KV store. + async fn store_materialized_view( + store: &SledStore, + subject: &str, + predicate: &str, + winner: &Assertion, + ) { + store_materialized_view_with_time(store, subject, predicate, winner, 1000).await; + } + + /// Helper to store a materialized view with a custom materialized_at timestamp. + async fn store_materialized_view_with_time( + store: &SledStore, + subject: &str, + predicate: &str, + winner: &Assertion, + materialized_at: u64, + ) { + use stemedb_core::types::MaterializedView; + + let view = MaterializedView { + winner: winner.clone(), + lens_name: "VoteAwareConsensus".to_string(), + resolution_confidence: 0.95, + candidates_count: 3, + materialized_at, + }; + + let key = format!("MV:{}:{}", subject, predicate).into_bytes(); + let bytes = stemedb_core::serde::serialize(&view).expect("serialize MV"); + store.put(&key, &bytes).await.expect("put MV"); + } + + #[tokio::test] + async fn test_fast_path_returns_materialized_view() { + let store = SledStore::open_temp().expect("store"); + + let assertion = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + store_assertion(&store, &assertion).await; + store_materialized_view(&store, "Tesla", "revenue", &assertion).await; + + let engine = QueryEngine::new(Arc::new(store)); + + let query = Query::builder().subject("Tesla").predicate("revenue").build(); + let result = engine.execute(&query).await.expect("execute"); + + // Should get exactly the MV winner + assert_eq!(result.assertions.len(), 1); + assert_eq!(result.assertions[0].subject, "Tesla"); + assert_eq!(result.assertions[0].predicate, "revenue"); + } + + #[tokio::test] + async fn test_fast_path_falls_back_when_no_mv() { + let store = SledStore::open_temp().expect("store"); + + // Store assertion but NO materialized view + let assertion = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + store_assertion(&store, &assertion).await; + + let engine = QueryEngine::new(Arc::new(store)); + + let query = Query::builder().subject("Tesla").predicate("revenue").build(); + let result = engine.execute(&query).await.expect("execute"); + + // Should still find assertion via slow path (SP index) + assert_eq!(result.assertions.len(), 1); + assert_eq!(result.assertions[0].subject, "Tesla"); + } + + #[tokio::test] + async fn test_fast_path_respects_lifecycle_filter() { + let store = SledStore::open_temp().expect("store"); + + // MV winner is Approved + let approved = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + store_assertion(&store, &approved).await; + store_materialized_view(&store, "Tesla", "revenue", &approved).await; + + // Also store a Proposed assertion via SP index + let proposed = create_test_assertion("Tesla", "revenue", LifecycleStage::Proposed); + store_assertion(&store, &proposed).await; + + let engine = QueryEngine::new(Arc::new(store)); + + // Query for Proposed — MV winner is Approved, should fall through to slow path + let query = Query::builder() + .subject("Tesla") + .predicate("revenue") + .lifecycle(LifecycleStage::Proposed) + .build(); + + let result = engine.execute(&query).await.expect("execute"); + + assert_eq!(result.assertions.len(), 1); + assert_eq!(result.assertions[0].lifecycle, LifecycleStage::Proposed); + } + + #[tokio::test] + async fn test_fast_path_not_used_for_subject_only() { + let store = SledStore::open_temp().expect("store"); + + let assertion = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + store_assertion(&store, &assertion).await; + store_materialized_view(&store, "Tesla", "revenue", &assertion).await; + + let engine = QueryEngine::new(Arc::new(store)); + + // Subject-only query should use S: index, not MV: + let query = Query::builder().subject("Tesla").build(); + let result = engine.execute(&query).await.expect("execute"); + + assert_eq!(result.assertions.len(), 1); + } + + #[tokio::test] + async fn test_query_strategy_selection() { + let store = SledStore::open_temp().expect("store"); + + let tesla_revenue = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + let apple_profit = create_test_assertion("Apple", "profit", LifecycleStage::Approved); + + store_assertion(&store, &tesla_revenue).await; + store_assertion(&store, &apple_profit).await; + + let engine = QueryEngine::new(Arc::new(store)); + + // Test 1: Both subject and predicate -> compound index (O(1)) + let query1 = Query::builder().subject("Tesla").predicate("revenue").build(); + let result1 = engine.execute(&query1).await.expect("execute"); + assert_eq!(result1.assertions.len(), 1); + + // Test 2: Only subject -> subject index (O(1)) + let query2 = Query::builder().subject("Tesla").build(); + let result2 = engine.execute(&query2).await.expect("execute"); + assert_eq!(result2.assertions.len(), 1); + + // Test 3: Neither -> full scan (O(n)) + let query3 = Query::builder().lifecycle(LifecycleStage::Approved).build(); + let result3 = engine.execute(&query3).await.expect("execute"); + assert_eq!(result3.assertions.len(), 2); + } + + // ======================================================================== + // MV STALENESS TESTS + // ======================================================================== + + #[tokio::test] + async fn test_fast_path_stale_view_falls_back() { + use std::time::{SystemTime, UNIX_EPOCH}; + + let store = SledStore::open_temp().expect("store"); + + // Store an assertion and multiple MVs with different timestamps + let mv_winner = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + let slow_path_result = create_test_assertion("Tesla", "revenue", LifecycleStage::Proposed); + + store_assertion(&store, &mv_winner).await; + store_assertion(&store, &slow_path_result).await; + + // Create an old MV (1000 seconds ago) + let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + let old_timestamp = now.saturating_sub(1000); + store_materialized_view_with_time(&store, "Tesla", "revenue", &mv_winner, old_timestamp) + .await; + + let engine = QueryEngine::new(Arc::new(store)); + + // Query with max_stale = 60 seconds (MV is 1000 seconds old, so it's stale) + let query = Query::builder() + .subject("Tesla") + .predicate("revenue") + .max_stale(60) // Only accept MVs < 60 seconds old + .build(); + + let result = engine.execute(&query).await.expect("execute"); + + // Should fall back to slow path and get ALL matching assertions (both) + // This proves we didn't use the MV (which would return just the winner) + assert_eq!(result.assertions.len(), 2); + } + + #[tokio::test] + async fn test_fast_path_fresh_view_used() { + use std::time::{SystemTime, UNIX_EPOCH}; + + let store = SledStore::open_temp().expect("store"); + + let assertion = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + store_assertion(&store, &assertion).await; + + // Create a fresh MV (just now) + let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + store_materialized_view_with_time(&store, "Tesla", "revenue", &assertion, now).await; + + let engine = QueryEngine::new(Arc::new(store)); + + // Query with max_stale = 300 seconds (MV is ~0 seconds old, so it's fresh) + let query = Query::builder() + .subject("Tesla") + .predicate("revenue") + .max_stale(300) // Accept MVs up to 5 minutes old + .build(); + + let result = engine.execute(&query).await.expect("execute"); + + // Should use fast path (MV) and return exactly the winner + assert_eq!(result.assertions.len(), 1); + assert_eq!(result.assertions[0].subject, "Tesla"); + } + + #[tokio::test] + async fn test_fast_path_no_max_stale_always_uses_mv() { + let store = SledStore::open_temp().expect("store"); + + let mv_winner = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + let other = create_test_assertion("Tesla", "revenue", LifecycleStage::Proposed); + + store_assertion(&store, &mv_winner).await; + store_assertion(&store, &other).await; + + // Store an ANCIENT MV (timestamp = 1, i.e., 1970) + store_materialized_view_with_time(&store, "Tesla", "revenue", &mv_winner, 1).await; + + let engine = QueryEngine::new(Arc::new(store)); + + // Query WITHOUT max_stale (default behavior: accept any age) + let query = Query::builder().subject("Tesla").predicate("revenue").build(); + + let result = engine.execute(&query).await.expect("execute"); + + // Should use fast path and return exactly the MV winner (not both assertions) + // This proves backward compatibility: no max_stale = accept any MV age + assert_eq!(result.assertions.len(), 1); + assert_eq!(result.assertions[0].lifecycle, LifecycleStage::Approved); + } + + #[tokio::test] + async fn test_fast_path_max_stale_zero_rejects_old_mv() { + let store = SledStore::open_temp().expect("store"); + + let mv_winner = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + let other = create_test_assertion("Tesla", "revenue", LifecycleStage::Proposed); + + store_assertion(&store, &mv_winner).await; + store_assertion(&store, &other).await; + + // Store an MV that is 1 second old (not brand new) + use std::time::{SystemTime, UNIX_EPOCH}; + let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + let one_second_ago = now.saturating_sub(1); + store_materialized_view_with_time(&store, "Tesla", "revenue", &mv_winner, one_second_ago) + .await; + + let engine = QueryEngine::new(Arc::new(store)); + + // Query with max_stale = 0: only accept MVs that are 0 seconds old (brand new) + // Since our MV is 1 second old, it should be rejected + let query = Query::builder().subject("Tesla").predicate("revenue").max_stale(0).build(); + + let result = engine.execute(&query).await.expect("execute"); + + // MV is 1 second old, which is > 0, so should fall back to slow path + assert_eq!(result.assertions.len(), 2); + } + + #[tokio::test] + async fn test_fast_path_max_stale_zero_accepts_brand_new_mv() { + let store = SledStore::open_temp().expect("store"); + + let mv_winner = create_test_assertion("Tesla", "revenue", LifecycleStage::Approved); + let other = create_test_assertion("Tesla", "revenue", LifecycleStage::Proposed); + + store_assertion(&store, &mv_winner).await; + store_assertion(&store, &other).await; + + // Store an MV with exact current timestamp (brand new) + use std::time::{SystemTime, UNIX_EPOCH}; + let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + store_materialized_view_with_time(&store, "Tesla", "revenue", &mv_winner, now).await; + + let engine = QueryEngine::new(Arc::new(store)); + + // Query with max_stale = 0: only accept MVs that are 0 seconds old (brand new) + // Since our MV is brand new (age = 0), it should be accepted + let query = Query::builder().subject("Tesla").predicate("revenue").max_stale(0).build(); + + let result = engine.execute(&query).await.expect("execute"); + + // MV age is 0, which is not > 0, so fast path should be used + assert_eq!(result.assertions.len(), 1); + assert_eq!(result.assertions[0].lifecycle, LifecycleStage::Approved); + } +} diff --git a/crates/stemedb-query/src/error.rs b/crates/stemedb-query/src/error.rs new file mode 100644 index 0000000..0645d2c --- /dev/null +++ b/crates/stemedb-query/src/error.rs @@ -0,0 +1,23 @@ +//! Error types for query operations. + +use stemedb_storage::StorageError; +use thiserror::Error; + +/// Result type for query operations. +pub type Result = std::result::Result; + +/// Errors that can occur during query execution. +#[derive(Error, Debug)] +pub enum QueryError { + /// Error from the storage layer. + #[error("Storage error: {0}")] + Storage(#[from] StorageError), + + /// Error deserializing stored data. + #[error("Deserialization error: {0}")] + Deserialization(String), + + /// Query validation error. + #[error("Invalid query: {0}")] + InvalidQuery(String), +} diff --git a/crates/stemedb-query/src/lib.rs b/crates/stemedb-query/src/lib.rs new file mode 100644 index 0000000..8d4647a --- /dev/null +++ b/crates/stemedb-query/src/lib.rs @@ -0,0 +1,56 @@ +//! Query engine for Episteme with lifecycle filtering. +//! +//! This crate provides the query interface for reading assertions from the +//! knowledge graph. Queries can filter by subject, predicate, lifecycle stage, +//! and epoch. +//! +//! # Two Query Modes +//! +//! | Mode | Returns | Use Case | +//! |------|---------|----------| +//! | `QueryEngine` | Winner assertion | "Give me the answer" | +//! | `SkepticResolver` | Conflict analysis | "Show me the disagreement" | +//! +//! # Example: Standard Query +//! +//! ```ignore +//! use stemedb_query::{Query, QueryEngine}; +//! use stemedb_core::types::LifecycleStage; +//! +//! let engine = QueryEngine::new(store); +//! +//! // Query only approved assertions +//! let query = Query::builder() +//! .subject("Tesla_Inc") +//! .predicate("has_revenue") +//! .lifecycle(LifecycleStage::Approved) +//! .build(); +//! +//! let result = engine.execute(&query).await?; +//! ``` +//! +//! # Example: Skeptic Query (Trust but Verify) +//! +//! ```ignore +//! use stemedb_query::SkepticResolver; +//! +//! let resolver = SkepticResolver::new(store, vote_store, trust_store); +//! let view = resolver.resolve("Semaglutide", "muscle_effect").await?; +//! +//! if view.analysis.status == ResolutionStatus::Contested { +//! println!("⚠️ This fact is disputed!"); +//! } +//! ``` + +mod engine; +mod error; +/// Background materializer for O(1) read performance. +pub mod materializer; +mod query; +mod skeptic; + +pub use engine::QueryEngine; +pub use error::{QueryError, Result}; +pub use materializer::{MaterializeReport, Materializer}; +pub use query::{hamming_distance, Query, QueryBuilder, QueryResult}; +pub use skeptic::{SkepticResolver, SkepticView}; diff --git a/crates/stemedb-query/src/materializer.rs b/crates/stemedb-query/src/materializer.rs new file mode 100644 index 0000000..9858585 --- /dev/null +++ b/crates/stemedb-query/src/materializer.rs @@ -0,0 +1,645 @@ +//! Background Materializer for O(1) read performance. +//! +//! The Materializer scans all subject+predicate combinations, resolves each +//! through a lens (default: VoteAwareConsensus), and writes the winning assertion +//! to `MV:{subject}:{predicate}` in the KV store. +//! +//! # Architecture +//! +//! From the architecture spec (Section 3, Step 4): +//! > "A background worker aggregates Votes + TrustRank to update the +//! > `MV:{Subject}:{Predicate}` key. This ensures that Read queries are O(1) +//! > lookups on the Materialized View, not O(N) calculations." +//! +//! # Design Philosophy +//! +//! Following the "Deep Module" principle: +//! - Simple interface: `step()` performs one full materialization pass +//! - Complex implementation: Discovers SP: keys, fetches candidates, +//! runs async lenses, writes MV: keys, tracks statistics +//! - `run()` wraps `step()` in a background loop with error resilience +//! +//! # Storage Layout +//! +//! | Key Pattern | Value | Purpose | +//! |-------------|-------|---------| +//! | `MV:{subject}:{predicate}` | Serialized `MaterializedView` | Pre-computed winner | + +use crate::error::{QueryError, Result}; +use std::sync::Arc; +use stemedb_core::types::{Assertion, MaterializedView}; +use stemedb_lens::AsyncLens; +use stemedb_storage::{GenericIndexStore, KVStore}; +use tokio::sync::Notify; +use tracing::{debug, error, info, instrument, warn}; + +/// Key prefix for materialized views. +const MV_PREFIX: &str = "MV:"; + +/// Key prefix for compound indexes (used to discover subject+predicate pairs). +const SP_PREFIX: &[u8] = b"SP:"; + +/// Report from a single materialization pass. +#[derive(Debug, Default)] +pub struct MaterializeReport { + /// Number of subject+predicate pairs scanned. + pub pairs_scanned: usize, + /// Number of views that were updated (winner changed or new). + pub views_updated: usize, + /// Number of pairs skipped due to errors. + pub errors: usize, + /// Number of pairs with no candidates (empty after filter). + pub empty_pairs: usize, +} + +/// Background worker that maintains materialized views for O(1) reads. +/// +/// The Materializer takes an `AsyncLens` implementation and uses it to +/// resolve all known subject+predicate pairs into winning assertions, +/// storing the results at `MV:{subject}:{predicate}`. +/// +/// # Example +/// +/// ```ignore +/// use stemedb_query::Materializer; +/// use stemedb_storage::{SledStore, GenericVoteStore}; +/// use stemedb_lens::VoteAwareConsensusLens; +/// use std::sync::Arc; +/// +/// let store = Arc::new(SledStore::open("./data")?); +/// let vote_store = Arc::new(GenericVoteStore::new(store.clone())); +/// let lens = VoteAwareConsensusLens::new(vote_store); +/// +/// let materializer = Materializer::new(store, Box::new(lens)); +/// let report = materializer.step().await?; +/// println!("Updated {} views", report.views_updated); +/// ``` +pub struct Materializer { + store: Arc, + index_store: GenericIndexStore>, + lens: Box, +} + +impl Materializer { + /// Create a new Materializer with the given store and lens. + /// + /// The lens determines the resolution strategy for materialized views. + /// Use `VoteAwareConsensusLens` for the standard Ballot Box consensus, + /// or `TrustAwareAuthorityLens` for reputation-weighted resolution. + pub fn new(store: Arc, lens: Box) -> Self { + let index_store = GenericIndexStore::new(store.clone()); + Self { store, index_store, lens } + } + + /// Perform one full materialization pass. + /// + /// Scans all `SP:` keys to discover subject+predicate pairs, fetches + /// candidate assertions for each pair, runs the lens, and writes the + /// winning assertion to `MV:{subject}:{predicate}`. + /// + /// Returns a report with statistics about the pass. + #[instrument(skip(self), fields(lens = %self.lens.name()))] + pub async fn step(&self) -> Result { + let mut report = MaterializeReport::default(); + + // Discover all subject+predicate pairs from SP: index + let sp_entries = self.store.scan_prefix(SP_PREFIX).await?; + + for (key, _value) in &sp_entries { + report.pairs_scanned += 1; + + // Parse the SP:{subject}:{predicate} key + let (subject, predicate) = match Self::parse_sp_key(key) { + Some(pair) => pair, + None => { + warn!(key = %String::from_utf8_lossy(key), "Skipping malformed SP: key"); + report.errors += 1; + continue; + } + }; + + // Materialize this subject+predicate pair + match self.materialize_pair(&subject, &predicate).await { + Ok(Some(_)) => { + report.views_updated += 1; + } + Ok(None) => { + report.empty_pairs += 1; + } + Err(e) => { + debug!( + subject = %subject, + predicate = %predicate, + error = %e, + "Failed to materialize pair, skipping" + ); + report.errors += 1; + } + } + } + + info!( + pairs_scanned = report.pairs_scanned, + views_updated = report.views_updated, + empty_pairs = report.empty_pairs, + errors = report.errors, + "Materialization pass complete" + ); + + Ok(report) + } + + /// Materialize a single subject+predicate pair. + /// + /// Fetches all candidate assertions, runs the lens, and writes the + /// result to `MV:{subject}:{predicate}` if a winner is found. + /// + /// Returns the `MaterializedView` if a winner was found, `None` if + /// there were no candidates. + #[instrument(skip(self), fields(subject = %subject, predicate = %predicate, lens = %self.lens.name()))] + pub async fn materialize_pair( + &self, + subject: &str, + predicate: &str, + ) -> Result> { + // Fetch candidate assertions via compound index + let candidates = self.fetch_candidates(subject, predicate).await?; + + if candidates.is_empty() { + debug!(subject, predicate, "No candidates found"); + return Ok(None); + } + + debug!( + subject, + predicate, + candidates_count = candidates.len(), + "Resolving candidates through lens" + ); + + // Run the lens + let resolution = self.lens.resolve_async(&candidates).await; + + let winner = match resolution.winner { + Some(winner) => winner, + None => { + debug!(subject, predicate, "Lens returned no winner"); + return Ok(None); + } + }; + + // Build the materialized view + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + + let view = MaterializedView { + winner, + lens_name: self.lens.name().to_string(), + resolution_confidence: resolution.resolution_confidence, + candidates_count: resolution.candidates_count, + materialized_at: now, + }; + + // Write to MV:{subject}:{predicate} + let mv_key = Self::mv_key(subject, predicate); + let serialized = stemedb_core::serde::serialize(&view) + .map_err(|e| QueryError::Deserialization(e.to_string()))?; + self.store.put(&mv_key, &serialized).await?; + + debug!( + subject, + predicate, + confidence = view.resolution_confidence, + candidates = view.candidates_count, + "Materialized view updated" + ); + + Ok(Some(view)) + } + + /// Read a materialized view from the store. + /// + /// Returns `None` if no materialized view exists for this subject+predicate. + /// This is the O(1) fast-path read. + #[instrument(skip(self), fields(subject = %subject, predicate = %predicate))] + pub async fn get_materialized_view( + &self, + subject: &str, + predicate: &str, + ) -> Result> { + let key = Self::mv_key(subject, predicate); + match self.store.get(&key).await? { + Some(data) => { + let view: MaterializedView = stemedb_core::serde::deserialize(&data) + .map_err(|e| QueryError::Deserialization(e.to_string()))?; + Ok(Some(view)) + } + None => Ok(None), + } + } + + /// Run the materializer continuously in the background (polling mode). + /// + /// Performs periodic materialization passes with a configurable interval. + /// Errors during a pass are logged but do not stop the loop. + /// + /// For event-driven mode, use [`run_notified`] instead. + pub async fn run(&self, interval: std::time::Duration) { + info!( + interval_ms = interval.as_millis() as u64, + lens = %self.lens.name(), + "Starting materializer loop (polling mode)" + ); + + loop { + self.run_step().await; + tokio::time::sleep(interval).await; + } + } + + /// Run the materializer in event-driven mode. + /// + /// Waits for a notification from the ingestion pipeline (via `Notify`) + /// before performing a materialization pass. Uses a timeout as a safety + /// net to catch missed notifications and ensure eventual consistency. + /// + /// # Arguments + /// + /// * `notify` - Shared notification channel, signaled by the IngestWorker + /// * `max_interval` - Maximum time to wait between passes (fallback timeout) + pub async fn run_notified(&self, notify: Arc, max_interval: std::time::Duration) { + info!( + max_interval_ms = max_interval.as_millis() as u64, + lens = %self.lens.name(), + "Starting materializer loop (event-driven mode)" + ); + + loop { + // Wait for notification or timeout — whichever comes first + let was_notified = tokio::time::timeout(max_interval, notify.notified()).await.is_ok(); + + if was_notified { + debug!("Materialization triggered by ingestion notification"); + } else { + debug!("Materialization triggered by timeout fallback"); + } + + self.run_step().await; + } + } + + /// Execute a single materialization pass, logging results. + async fn run_step(&self) { + match self.step().await { + Ok(report) => { + if report.views_updated > 0 { + info!( + updated = report.views_updated, + scanned = report.pairs_scanned, + "Materialization pass updated views" + ); + } + } + Err(e) => { + error!(error = %e, "Materialization pass failed"); + } + } + } + + /// Fetch candidate assertions for a subject+predicate pair. + async fn fetch_candidates(&self, subject: &str, predicate: &str) -> Result> { + use stemedb_storage::IndexStore; + + let hash_list = self.index_store.get_by_subject_predicate(subject, predicate).await?; + + let mut candidates = Vec::with_capacity(hash_list.len()); + for hash in hash_list { + let key = format!("H:{}", hex::encode(hash)).into_bytes(); + if let Some(data) = self.store.get(&key).await? { + match stemedb_core::serde::deserialize::(&data) { + Ok(assertion) => candidates.push(assertion), + Err(e) => { + debug!( + hash = %hex::encode(hash), + error = %e, + "Skipping malformed assertion" + ); + } + } + } + } + + Ok(candidates) + } + + /// Parse a `SP:{subject}:{predicate}` key into its components. + /// + /// Returns `None` if the key is malformed. + fn parse_sp_key(key: &[u8]) -> Option<(String, String)> { + let key_str = std::str::from_utf8(key).ok()?; + let without_prefix = key_str.strip_prefix("SP:")?; + + // Find the first colon separator after the prefix + let colon_pos = without_prefix.find(':')?; + if colon_pos == 0 || colon_pos == without_prefix.len() - 1 { + return None; + } + + let subject = &without_prefix[..colon_pos]; + let predicate = &without_prefix[colon_pos + 1..]; + + Some((subject.to_string(), predicate.to_string())) + } + + /// Construct the MV key for a subject+predicate pair. + fn mv_key(subject: &str, predicate: &str) -> Vec { + format!("{}{}:{}", MV_PREFIX, subject, predicate).into_bytes() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use stemedb_core::testing::{self, AssertionBuilder}; + use stemedb_core::types::{ObjectValue, Vote}; + use stemedb_lens::VoteAwareConsensusLens; + use stemedb_storage::{GenericVoteStore, SledStore, VoteStore}; + use tokio::sync::Notify; + + fn create_assertion(subject: &str, predicate: &str, value: f64, timestamp: u64) -> Assertion { + AssertionBuilder::new() + .subject(subject) + .predicate(predicate) + .object_number(value) + .timestamp(timestamp) + .build() + } + + /// Store an assertion at H:{hash} and update indexes. + async fn store_assertion(store: &Arc, assertion: &Assertion) -> [u8; 32] { + use stemedb_storage::IndexStore; + + let bytes = stemedb_core::serde::serialize(assertion).expect("serialize"); + let hash = blake3::hash(&bytes); + let key = format!("H:{}", hash.to_hex()).into_bytes(); + store.put(&key, &bytes).await.expect("put"); + + let index_store = GenericIndexStore::new(store.clone()); + let assertion_hash: [u8; 32] = *hash.as_bytes(); + index_store + .add_to_indexes(&assertion.subject, &assertion.predicate, &assertion_hash) + .await + .expect("index"); + + assertion_hash + } + + fn create_vote( + assertion_hash: [u8; 32], + agent_id: [u8; 32], + weight: f32, + timestamp: u64, + ) -> Vote { + testing::test_vote(assertion_hash, agent_id, weight, timestamp) + } + + #[tokio::test] + async fn test_empty_store() { + let store = Arc::new(SledStore::open_temp().expect("store")); + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let lens = VoteAwareConsensusLens::new(vote_store); + let materializer = Materializer::new(store, Box::new(lens)); + + let report = materializer.step().await.expect("step"); + + assert_eq!(report.pairs_scanned, 0); + assert_eq!(report.views_updated, 0); + assert_eq!(report.errors, 0); + } + + #[tokio::test] + async fn test_single_assertion_materialized() { + let store = Arc::new(SledStore::open_temp().expect("store")); + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let lens = VoteAwareConsensusLens::new(vote_store); + let materializer = Materializer::new(store.clone(), Box::new(lens)); + + // Store one assertion + let assertion = create_assertion("Tesla", "revenue", 96.7, 1000); + store_assertion(&store, &assertion).await; + + // Materialize + let report = materializer.step().await.expect("step"); + + assert_eq!(report.pairs_scanned, 1); + assert_eq!(report.views_updated, 1); + + // Read back the materialized view + let view = materializer + .get_materialized_view("Tesla", "revenue") + .await + .expect("get_mv") + .expect("should exist"); + + assert_eq!(view.winner.subject, "Tesla"); + assert_eq!(view.winner.predicate, "revenue"); + assert_eq!(view.candidates_count, 1); + assert!((view.resolution_confidence - 1.0).abs() < f32::EPSILON); + assert_eq!(view.lens_name, "VoteAwareConsensus"); + } + + #[tokio::test] + async fn test_vote_weighted_winner() { + let store = Arc::new(SledStore::open_temp().expect("store")); + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let lens = VoteAwareConsensusLens::new(Arc::clone(&vote_store)); + let materializer = Materializer::new(store.clone(), Box::new(lens)); + + // Store two competing assertions + let a1 = create_assertion("Tesla", "revenue", 96.7, 1000); + let a2 = create_assertion("Tesla", "revenue", 100.0, 1100); + let hash1 = store_assertion(&store, &a1).await; + let hash2 = store_assertion(&store, &a2).await; + + // Give a2 more votes + vote_store.put_vote(&create_vote(hash1, [10u8; 32], 0.3, 2000)).await.expect("put"); + vote_store.put_vote(&create_vote(hash2, [20u8; 32], 0.8, 2001)).await.expect("put"); + vote_store.put_vote(&create_vote(hash2, [30u8; 32], 0.7, 2002)).await.expect("put"); + + // Materialize + let report = materializer.step().await.expect("step"); + assert_eq!(report.views_updated, 1); + + // Winner should be a2 (higher aggregate weight) + let view = materializer + .get_materialized_view("Tesla", "revenue") + .await + .expect("get_mv") + .expect("should exist"); + + assert_eq!(view.winner.object, ObjectValue::Number(100.0)); + assert_eq!(view.candidates_count, 2); + } + + #[tokio::test] + async fn test_multiple_pairs_materialized() { + let store = Arc::new(SledStore::open_temp().expect("store")); + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let lens = VoteAwareConsensusLens::new(vote_store); + let materializer = Materializer::new(store.clone(), Box::new(lens)); + + // Store assertions for different subject+predicate pairs + store_assertion(&store, &create_assertion("Tesla", "revenue", 96.7, 1000)).await; + store_assertion(&store, &create_assertion("Tesla", "profit", 12.0, 1001)).await; + store_assertion(&store, &create_assertion("Apple", "revenue", 380.0, 1002)).await; + + let report = materializer.step().await.expect("step"); + + assert_eq!(report.pairs_scanned, 3); + assert_eq!(report.views_updated, 3); + + // Verify all three MVs exist + assert!(materializer + .get_materialized_view("Tesla", "revenue") + .await + .expect("get") + .is_some()); + assert!(materializer + .get_materialized_view("Tesla", "profit") + .await + .expect("get") + .is_some()); + assert!(materializer + .get_materialized_view("Apple", "revenue") + .await + .expect("get") + .is_some()); + + // And non-existent pair returns None + assert!(materializer + .get_materialized_view("Apple", "profit") + .await + .expect("get") + .is_none()); + } + + #[tokio::test] + async fn test_idempotent_materialization() { + let store = Arc::new(SledStore::open_temp().expect("store")); + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let lens = VoteAwareConsensusLens::new(vote_store); + let materializer = Materializer::new(store.clone(), Box::new(lens)); + + store_assertion(&store, &create_assertion("Tesla", "revenue", 96.7, 1000)).await; + + // Run two passes + let report1 = materializer.step().await.expect("step1"); + let report2 = materializer.step().await.expect("step2"); + + // Both should succeed and update (we always overwrite for freshness) + assert_eq!(report1.views_updated, 1); + assert_eq!(report2.views_updated, 1); + } + + #[tokio::test] + async fn test_no_mv_for_nonexistent_pair() { + let store = Arc::new(SledStore::open_temp().expect("store")); + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let lens = VoteAwareConsensusLens::new(vote_store); + let materializer = Materializer::new(store, Box::new(lens)); + + let result = materializer.get_materialized_view("Nonexistent", "field").await.expect("get"); + assert!(result.is_none()); + } + + #[tokio::test] + async fn test_parse_sp_key() { + // Valid key + let key = b"SP:Tesla:revenue"; + let result = Materializer::::parse_sp_key(key); + assert_eq!(result, Some(("Tesla".to_string(), "revenue".to_string()))); + + // Missing predicate + let key = b"SP:Tesla"; + assert!(Materializer::::parse_sp_key(key).is_none()); + + // Empty subject + let key = b"SP::revenue"; + assert!(Materializer::::parse_sp_key(key).is_none()); + + // Wrong prefix + let key = b"S:Tesla"; + assert!(Materializer::::parse_sp_key(key).is_none()); + } + + #[tokio::test] + async fn test_materialize_pair_directly() { + let store = Arc::new(SledStore::open_temp().expect("store")); + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let lens = VoteAwareConsensusLens::new(vote_store); + let materializer = Materializer::new(store.clone(), Box::new(lens)); + + let assertion = create_assertion("Tesla", "revenue", 96.7, 1000); + store_assertion(&store, &assertion).await; + + // Materialize a specific pair + let view = materializer + .materialize_pair("Tesla", "revenue") + .await + .expect("materialize") + .expect("should have winner"); + + assert_eq!(view.winner.subject, "Tesla"); + assert!(view.materialized_at > 0); + + // Empty pair returns None + let no_view = + materializer.materialize_pair("Nonexistent", "field").await.expect("materialize"); + assert!(no_view.is_none()); + } + + #[tokio::test] + async fn test_mv_key_construction() { + let key = Materializer::::mv_key("Tesla", "revenue"); + assert_eq!(key, b"MV:Tesla:revenue"); + } + + #[tokio::test] + async fn test_run_notified_triggers_on_notify() { + let store = Arc::new(SledStore::open_temp().expect("store")); + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let lens = VoteAwareConsensusLens::new(vote_store); + let materializer = Arc::new(Materializer::new(store.clone(), Box::new(lens))); + + // Store an assertion so materialization has work to do + let assertion = create_assertion("Tesla", "revenue", 96.7, 1000); + store_assertion(&store, &assertion).await; + + let notify = Arc::new(Notify::new()); + let notify_clone = Arc::clone(¬ify); + let materializer_clone = Arc::clone(&materializer); + + // Spawn the event-driven loop + let handle = tokio::spawn(async move { + // Use a very long max_interval so it only triggers via notification + materializer_clone.run_notified(notify_clone, std::time::Duration::from_secs(60)).await; + }); + + // Give the loop time to start waiting + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + + // Signal the notification + notify.notify_one(); + + // Wait for the materializer to process + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + + // Verify the MV was created + let view = materializer.get_materialized_view("Tesla", "revenue").await.expect("get_mv"); + assert!(view.is_some(), "Materialized view should exist after notification"); + + handle.abort(); + } +} diff --git a/crates/stemedb-query/src/query.rs b/crates/stemedb-query/src/query.rs new file mode 100644 index 0000000..f26a588 --- /dev/null +++ b/crates/stemedb-query/src/query.rs @@ -0,0 +1,583 @@ +//! Query types and builder for filtering assertions. +//! +//! The Query struct represents a read request against the knowledge graph. +//! Queries can filter by any combination of subject, predicate, lifecycle, +//! and epoch. + +use stemedb_core::types::{Assertion, EpochId, LifecycleStage, PHash}; + +/// Compute hamming distance between two 8-byte perceptual hashes. +/// +/// Returns the number of differing bits (0-64). Lower distance means +/// more visually similar images. +/// +/// # Example +/// +/// ```rust +/// use stemedb_query::hamming_distance; +/// +/// let a = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; +/// let b = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]; +/// assert_eq!(hamming_distance(&a, &b), 64); // All bits differ +/// +/// let c = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01]; +/// assert_eq!(hamming_distance(&a, &c), 1); // One bit differs +/// ``` +pub fn hamming_distance(a: &PHash, b: &PHash) -> u32 { + a.iter().zip(b.iter()).map(|(x, y)| (x ^ y).count_ones()).sum() +} + +/// Parse hex string to 8-byte pHash. +/// +/// Returns `None` if the hex string is not exactly 16 characters +/// or contains invalid hex digits. Case-insensitive: both "A3F2..." +/// and "a3f2..." are valid and produce identical results. +fn parse_hex_phash(hex_str: &str) -> Option { + if hex_str.len() != 16 { + return None; + } + let bytes = hex::decode(hex_str).ok()?; + if bytes.len() != 8 { + return None; + } + let mut hash = [0u8; 8]; + hash.copy_from_slice(&bytes); + Some(hash) +} + +/// A query against the knowledge graph. +/// +/// All fields are optional filters. If a field is `None`, it matches any value. +/// Multiple filters combine with AND semantics. +#[derive(Debug, Clone, Default)] +pub struct Query { + /// Filter by subject entity. + pub subject: Option, + + /// Filter by predicate/relation. + pub predicate: Option, + + /// Filter by lifecycle stage. + pub lifecycle: Option, + + /// Filter by epoch (paradigm context). + pub epoch: Option, + + /// Maximum number of results to return. + pub limit: Option, + + /// Maximum acceptable staleness of materialized views in seconds. + /// + /// When set, the fast path (MV lookup) will be skipped if the materialized + /// view is older than this threshold. This causes the query to fall through + /// to the slow path, which re-computes the result from all candidate assertions. + /// + /// - `None` (default): Accept any MV age (backward-compatible behavior) + /// - `Some(0)`: Never use MV, always use slow path + /// - `Some(60)`: Only use MV if materialized within the last 60 seconds + pub max_stale: Option, + + /// Filter by visual similarity to a reference pHash (hex-encoded, 16 chars). + /// + /// Returns assertions whose `visual_hash` has hamming distance <= `visual_threshold`. + /// Assertions without a `visual_hash` are excluded from results when this is set. + pub visual_near: Option, + + /// Maximum hamming distance for `visual_near` matching. + /// + /// Range: 0-64 (8 bytes = 64 bits). Default: 8 (12.5% bit difference). + /// Lower values require closer visual similarity. + pub visual_threshold: Option, +} + +impl Query { + /// Create a new empty query (matches all assertions). + pub fn new() -> Self { + Self::default() + } + + /// Create a query builder for ergonomic query construction. + pub fn builder() -> QueryBuilder { + QueryBuilder::new() + } + + /// Check if an assertion matches this query's filters. + pub fn matches(&self, assertion: &Assertion) -> bool { + // Check subject filter + if let Some(ref subject) = self.subject { + if &assertion.subject != subject { + return false; + } + } + + // Check predicate filter + if let Some(ref predicate) = self.predicate { + if &assertion.predicate != predicate { + return false; + } + } + + // Check lifecycle filter + if let Some(lifecycle) = self.lifecycle { + if assertion.lifecycle != lifecycle { + return false; + } + } + + // Check epoch filter + if let Some(epoch) = self.epoch { + match assertion.epoch { + Some(assertion_epoch) if assertion_epoch == epoch => {} + _ => return false, + } + } + + // Check visual similarity filter + if let Some(ref target_hex) = self.visual_near { + let target = match parse_hex_phash(target_hex) { + Some(h) => h, + None => return false, // Invalid hex = no match + }; + match assertion.visual_hash { + Some(ref assertion_hash) => { + let threshold = self.visual_threshold.unwrap_or(8); + if hamming_distance(&target, assertion_hash) > threshold { + return false; + } + } + None => return false, // No visual_hash = no match when visual_near is specified + } + } + + true + } +} + +/// Builder for constructing queries with a fluent API. +#[derive(Debug, Clone, Default)] +pub struct QueryBuilder { + query: Query, +} + +impl QueryBuilder { + /// Create a new query builder. + pub fn new() -> Self { + Self::default() + } + + /// Filter by subject. + pub fn subject(mut self, subject: impl Into) -> Self { + self.query.subject = Some(subject.into()); + self + } + + /// Filter by predicate. + pub fn predicate(mut self, predicate: impl Into) -> Self { + self.query.predicate = Some(predicate.into()); + self + } + + /// Filter by lifecycle stage. + pub fn lifecycle(mut self, lifecycle: LifecycleStage) -> Self { + self.query.lifecycle = Some(lifecycle); + self + } + + /// Filter by epoch. + pub fn epoch(mut self, epoch: EpochId) -> Self { + self.query.epoch = Some(epoch); + self + } + + /// Set maximum number of results. + pub fn limit(mut self, limit: usize) -> Self { + self.query.limit = Some(limit); + self + } + + /// Set maximum acceptable staleness for materialized views. + /// + /// When set, the fast path (MV lookup) will be skipped if the materialized + /// view was created more than `seconds` ago. This causes the query to + /// fall through to the slow path, which re-computes the result from all + /// candidate assertions. + /// + /// # Example + /// ```rust + /// use stemedb_query::Query; + /// + /// // Only accept MVs materialized within the last 5 minutes + /// let query = Query::builder() + /// .subject("Tesla") + /// .predicate("revenue") + /// .max_stale(300) + /// .build(); + /// ``` + pub fn max_stale(mut self, seconds: u64) -> Self { + self.query.max_stale = Some(seconds); + self + } + + /// Filter by visual similarity to a reference perceptual hash. + /// + /// Returns only assertions whose `visual_hash` has a hamming distance + /// less than or equal to `threshold` from the target hash. Assertions + /// without a `visual_hash` are excluded. + /// + /// # Arguments + /// + /// * `hash` - Hex-encoded 8-byte pHash (16 hex characters) + /// * `threshold` - Maximum hamming distance (0-64, default: 8) + /// + /// # Example + /// + /// ```rust + /// use stemedb_query::Query; + /// + /// // Find visually similar screenshots (within 5 bits of difference) + /// let query = Query::builder() + /// .subject("Tesla_10K_2024") + /// .visual_near("a3f2b1c4d5e6f708", 5) + /// .build(); + /// ``` + pub fn visual_near(mut self, hash: impl Into, threshold: u32) -> Self { + self.query.visual_near = Some(hash.into()); + self.query.visual_threshold = Some(threshold); + self + } + + /// Build the query. + pub fn build(self) -> Query { + self.query + } +} + +/// The result of executing a query. +#[derive(Debug, Clone)] +pub struct QueryResult { + /// The matching assertions. + pub assertions: Vec, + + /// Total number of matches (may be greater than assertions.len() if limited). + pub total_count: usize, + + /// Whether there are more results beyond the limit. + pub has_more: bool, +} + +impl QueryResult { + /// Create an empty result. + pub fn empty() -> Self { + Self { assertions: Vec::new(), total_count: 0, has_more: false } + } + + /// Create a result with the given assertions. + pub fn with_assertions(assertions: Vec) -> Self { + let total_count = assertions.len(); + Self { assertions, total_count, has_more: false } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use stemedb_core::testing::AssertionBuilder; + + fn create_test_assertion( + subject: &str, + predicate: &str, + lifecycle: LifecycleStage, + ) -> Assertion { + AssertionBuilder::new() + .subject(subject) + .predicate(predicate) + .object_text("test") + .confidence(0.95) + .lifecycle(lifecycle) + .build() + } + + #[test] + fn test_query_builder() { + let query = Query::builder() + .subject("Tesla") + .predicate("revenue") + .lifecycle(LifecycleStage::Approved) + .limit(10) + .build(); + + assert_eq!(query.subject, Some("Tesla".to_string())); + assert_eq!(query.predicate, Some("revenue".to_string())); + assert_eq!(query.lifecycle, Some(LifecycleStage::Approved)); + assert_eq!(query.limit, Some(10)); + } + + #[test] + fn test_query_matches_all_filters() { + let assertion = create_test_assertion("Tesla", "has_revenue", LifecycleStage::Approved); + + // Query that matches + let query = Query::builder() + .subject("Tesla") + .predicate("has_revenue") + .lifecycle(LifecycleStage::Approved) + .build(); + + assert!(query.matches(&assertion)); + } + + #[test] + fn test_query_matches_subject_only() { + let assertion = create_test_assertion("Tesla", "has_revenue", LifecycleStage::Proposed); + + let query = Query::builder().subject("Tesla").build(); + + assert!(query.matches(&assertion)); + } + + #[test] + fn test_query_rejects_wrong_subject() { + let assertion = create_test_assertion("Apple", "has_revenue", LifecycleStage::Approved); + + let query = Query::builder().subject("Tesla").build(); + + assert!(!query.matches(&assertion)); + } + + #[test] + fn test_query_rejects_wrong_lifecycle() { + let assertion = create_test_assertion("Tesla", "has_revenue", LifecycleStage::Proposed); + + let query = Query::builder().subject("Tesla").lifecycle(LifecycleStage::Approved).build(); + + assert!(!query.matches(&assertion)); + } + + #[test] + fn test_empty_query_matches_all() { + let assertion = create_test_assertion("Tesla", "has_revenue", LifecycleStage::Proposed); + + let query = Query::new(); + + assert!(query.matches(&assertion)); + } + + #[test] + fn test_query_result_empty() { + let result = QueryResult::empty(); + assert!(result.assertions.is_empty()); + assert_eq!(result.total_count, 0); + assert!(!result.has_more); + } + + // ======================================================================== + // Visual Hash Query Tests + // ======================================================================== + + #[test] + fn test_hamming_distance_zero() { + let a: PHash = [0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0]; + let b: PHash = [0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0]; + assert_eq!(hamming_distance(&a, &b), 0); + } + + #[test] + fn test_hamming_distance_max() { + // All zeros vs all ones = 64 bits different + let a: PHash = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + let b: PHash = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]; + assert_eq!(hamming_distance(&a, &b), 64); + } + + #[test] + fn test_hamming_distance_partial() { + // 0x08 = 0000 1000, 0x0F = 0000 1111 + // XOR = 0000 0111 = 3 bits different + let a: PHash = [0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + let b: PHash = [0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + assert_eq!(hamming_distance(&a, &b), 3); + } + + #[test] + fn test_hamming_distance_single_bit() { + let a: PHash = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + let b: PHash = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01]; + assert_eq!(hamming_distance(&a, &b), 1); + } + + #[test] + fn test_parse_hex_phash_valid() { + let result = parse_hex_phash("a3f2b1c4d5e6f708"); + assert!(result.is_some()); + let hash = result.unwrap(); + assert_eq!(hash, [0xa3, 0xf2, 0xb1, 0xc4, 0xd5, 0xe6, 0xf7, 0x08]); + } + + #[test] + fn test_parse_hex_phash_invalid_length() { + // Too short + assert!(parse_hex_phash("a3f2b1c4d5e6f7").is_none()); + // Too long + assert!(parse_hex_phash("a3f2b1c4d5e6f70800").is_none()); + // Empty + assert!(parse_hex_phash("").is_none()); + } + + #[test] + fn test_parse_hex_phash_invalid_chars() { + // Contains 'g' which is not valid hex + assert!(parse_hex_phash("a3f2b1c4d5e6f70g").is_none()); + } + + #[test] + fn test_parse_hex_phash_case_insensitive() { + let lower = parse_hex_phash("a3f2b1c4d5e6f708"); + let upper = parse_hex_phash("A3F2B1C4D5E6F708"); + let mixed = parse_hex_phash("A3f2B1c4D5e6F708"); + + assert!(lower.is_some()); + assert_eq!(lower, upper); + assert_eq!(lower, mixed); + } + + #[test] + fn test_visual_near_exact_match() { + let visual_hash: PHash = [0xa3, 0xf2, 0xb1, 0xc4, 0xd5, 0xe6, 0xf7, 0x08]; + let assertion = AssertionBuilder::new().subject("test").visual_hash(visual_hash).build(); + + // Exact match with threshold 0 + let query = Query::builder().visual_near("a3f2b1c4d5e6f708", 0).build(); + + assert!(query.matches(&assertion)); + } + + #[test] + fn test_visual_near_within_threshold() { + // Hash with 3 bits different in first byte + let visual_hash: PHash = [0xa0, 0xf2, 0xb1, 0xc4, 0xd5, 0xe6, 0xf7, 0x08]; + let assertion = AssertionBuilder::new().subject("test").visual_hash(visual_hash).build(); + + // Query for a3... but assertion has a0... + // 0xa3 = 1010 0011, 0xa0 = 1010 0000 + // XOR = 0000 0011 = 2 bits different + let query = Query::builder() + .visual_near("a3f2b1c4d5e6f708", 5) // threshold 5, distance 2 + .build(); + + assert!(query.matches(&assertion)); + } + + #[test] + fn test_visual_near_exceeds_threshold() { + // Hash with many bits different + let visual_hash: PHash = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + let assertion = AssertionBuilder::new().subject("test").visual_hash(visual_hash).build(); + + // Query for a3f2... (many bits set) vs 0000... = large distance + // a3f2b1c4d5e6f708 = many 1 bits, distance will be >> 5 + let query = Query::builder().visual_near("a3f2b1c4d5e6f708", 5).build(); + + assert!(!query.matches(&assertion)); + } + + #[test] + fn test_visual_near_skips_assertions_without_hash() { + // Assertion without visual_hash + let assertion = AssertionBuilder::new().subject("test").build(); + + assert!(assertion.visual_hash.is_none()); + + let query = Query::builder().visual_near("a3f2b1c4d5e6f708", 8).build(); + + // Should not match because assertion has no visual_hash + assert!(!query.matches(&assertion)); + } + + #[test] + fn test_visual_near_invalid_hex() { + let visual_hash: PHash = [0xa3, 0xf2, 0xb1, 0xc4, 0xd5, 0xe6, 0xf7, 0x08]; + let assertion = AssertionBuilder::new().subject("test").visual_hash(visual_hash).build(); + + // Invalid hex string in query + let query = Query::builder().visual_near("not_valid_hex!!!", 8).build(); + + // Should not match due to invalid hex + assert!(!query.matches(&assertion)); + } + + #[test] + fn test_visual_near_wrong_length_hex() { + let visual_hash: PHash = [0xa3, 0xf2, 0xb1, 0xc4, 0xd5, 0xe6, 0xf7, 0x08]; + let assertion = AssertionBuilder::new().subject("test").visual_hash(visual_hash).build(); + + // Hex string too short + let query = Query::builder().visual_near("a3f2b1c4", 8).build(); + + assert!(!query.matches(&assertion)); + } + + #[test] + fn test_visual_near_combines_with_subject() { + let visual_hash: PHash = [0xa3, 0xf2, 0xb1, 0xc4, 0xd5, 0xe6, 0xf7, 0x08]; + let assertion = AssertionBuilder::new().subject("Tesla").visual_hash(visual_hash).build(); + + // Both filters must pass (AND semantics) + let query = Query::builder().subject("Tesla").visual_near("a3f2b1c4d5e6f708", 0).build(); + assert!(query.matches(&assertion)); + + // Wrong subject, right visual + let query = Query::builder().subject("Apple").visual_near("a3f2b1c4d5e6f708", 0).build(); + assert!(!query.matches(&assertion)); + + // Right subject, wrong visual (exceeds threshold) + let query = Query::builder().subject("Tesla").visual_near("0000000000000000", 5).build(); + assert!(!query.matches(&assertion)); + } + + #[test] + fn test_visual_near_default_threshold() { + let visual_hash: PHash = [0xa3, 0xf2, 0xb1, 0xc4, 0xd5, 0xe6, 0xf7, 0x08]; + let assertion = AssertionBuilder::new().subject("test").visual_hash(visual_hash).build(); + + // Query without explicit threshold - should use default of 8 + let mut query = Query::new(); + query.visual_near = Some("a3f2b1c4d5e6f708".to_string()); + // No threshold set, should default to 8 + + assert!(query.matches(&assertion)); // Exact match, distance 0 < 8 + } + + #[test] + fn test_query_builder_visual_near() { + let query = Query::builder().subject("Tesla").visual_near("a3f2b1c4d5e6f708", 10).build(); + + assert_eq!(query.subject, Some("Tesla".to_string())); + assert_eq!(query.visual_near, Some("a3f2b1c4d5e6f708".to_string())); + assert_eq!(query.visual_threshold, Some(10)); + } + + #[test] + fn test_visual_near_max_threshold_matches_any() { + // Max threshold of 64 should match any visual_hash (max hamming distance is 64) + let visual_hash: PHash = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + let assertion = AssertionBuilder::new().subject("test").visual_hash(visual_hash).build(); + + // Query with totally different hash (all 1s vs all 0s = 64 bits different) + // but max threshold of 64 should still match + let query = Query::builder().visual_near("ffffffffffffffff", 64).build(); + + assert!(query.matches(&assertion)); + } + + #[test] + fn test_visual_near_threshold_63_rejects_max_distance() { + // Threshold of 63 should reject assertions with max distance (64) + let visual_hash: PHash = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + let assertion = AssertionBuilder::new().subject("test").visual_hash(visual_hash).build(); + + // All 1s vs all 0s = 64 bits different, threshold 63 should reject + let query = Query::builder().visual_near("ffffffffffffffff", 63).build(); + + assert!(!query.matches(&assertion)); + } +} diff --git a/crates/stemedb-query/src/skeptic.rs b/crates/stemedb-query/src/skeptic.rs new file mode 100644 index 0000000..604d72d --- /dev/null +++ b/crates/stemedb-query/src/skeptic.rs @@ -0,0 +1,234 @@ +//! Skeptic View builder for "Trust but Verify" queries. +//! +//! While `QueryEngine` returns assertions and `Materializer` creates single-winner +//! views, `SkepticResolver` builds conflict analysis views that surface disagreement. +//! +//! # Use Case +//! +//! A medical researcher queries "Semaglutide muscle_effect" and instead of getting +//! a single answer, they see: +//! - Status: Contested (conflict_score: 0.72) +//! - Claim A: "Significant loss" (45% support) +//! - Claim B: "Minimal loss" (35% support) +//! - Claim C: "No effect" (20% support) +//! +//! This enables transparent decision-making where users understand the certainty +//! of the data they're using. +//! +//! # Example +//! +//! ```ignore +//! use stemedb_query::SkepticResolver; +//! +//! let resolver = SkepticResolver::new(store, vote_store, trust_store); +//! let view = resolver.resolve("Semaglutide", "muscle_effect").await?; +//! +//! if view.status == ResolutionStatus::Contested { +//! println!("⚠️ This fact is disputed!"); +//! for claim in &view.claims { +//! println!(" {} - {:.0}% support", claim.value, claim.weight_share * 100.0); +//! } +//! } +//! ``` + +use crate::error::Result; +use std::sync::Arc; +use stemedb_core::types::{ConflictAnalysis, EntityId, RelationId}; +use stemedb_lens::{AnalysisLens, SkepticLens}; +use stemedb_storage::trust_rank_store::TrustRankStore; +use stemedb_storage::vote_store::VoteStore; +use stemedb_storage::{GenericIndexStore, IndexStore, KVStore}; +use tracing::instrument; + +/// A "Trust but Verify" view that shows disagreement instead of hiding it. +/// +/// Where `MaterializedView` answers "What is the answer?", +/// `SkepticView` answers "What are the competing claims and how much do they disagree?" +#[derive(Debug, Clone)] +pub struct SkepticView { + /// The subject that was queried. + pub subject: EntityId, + /// The predicate that was queried. + pub predicate: RelationId, + /// The conflict analysis from SkepticLens. + pub analysis: ConflictAnalysis, + /// Unix timestamp when this view was computed. + pub computed_at: u64, + /// Which lens was used (always "Skeptic" for now). + pub lens_name: String, +} + +/// Resolves subject+predicate pairs into SkepticViews. +/// +/// Unlike the `Materializer` which picks winners, `SkepticResolver` surfaces +/// all competing claims with their relative support. +pub struct SkepticResolver { + store: Arc, + index_store: GenericIndexStore>, + lens: SkepticLens, +} + +impl SkepticResolver +where + S: KVStore + 'static, + V: VoteStore + 'static, + T: TrustRankStore + 'static, +{ + /// Create a new SkepticResolver. + pub fn new(store: Arc, vote_store: Arc, trust_store: Arc) -> Self { + let index_store = GenericIndexStore::new(store.clone()); + let lens = SkepticLens::new(vote_store, trust_store); + Self { store, index_store, lens } + } + + /// Resolve a subject+predicate pair into a SkepticView. + /// + /// Returns `None` if no assertions exist for the given subject+predicate. + #[instrument(skip(self), fields(subject = %subject, predicate = %predicate))] + pub async fn resolve(&self, subject: &str, predicate: &str) -> Result> { + // Fetch all candidate assertions using the compound index + let hash_list = self.index_store.get_by_subject_predicate(subject, predicate).await?; + + if hash_list.is_empty() { + return Ok(None); + } + + // Load all assertions + let mut candidates = Vec::with_capacity(hash_list.len()); + for hash in hash_list { + let key = format!("H:{}", hex::encode(hash)).into_bytes(); + if let Some(data) = self.store.get(&key).await? { + if let Ok(assertion) = stemedb_core::serde::deserialize(&data) { + candidates.push(assertion); + } + } + } + + if candidates.is_empty() { + return Ok(None); + } + + // Run the SkepticLens + let analysis = self.lens.analyze(&candidates).await; + + Ok(Some(SkepticView { + subject: subject.to_string(), + predicate: predicate.to_string(), + analysis, + computed_at: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0), + lens_name: self.lens.name().to_string(), + })) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use stemedb_core::testing::AssertionBuilder; + use stemedb_core::types::ResolutionStatus; + use stemedb_storage::{GenericTrustRankStore, GenericVoteStore, SledStore}; + + async fn store_assertion( + store: &Arc, + index_store: &GenericIndexStore>, + subject: &str, + predicate: &str, + value: f64, + confidence: f32, + ) { + let assertion = AssertionBuilder::new() + .subject(subject) + .predicate(predicate) + .object_number(value) + .confidence(confidence) + .build(); + + let bytes = stemedb_core::serde::serialize(&assertion).expect("serialize"); + let hash = blake3::hash(&bytes); + let key = format!("H:{}", hash.to_hex()).into_bytes(); + store.put(&key, &bytes).await.expect("put"); + + let assertion_hash: [u8; 32] = *hash.as_bytes(); + index_store.add_to_indexes(subject, predicate, &assertion_hash).await.expect("index"); + } + + #[tokio::test] + async fn test_resolve_empty() { + let store = Arc::new(SledStore::open_temp().expect("store")); + let vote_store = Arc::new(GenericVoteStore::new((*store).clone())); + let trust_store = Arc::new(GenericTrustRankStore::new((*store).clone())); + let resolver = SkepticResolver::new(store, vote_store, trust_store); + + let result = resolver.resolve("NonExistent", "predicate").await.expect("resolve"); + assert!(result.is_none()); + } + + #[tokio::test] + async fn test_resolve_single_claim() { + let store = Arc::new(SledStore::open_temp().expect("store")); + let index_store = GenericIndexStore::new(store.clone()); + + store_assertion(&store, &index_store, "Drug", "effect", 100.0, 0.9).await; + + let vote_store = Arc::new(GenericVoteStore::new((*store).clone())); + let trust_store = Arc::new(GenericTrustRankStore::new((*store).clone())); + let resolver = SkepticResolver::new(store, vote_store, trust_store); + + let result = resolver.resolve("Drug", "effect").await.expect("resolve"); + assert!(result.is_some()); + + let view = result.expect("view"); + assert_eq!(view.subject, "Drug"); + assert_eq!(view.predicate, "effect"); + assert_eq!(view.analysis.status, ResolutionStatus::Unanimous); + assert_eq!(view.analysis.claims.len(), 1); + } + + #[tokio::test] + async fn test_resolve_contested_claims() { + let store = Arc::new(SledStore::open_temp().expect("store")); + let index_store = GenericIndexStore::new(store.clone()); + + // Add two conflicting claims with equal weight + store_assertion(&store, &index_store, "Drug", "effect", 100.0, 0.5).await; + store_assertion(&store, &index_store, "Drug", "effect", 200.0, 0.5).await; + + let vote_store = Arc::new(GenericVoteStore::new((*store).clone())); + let trust_store = Arc::new(GenericTrustRankStore::new((*store).clone())); + let resolver = SkepticResolver::new(store, vote_store, trust_store); + + let result = resolver.resolve("Drug", "effect").await.expect("resolve"); + assert!(result.is_some()); + + let view = result.expect("view"); + assert_eq!(view.analysis.status, ResolutionStatus::Contested); + assert_eq!(view.analysis.claims.len(), 2); + assert!(view.analysis.conflict_score > 0.9); // Near 1.0 for 50/50 split + } + + #[tokio::test] + async fn test_resolve_includes_computed_at() { + let store = Arc::new(SledStore::open_temp().expect("store")); + let index_store = GenericIndexStore::new(store.clone()); + + store_assertion(&store, &index_store, "Drug", "effect", 100.0, 0.9).await; + + let vote_store = Arc::new(GenericVoteStore::new((*store).clone())); + let trust_store = Arc::new(GenericTrustRankStore::new((*store).clone())); + let resolver = SkepticResolver::new(store, vote_store, trust_store); + + let result = resolver.resolve("Drug", "effect").await.expect("resolve"); + let view = result.expect("view"); + + // computed_at should be recent (within last minute) + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("time") + .as_secs(); + assert!(view.computed_at <= now); + assert!(view.computed_at > now - 60); + } +} diff --git a/crates/stemedb-query/tests/e2e_pipeline.rs b/crates/stemedb-query/tests/e2e_pipeline.rs new file mode 100644 index 0000000..db432e4 --- /dev/null +++ b/crates/stemedb-query/tests/e2e_pipeline.rs @@ -0,0 +1,407 @@ +//! E2E integration tests for the StemeDB pipeline. +//! +//! Validates the full data flow: WAL -> IngestWorker -> Materializer -> QueryEngine +//! +//! # Test Coverage +//! +//! | Test | Pipeline Stage | Validates | +//! |------|---------------|-----------| +//! | `test_e2e_write_materialize_read` | Full | Basic happy path | +//! | `test_e2e_vote_consensus` | Full + Votes | Vote-weighted resolution | +//! | `test_e2e_update_winner` | Full + Update | Winner changes on re-materialize | +//! | `test_e2e_cursor_persistence` | WAL + Ingest | Cursor survives worker restart | +//! | `test_e2e_notify_integration` | Ingest | Event-driven notification channel | + +#![allow(clippy::expect_used)] // Test code uses expect() for clear failure messages + +use ed25519_dalek::{Signer, SigningKey}; +use rand::rngs::OsRng; +use std::sync::Arc; +use stemedb_core::serde::serialize; +use stemedb_core::testing::AssertionBuilder; +use stemedb_core::types::{Assertion, LifecycleStage, ObjectValue, SignatureEntry, Vote}; +use stemedb_ingest::worker::{serialize_assertion, IngestWorker}; +use stemedb_lens::{RecencyLens, SyncLensWrapper, VoteAwareConsensusLens}; +use stemedb_query::{Materializer, Query, QueryEngine}; +use stemedb_storage::{GenericVoteStore, KVStore, SledStore, VoteStore}; +use stemedb_wal::Journal; +use tempfile::tempdir; +use tokio::sync::{Mutex, Notify}; + +// ============================================================================ +// TEST HELPERS +// ============================================================================ + +/// Create a signed assertion with Ed25519 signature. +/// +/// The signature signs the message `"{subject}:{predicate}"` which matches +/// IngestWorker's verification logic. +fn create_signed_assertion( + subject: &str, + predicate: &str, + value: f64, + timestamp: u64, +) -> Assertion { + let mut csprng = OsRng; + let signing_key = SigningKey::generate(&mut csprng); + let verifying_key = signing_key.verifying_key(); + + let message = format!("{}:{}", subject, predicate); + let signature = signing_key.sign(message.as_bytes()); + + AssertionBuilder::new() + .subject(subject) + .predicate(predicate) + .object_number(value) + .confidence(0.95) + .lifecycle(LifecycleStage::Proposed) + .timestamp(timestamp) + .signatures(vec![SignatureEntry { + agent_id: verifying_key.to_bytes(), + signature: signature.to_bytes(), + timestamp, + }]) + .build() +} + +/// Compute the content-addressed hash of an assertion. +/// +/// Matches the hash computation in the ingestion pipeline. +fn compute_assertion_hash(assertion: &Assertion) -> [u8; 32] { + let bytes = serialize(assertion).expect("serialize assertion"); + *blake3::hash(&bytes).as_bytes() +} + +/// Create a test vote for an assertion. +fn create_vote(assertion_hash: [u8; 32], agent_idx: u8, weight: f32, timestamp: u64) -> Vote { + let mut agent_id = [0u8; 32]; + agent_id[0] = agent_idx; + + Vote { assertion_hash, agent_id, weight, signature: [0u8; 64], timestamp } +} + +// ============================================================================ +// E2E TESTS +// ============================================================================ + +/// Test 1: Basic pipeline - write, ingest, materialize, query. +/// +/// Proves the fundamental flow works end-to-end: +/// 1. Write signed assertion to WAL +/// 2. IngestWorker reads from WAL and stores in KV +/// 3. Materializer creates MV:{subject}:{predicate} +/// 4. QueryEngine returns the assertion +#[tokio::test] +async fn test_e2e_write_materialize_read() { + let dir = tempdir().expect("create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + // === Step 1: Write assertion to WAL === + let assertion = create_signed_assertion("Tesla_Inc", "has_revenue", 96.7, 1000); + + let mut journal = Journal::open(&wal_dir).expect("open journal"); + let payload = serialize_assertion(&assertion).expect("serialize"); + journal.append(payload).expect("append to WAL"); + + // === Step 2: Run IngestWorker to process WAL === + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(SledStore::open(&db_dir).expect("open store")); + let notify = Arc::new(Notify::new()); + + let mut worker = IngestWorker::new(journal.clone(), store.clone()) + .await + .expect("create worker") + .with_notify(notify.clone()); + + let bytes_processed = worker.step().await.expect("ingest step"); + assert!(bytes_processed > 0, "should have processed data from WAL"); + + // Verify assertion stored at H:{hash} + let assertion_hash = compute_assertion_hash(&assertion); + let h_key = format!("H:{}", hex::encode(assertion_hash)).into_bytes(); + let stored = store.get(&h_key).await.expect("get assertion"); + assert!(stored.is_some(), "assertion should be stored at H: key"); + + // Verify compound index SP:{subject}:{predicate} created + let sp_key = b"SP:Tesla_Inc:has_revenue"; + let sp_entries = store.scan_prefix(sp_key).await.expect("scan SP: prefix"); + assert_eq!(sp_entries.len(), 1, "should have one SP: index entry"); + + // === Step 3: Run Materializer === + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let lens = VoteAwareConsensusLens::new(vote_store); + let materializer = Materializer::new(store.clone(), Box::new(lens)); + + let report = materializer.step().await.expect("materialize step"); + assert_eq!(report.pairs_scanned, 1, "should scan one subject+predicate pair"); + assert_eq!(report.views_updated, 1, "should update one materialized view"); + + // Verify MV:{subject}:{predicate} written + let mv_key = b"MV:Tesla_Inc:has_revenue"; + let mv_data = store.get(mv_key).await.expect("get MV"); + assert!(mv_data.is_some(), "materialized view should exist"); + + // === Step 4: Query via QueryEngine === + let engine = QueryEngine::new(store.clone()); + let query = Query::builder().subject("Tesla_Inc").predicate("has_revenue").build(); + + let result = engine.execute(&query).await.expect("execute query"); + assert_eq!(result.assertions.len(), 1, "query should return one assertion"); + assert_eq!(result.assertions[0].subject, "Tesla_Inc"); + assert_eq!(result.assertions[0].predicate, "has_revenue"); + assert_eq!(result.assertions[0].object, ObjectValue::Number(96.7)); +} + +/// Test 2: Vote-weighted consensus. +/// +/// Proves that VoteAwareConsensusLens selects the assertion with highest +/// aggregate vote weight: +/// 1. Write two assertions with same subject+predicate but different values +/// 2. Add votes favoring assertion_a (3 votes, weight 0.9 each) +/// 3. Add 1 vote for assertion_b (weight 0.2) +/// 4. Materializer picks assertion_a as winner +#[tokio::test] +async fn test_e2e_vote_consensus() { + let dir = tempdir().expect("create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + // Create two competing assertions + let assertion_a = create_signed_assertion("Semaglutide", "muscle_effect", -5.0, 1000); + let assertion_b = create_signed_assertion("Semaglutide", "muscle_effect", -15.0, 1100); + + // Write both to WAL + let mut journal = Journal::open(&wal_dir).expect("open journal"); + journal.append(serialize_assertion(&assertion_a).expect("ser")).expect("append"); + journal.append(serialize_assertion(&assertion_b).expect("ser")).expect("append"); + + // Ingest both + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(SledStore::open(&db_dir).expect("open store")); + + let mut worker = + IngestWorker::new(journal.clone(), store.clone()).await.expect("create worker"); + + let bytes1 = worker.step().await.expect("step 1"); + assert!(bytes1 > 0, "should ingest first assertion"); + + let bytes2 = worker.step().await.expect("step 2"); + assert!(bytes2 > 0, "should ingest second assertion"); + + // Verify both are stored + let h_entries = store.scan_prefix(b"H:").await.expect("scan H:"); + assert_eq!(h_entries.len(), 2, "should have two assertions"); + + // Add votes via VoteStore + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + + let hash_a = compute_assertion_hash(&assertion_a); + let hash_b = compute_assertion_hash(&assertion_b); + + // assertion_a gets 3 votes (total weight = 2.7) + for i in 0..3 { + let vote = create_vote(hash_a, i, 0.9, 2000 + i as u64); + vote_store.put_vote(&vote).await.expect("put vote for a"); + } + + // assertion_b gets 1 vote (total weight = 0.2) + let vote_b = create_vote(hash_b, 10, 0.2, 2100); + vote_store.put_vote(&vote_b).await.expect("put vote for b"); + + // Materialize with VoteAwareConsensusLens + let lens = VoteAwareConsensusLens::new(Arc::clone(&vote_store)); + let materializer = Materializer::new(store.clone(), Box::new(lens)); + + let report = materializer.step().await.expect("materialize"); + assert_eq!(report.views_updated, 1); + + // Query should return assertion_a (higher aggregate weight) + let engine = QueryEngine::new(store.clone()); + let query = Query::builder().subject("Semaglutide").predicate("muscle_effect").build(); + + let result = engine.execute(&query).await.expect("query"); + assert_eq!(result.assertions.len(), 1); + assert_eq!( + result.assertions[0].object, + ObjectValue::Number(-5.0), + "should return assertion_a (higher vote weight)" + ); +} + +/// Test 3: Winner changes after new assertion. +/// +/// Proves that re-materialization updates the winner when new data arrives: +/// 1. Write assertion_v1 (timestamp=1000), ingest, materialize +/// 2. Query returns v1 +/// 3. Write assertion_v2 (timestamp=2000, same subject+predicate) +/// 4. Re-ingest and re-materialize with RecencyLens +/// 5. Query returns v2 (newer timestamp wins) +#[tokio::test] +async fn test_e2e_update_winner() { + let dir = tempdir().expect("create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + // === Phase 1: Initial assertion === + let assertion_v1 = create_signed_assertion("Apple_Inc", "stock_price", 150.0, 1000); + + let mut journal = Journal::open(&wal_dir).expect("open journal"); + journal.append(serialize_assertion(&assertion_v1).expect("ser")).expect("append v1"); + + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(SledStore::open(&db_dir).expect("open store")); + + // Ingest v1 + let mut worker = IngestWorker::new(journal.clone(), store.clone()).await.expect("worker"); + let bytes = worker.step().await.expect("step v1"); + assert!(bytes > 0); + + // Materialize with RecencyLens (wrapped for AsyncLens trait) + let lens = SyncLensWrapper(RecencyLens); + let materializer = Materializer::new(store.clone(), Box::new(lens)); + materializer.step().await.expect("materialize v1"); + + // Query returns v1 + let engine = QueryEngine::new(store.clone()); + let query = Query::builder().subject("Apple_Inc").predicate("stock_price").build(); + + let result = engine.execute(&query).await.expect("query v1"); + assert_eq!(result.assertions.len(), 1); + assert_eq!(result.assertions[0].object, ObjectValue::Number(150.0)); + assert_eq!(result.assertions[0].timestamp, 1000); + + // === Phase 2: New assertion with higher timestamp === + let assertion_v2 = create_signed_assertion("Apple_Inc", "stock_price", 175.0, 2000); + + // Write to WAL + { + let mut journal = journal.lock().await; + journal.append(serialize_assertion(&assertion_v2).expect("ser")).expect("append v2"); + } + + // Re-ingest (worker resumes from cursor) + let mut worker2 = IngestWorker::new(journal.clone(), store.clone()).await.expect("worker2"); + let bytes2 = worker2.step().await.expect("step v2"); + assert!(bytes2 > 0, "should process new assertion"); + + // Verify both assertions are now stored + let h_entries = store.scan_prefix(b"H:").await.expect("scan"); + assert_eq!(h_entries.len(), 2, "should have two assertions"); + + // Re-materialize + let lens2 = SyncLensWrapper(RecencyLens); + let materializer2 = Materializer::new(store.clone(), Box::new(lens2)); + materializer2.step().await.expect("materialize v2"); + + // Query returns v2 (newer timestamp wins with RecencyLens) + let result2 = engine.execute(&query).await.expect("query v2"); + assert_eq!(result2.assertions.len(), 1); + assert_eq!( + result2.assertions[0].object, + ObjectValue::Number(175.0), + "should return v2 (more recent)" + ); + assert_eq!(result2.assertions[0].timestamp, 2000); +} + +/// Test: Cursor persistence across worker restarts. +/// +/// Validates that the IngestWorker correctly resumes from the last cursor, +/// avoiding replay of already-processed records. +#[tokio::test] +async fn test_e2e_cursor_persistence() { + let dir = tempdir().expect("create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + // Write 3 assertions to WAL + let a1 = create_signed_assertion("Entity_A", "prop", 1.0, 1000); + let a2 = create_signed_assertion("Entity_B", "prop", 2.0, 2000); + let a3 = create_signed_assertion("Entity_C", "prop", 3.0, 3000); + + let mut journal = Journal::open(&wal_dir).expect("open journal"); + journal.append(serialize_assertion(&a1).expect("ser")).expect("append"); + journal.append(serialize_assertion(&a2).expect("ser")).expect("append"); + journal.append(serialize_assertion(&a3).expect("ser")).expect("append"); + + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(SledStore::open(&db_dir).expect("open store")); + + // Worker 1: Process first 2 assertions + let mut worker1 = IngestWorker::new(journal.clone(), store.clone()).await.expect("worker1"); + worker1.step().await.expect("step 1"); + worker1.step().await.expect("step 2"); + + // Verify 2 assertions stored + let h_entries = store.scan_prefix(b"H:").await.expect("scan"); + assert_eq!(h_entries.len(), 2, "worker1 should have processed 2 assertions"); + + // Drop worker1, simulate restart + drop(worker1); + + // Worker 2: Should resume from cursor and only process the third assertion + let mut worker2 = IngestWorker::new(journal.clone(), store.clone()).await.expect("worker2"); + + let mut steps = 0; + while worker2.step().await.expect("step") > 0 { + steps += 1; + } + assert_eq!(steps, 1, "worker2 should only process 1 new assertion"); + + // Verify all 3 assertions now stored + let h_entries = store.scan_prefix(b"H:").await.expect("scan"); + assert_eq!(h_entries.len(), 3, "should have all 3 assertions"); +} + +/// Test: Event-driven materialization via Notify. +/// +/// Validates that the IngestWorker signals downstream consumers (Materializer) +/// when new data is available. +#[tokio::test] +async fn test_e2e_notify_integration() { + let dir = tempdir().expect("create temp dir"); + let wal_dir = dir.path().join("wal"); + let db_dir = dir.path().join("db"); + + let assertion = create_signed_assertion("Tesla_Inc", "deliveries", 500000.0, 1000); + + let mut journal = Journal::open(&wal_dir).expect("open journal"); + journal.append(serialize_assertion(&assertion).expect("ser")).expect("append"); + + let journal = Arc::new(Mutex::new(journal)); + let store = Arc::new(SledStore::open(&db_dir).expect("open store")); + let notify = Arc::new(Notify::new()); + + // Track if notification was received + let notify_clone = Arc::clone(¬ify); + let notification_received = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let notification_received_clone = Arc::clone(¬ification_received); + + // Spawn listener that waits for notification + let listener = tokio::spawn(async move { + tokio::time::timeout(std::time::Duration::from_secs(5), notify_clone.notified()) + .await + .expect("timeout waiting for notification"); + notification_received_clone.store(true, std::sync::atomic::Ordering::SeqCst); + }); + + // Give listener time to start + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + + // Ingest with notify attached + let mut worker = IngestWorker::new(journal.clone(), store.clone()) + .await + .expect("worker") + .with_notify(notify); + + worker.step().await.expect("step"); + + // Wait for listener to complete + listener.await.expect("listener task"); + + assert!( + notification_received.load(std::sync::atomic::Ordering::SeqCst), + "notification should have been received" + ); +} diff --git a/crates/stemedb-sim/Cargo.toml b/crates/stemedb-sim/Cargo.toml index 344e377..82e3023 100644 --- a/crates/stemedb-sim/Cargo.toml +++ b/crates/stemedb-sim/Cargo.toml @@ -13,7 +13,9 @@ stemedb-core = { path = "../stemedb-core" } stemedb-wal = { path = "../stemedb-wal" } stemedb-ingest = { path = "../stemedb-ingest" } stemedb-storage = { path = "../stemedb-storage" } -tokio = { version = "1.36", features = ["full"] } +stemedb-query = { path = "../stemedb-query" } +stemedb-lens = { path = "../stemedb-lens" } +tokio = { version = "1", features = ["full"] } ed25519-dalek = { version = "2.1", features = ["rand_core"] } rand = "0.8" tracing = "0.1" @@ -21,4 +23,6 @@ tracing-subscriber = "0.3" rkyv = { version = "0.7", features = ["validation"] } bytecheck = "0.6" thiserror = "1.0" -tempfile = "3.10" \ No newline at end of file +tempfile = "3.10" +blake3 = "1.5" +hex = "0.4" \ No newline at end of file diff --git a/crates/stemedb-sim/src/lib.rs b/crates/stemedb-sim/src/lib.rs new file mode 100644 index 0000000..bfb3ac3 --- /dev/null +++ b/crates/stemedb-sim/src/lib.rs @@ -0,0 +1,1525 @@ +//! StemeDB Simulation Library +//! +//! This module provides the core simulation logic for validating the StemeDB +//! "Spine" (Durability + Schema + Ingestion) and "Cortex" (Query + Lenses) +//! under agent-driven stress tests. +//! +//! # Design Philosophy +//! +//! Following "Philosophy of Software Design" principles: +//! - **Deep Module**: Simple `run_simulation()` interface hides all complexity +//! - **Define Errors Out of Existence**: Failures are collected, not panicked +//! - **Strategic Programming**: Built for testability and extension +//! +//! # Arena Phases +//! +//! - **Arena 0**: Spine validation (WAL + Ingestor + KV Store) +//! - **Arena 1**: Query path validation (QueryEngine + Lenses + Lifecycle + Audits) +//! - **Arena 2**: Voting & Consensus (VoteStore + VoteAwareConsensusLens) +//! +//! # Example +//! +//! ```ignore +//! use stemedb_sim::{run_simulation, SimulationConfig}; +//! +//! let config = SimulationConfig::default(); +//! let result = run_simulation(config).await?; +//! +//! assert_eq!(result.assertions_verified, result.assertions_written); +//! assert!(result.errors.is_empty()); +//! ``` + +use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; +use rand::rngs::OsRng; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use stemedb_core::serde::serialize; +use stemedb_core::types::{ + Assertion, ContributingAssertion, Hash, LifecycleStage, ObjectValue, QueryAudit, QueryId, + QueryParams, SignatureEntry, SourceClass, Vote, +}; +use stemedb_ingest::{serialize_assertion, serialize_vote, Ingestor}; +use stemedb_lens::{AsyncLens, Lens, RecencyLens, VoteAwareConsensusLens}; +use stemedb_query::{Query, QueryEngine}; +use stemedb_storage::{AuditStore, GenericAuditStore, GenericVoteStore, KVStore, SledStore}; +use stemedb_wal::Journal; +use thiserror::Error; +use tokio::sync::Mutex; +use tracing::{debug, info, warn}; + +// ============================================================================ +// Public Types +// ============================================================================ + +/// The outcome of a simulation run. +/// +/// This struct captures both success metrics and any errors encountered, +/// allowing callers to programmatically verify simulation outcomes. +#[derive(Debug, Clone)] +pub struct SimulationResult { + /// Number of assertions successfully written to WAL. + pub assertions_written: u64, + + /// Number of assertions successfully verified from KV store. + pub assertions_verified: u64, + + /// Number of queries executed via QueryEngine. + pub queries_executed: u64, + + /// Number of votes written to WAL. + pub votes_written: u64, + + /// Whether the recency lens test passed. + pub recency_test_passed: bool, + + /// Whether the lifecycle filtering test passed. + pub lifecycle_test_passed: bool, + + /// Whether the query audit verification passed. + pub audit_test_passed: bool, + + /// Whether the vote-aware consensus test passed (Arena 2.2). + pub vote_consensus_test_passed: bool, + + /// Whether the troll resistance test passed (Arena 2.3). + pub troll_resistance_test_passed: bool, + + /// Errors encountered during the simulation (non-fatal). + /// An empty vector indicates complete success. + pub errors: Vec, + + /// Number of agents that participated. + pub agent_count: usize, + + /// Number of ticks executed. + pub tick_count: usize, +} + +impl SimulationResult { + /// Returns true if the simulation completed without errors. + /// + /// Note: We don't check assertions_written == assertions_verified because + /// Arena 2 tests write additional test assertions that are verified through + /// the VoteAwareConsensusLens rather than the main verification loop. + pub fn is_success(&self) -> bool { + self.errors.is_empty() + && self.recency_test_passed + && self.lifecycle_test_passed + && self.audit_test_passed + && self.vote_consensus_test_passed + && self.troll_resistance_test_passed + } + + /// Returns a human-readable summary of the simulation. + pub fn summary(&self) -> String { + if self.is_success() { + format!( + "✅ Success: {} assertions, {} votes, {} queries | \ + recency={}, lifecycle={}, audit={}, vote_consensus={}, troll_resist={}", + self.assertions_written, + self.votes_written, + self.queries_executed, + if self.recency_test_passed { "✓" } else { "✗" }, + if self.lifecycle_test_passed { "✓" } else { "✗" }, + if self.audit_test_passed { "✓" } else { "✗" }, + if self.vote_consensus_test_passed { "✓" } else { "✗" }, + if self.troll_resistance_test_passed { "✓" } else { "✗" }, + ) + } else { + format!( + "❌ Failed: {} assertions, {} votes, {} errors | \ + recency={}, lifecycle={}, audit={}, vote_consensus={}, troll_resist={}", + self.assertions_written, + self.votes_written, + self.errors.len(), + if self.recency_test_passed { "✓" } else { "✗" }, + if self.lifecycle_test_passed { "✓" } else { "✗" }, + if self.audit_test_passed { "✓" } else { "✗" }, + if self.vote_consensus_test_passed { "✓" } else { "✗" }, + if self.troll_resistance_test_passed { "✓" } else { "✗" }, + ) + } + } +} + +/// A non-fatal error encountered during simulation. +#[derive(Debug, Clone)] +pub struct SimulationError { + /// Which tick the error occurred on (0-indexed), or 0 for scenario errors. + pub tick: u64, + + /// The category of error. + pub kind: ErrorKind, + + /// Human-readable error description. + pub message: String, +} + +/// Categories of simulation errors. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ErrorKind { + /// Failed to write assertion to WAL. + WriteFailure, + + /// Assertion not found in KV store after ingestion. + VerificationFailure, + + /// Ed25519 signature verification failed. + SignatureInvalid, + + /// Deserialization of stored data failed. + StorageCorruption, + + /// Serialization of assertion failed. + SerializationFailure, + + /// Query execution failed. + QueryFailure, + + /// Lens resolution produced unexpected result. + LensResolutionFailure, + + /// Audit trail verification failed. + AuditFailure, + + /// Failed to write vote to WAL. + VoteWriteFailure, + + /// Vote-aware consensus resolution failed. + VoteConsensusFailure, +} + +/// Configuration for a simulation run. +#[derive(Debug, Clone)] +pub struct SimulationConfig { + /// Number of agents to create. + pub agent_count: usize, + + /// Number of ticks (assertion cycles) to run. + pub tick_count: usize, + + /// Milliseconds to wait for ingestion to complete. + pub ingestion_wait_ms: u64, +} + +impl Default for SimulationConfig { + fn default() -> Self { + Self { agent_count: 3, tick_count: 10, ingestion_wait_ms: 500 } + } +} + +/// Fatal errors that prevent the simulation from running. +#[derive(Error, Debug)] +pub enum SimulationSetupError { + /// Failed to create temporary directory for WAL. + #[error("Failed to create WAL directory: {0}")] + WalDirectory(String), + + /// Failed to create temporary directory for KV store. + #[error("Failed to create store directory: {0}")] + StoreDirectory(String), + + /// Failed to open the WAL journal. + #[error("Failed to open journal: {0}")] + JournalOpen(String), + + /// Failed to open the KV store. + #[error("Failed to open store: {0}")] + StoreOpen(String), + + /// Failed to create the ingestor. + #[error("Failed to create ingestor: {0}")] + IngestorCreate(String), +} + +// ============================================================================ +// Internal Types +// ============================================================================ + +/// A simulated agent with a cryptographic identity. +struct Agent { + pub id: String, + signing_key: SigningKey, + verifying_key: VerifyingKey, +} + +impl Agent { + pub fn new(id: &str) -> Self { + let mut csprng = OsRng; + let signing_key = SigningKey::generate(&mut csprng); + let verifying_key = VerifyingKey::from(&signing_key); + Self { id: id.to_string(), signing_key, verifying_key } + } + + /// Get the agent's public key as a 32-byte array. + pub fn public_key(&self) -> [u8; 32] { + self.verifying_key.to_bytes() + } + + /// Create and sign an assertion with default lifecycle (Proposed). + pub fn sign_assertion(&self, subject: &str, predicate: &str, object: ObjectValue) -> Assertion { + self.sign_assertion_with_options(subject, predicate, object, LifecycleStage::Proposed, None) + } + + /// Create and sign an assertion with custom lifecycle and timestamp. + pub fn sign_assertion_with_options( + &self, + subject: &str, + predicate: &str, + object: ObjectValue, + lifecycle: LifecycleStage, + custom_timestamp: Option, + ) -> Assertion { + let timestamp = custom_timestamp.unwrap_or_else(|| { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) + }); + + // For simulation, we sign the concatenation of subject and predicate. + // In a real system, we'd sign the hash of the fact data. + let message = format!("{}:{}", subject, predicate); + let signature: Signature = self.signing_key.sign(message.as_bytes()); + + Assertion { + subject: subject.to_string(), + predicate: predicate.to_string(), + object, + parent_hash: None, + source_hash: [0u8; 32], + source_class: SourceClass::Expert, + visual_hash: None, + epoch: None, + lifecycle, + signatures: vec![SignatureEntry { + agent_id: self.verifying_key.to_bytes(), + signature: signature.to_bytes(), + timestamp, + }], + confidence: 1.0, + timestamp, + vector: None, + } + } + + /// Create and sign a vote for an assertion. + /// + /// The agent signs the assertion_hash to prove authenticity. + pub fn vote(&self, assertion_hash: Hash, weight: f32) -> Vote { + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + + // Sign the assertion hash to prove we're voting on this specific assertion + let signature: Signature = self.signing_key.sign(&assertion_hash); + + Vote { + assertion_hash, + agent_id: self.verifying_key.to_bytes(), + weight, + signature: signature.to_bytes(), + timestamp, + } + } +} + +// ============================================================================ +// Helper Functions +// ============================================================================ + +/// Result from writing to WAL, includes the raw bytes and the journal offset after the write. +struct WalWriteResult { + raw_bytes: Vec, + /// The journal offset AFTER this write (use this as target for wait_until_ingested) + end_offset: u64, +} + +/// Write an assertion to the WAL and track it for verification. +/// Returns the raw bytes and the journal offset after the write. +async fn write_assertion_to_wal( + journal: &Arc>, + assertion: &Assertion, +) -> Result { + // Serialize with header for WAL + let wal_bytes = + serialize_assertion(assertion).map_err(|e| format!("Failed to serialize: {}", e))?; + + // Serialize raw for hash computation + let raw_bytes = serialize(assertion).map_err(|e| format!("Failed to serialize raw: {}", e))?; + + // Write to WAL and get the offset after write + let mut journal_lock = journal.lock().await; + let end_offset = + journal_lock.append(wal_bytes).map_err(|e| format!("WAL write failed: {}", e))?; + + Ok(WalWriteResult { raw_bytes, end_offset }) +} + +/// Write a vote to the WAL. +/// +/// The vote flows through the full pipeline: WAL → IngestWorker → VoteStore, +/// which automatically updates vote count and aggregate weight caches. +/// Returns the journal offset after the write. +async fn write_vote_to_wal(journal: &Arc>, vote: &Vote) -> Result { + let wal_bytes = serialize_vote(vote).map_err(|e| format!("Failed to serialize vote: {}", e))?; + + let mut journal_lock = journal.lock().await; + let end_offset = + journal_lock.append(wal_bytes).map_err(|e| format!("WAL vote write failed: {}", e))?; + + Ok(end_offset) +} + +/// Compute the content-addressed hash of an assertion. +fn compute_assertion_hash(assertion: &Assertion) -> Hash { + let bytes = match serialize(assertion) { + Ok(b) => b, + Err(_) => return [0u8; 32], + }; + *blake3::hash(&bytes).as_bytes() +} + +/// The cursor key used by the ingestor to track its progress. +#[allow(dead_code)] +const CURSOR_KEY: &[u8] = b"__CURSOR__:ingest"; + +/// Wait until the ingestor cursor reaches or exceeds the target offset. +/// +/// This replaces hardcoded sleep timers with cursor-based polling, making +/// tests deterministic rather than timing-dependent. +/// +/// Polls every 10ms and times out after max_wait_ms milliseconds. +/// +/// # Arguments +/// * `store` - The KVStore to read the cursor from +/// * `target_offset` - The minimum cursor offset to wait for +/// * `max_wait_ms` - Maximum time to wait in milliseconds +/// +/// # Returns +/// * `Ok(())` if cursor reached target +/// * `Err(SimulationError)` if timeout exceeded +#[allow(dead_code)] +async fn wait_until_ingested( + store: &S, + target_offset: u64, + max_wait_ms: u64, +) -> Result<(), SimulationError> { + let start = Instant::now(); + let timeout = Duration::from_millis(max_wait_ms); + let poll_interval = Duration::from_millis(10); + + loop { + // Read current cursor position + if let Ok(Some(bytes)) = store.get(CURSOR_KEY).await { + if let Ok(arr) = <[u8; 8]>::try_from(bytes.as_slice()) { + let cursor = u64::from_le_bytes(arr); + if cursor >= target_offset { + debug!(cursor, target_offset, "Ingestion sync: cursor reached target"); + return Ok(()); + } + } + } + + // Check timeout + if start.elapsed() > timeout { + return Err(SimulationError { + tick: 0, + kind: ErrorKind::WriteFailure, + message: format!( + "Ingestion sync timeout: cursor did not reach {} within {}ms", + target_offset, max_wait_ms + ), + }); + } + + tokio::time::sleep(poll_interval).await; + } +} + +// ============================================================================ +// Core Simulation Function +// ============================================================================ + +/// Run the simulation with the given configuration. +/// +/// This is the primary entry point for the simulation. It: +/// 1. Sets up storage infrastructure (WAL + KV) +/// 2. Creates agents with cryptographic identities +/// 3. Runs assertion ticks (write to WAL) +/// 4. Waits for ingestion +/// 5. Verifies assertions via QueryEngine (Arena 1) +/// 6. Tests Recency Lens (Arena 1) +/// 7. Tests Lifecycle Filtering (Arena 1) +/// 8. Verifies Query Audit Trail (Arena 1) +/// +/// # Returns +/// +/// - `Ok(SimulationResult)` on completion (even with verification errors) +/// - `Err(SimulationSetupError)` if infrastructure setup fails +pub async fn run_simulation( + config: SimulationConfig, +) -> Result { + info!("🚀 Starting StemeDB Simulation: 'The Arena' (Phase 1: Query Path)"); + info!( + " Config: {} agents, {} ticks, {}ms ingestion wait", + config.agent_count, config.tick_count, config.ingestion_wait_ms + ); + + // 1. Setup Storage (WAL + KV) + let temp_wal_dir = + tempfile::tempdir().map_err(|e| SimulationSetupError::WalDirectory(e.to_string()))?; + let temp_db_dir = + tempfile::tempdir().map_err(|e| SimulationSetupError::StoreDirectory(e.to_string()))?; + + let journal = Arc::new(Mutex::new( + Journal::open(temp_wal_dir.path()) + .map_err(|e| SimulationSetupError::JournalOpen(e.to_string()))?, + )); + let store = Arc::new( + SledStore::open(temp_db_dir.path()) + .map_err(|e| SimulationSetupError::StoreOpen(e.to_string()))?, + ); + + debug!(" WAL initialized at {:?}", temp_wal_dir.path()); + debug!(" KV Store initialized at {:?}", temp_db_dir.path()); + + // 2. Start Ingestor + let mut ingestor = Ingestor::new(journal.clone(), store.clone()) + .await + .map_err(|e| SimulationSetupError::IngestorCreate(e.to_string()))?; + ingestor.start(); + debug!(" Ingestor started (background worker)."); + + // 3. Setup Agents + let agents: Vec = (0..config.agent_count) + .map(|i| { + let name = match i % 3 { + 0 => format!("Scientist_{}", i), + 1 => format!("Researcher_{}", i), + _ => format!("Troll_{}", i), + }; + Agent::new(&name) + }) + .collect(); + info!(" Swarm of {} agents instantiated.", agents.len()); + + // 4. Initialize Result + let mut result = SimulationResult { + assertions_written: 0, + assertions_verified: 0, + queries_executed: 0, + votes_written: 0, + recency_test_passed: false, + lifecycle_test_passed: false, + audit_test_passed: false, + vote_consensus_test_passed: false, + troll_resistance_test_passed: false, + errors: Vec::new(), + agent_count: config.agent_count, + tick_count: config.tick_count, + }; + + // 5. Run Simulation Ticks (Write Phase) + let mut assertions_data: Vec<(Assertion, Vec)> = Vec::with_capacity(config.tick_count); + let mut last_journal_offset = 0u64; + + for tick in 0..config.tick_count { + let agent = &agents[tick % agents.len()]; + let assertion = agent.sign_assertion( + &format!("Entity_{}", tick), + "has_property", + ObjectValue::Text(format!("Value_{}", tick)), + ); + + match write_assertion_to_wal(&journal, &assertion).await { + Ok(wal_result) => { + debug!(" [Tick {}] Agent '{}' wrote to WAL", tick, agent.id); + result.assertions_written += 1; + last_journal_offset = wal_result.end_offset; + assertions_data.push((assertion, wal_result.raw_bytes)); + } + Err(e) => { + result.errors.push(SimulationError { + tick: tick as u64, + kind: ErrorKind::WriteFailure, + message: e, + }); + } + } + } + + info!(" {} assertions written to WAL.", result.assertions_written); + + // 6. Wait for Ingestion (cursor-based sync) + info!("⏳ Waiting for ingestion to reach offset {}...", last_journal_offset); + if let Err(e) = + wait_until_ingested(&*store, last_journal_offset, config.ingestion_wait_ms).await + { + result.errors.push(e); + } + + // ======================================================================== + // ARENA 1: Query Path Verification + // ======================================================================== + + info!("🔬 Arena 1: Verifying Query Path..."); + + // 7. Create QueryEngine and verify assertions via queries + let engine = QueryEngine::new(store.clone()); + + for (i, (original_assertion, _original_bytes)) in assertions_data.iter().enumerate() { + let tick = i as u64; + + // Query via QueryEngine (not direct KV access) + let query = Query::builder() + .subject(&original_assertion.subject) + .predicate(&original_assertion.predicate) + .build(); + + match engine.execute(&query).await { + Ok(query_result) => { + result.queries_executed += 1; + + if query_result.assertions.is_empty() { + result.errors.push(SimulationError { + tick, + kind: ErrorKind::QueryFailure, + message: format!( + "Query returned no results for {}:{}", + original_assertion.subject, original_assertion.predicate + ), + }); + continue; + } + + // Verify content matches + let found = &query_result.assertions[0]; + if found.subject != original_assertion.subject + || found.object != original_assertion.object + { + result.errors.push(SimulationError { + tick, + kind: ErrorKind::StorageCorruption, + message: format!( + "Content mismatch: expected subject='{}', got='{}'", + original_assertion.subject, found.subject + ), + }); + continue; + } + + // Verify signature + let sig_entry = &found.signatures[0]; + let verifying_key = match VerifyingKey::from_bytes(&sig_entry.agent_id) { + Ok(k) => k, + Err(e) => { + result.errors.push(SimulationError { + tick, + kind: ErrorKind::SignatureInvalid, + message: format!("Invalid agent public key: {}", e), + }); + continue; + } + }; + let signature = Signature::from_bytes(&sig_entry.signature); + let message = format!("{}:{}", found.subject, found.predicate); + + if let Err(e) = verifying_key.verify(message.as_bytes(), &signature) { + result.errors.push(SimulationError { + tick, + kind: ErrorKind::SignatureInvalid, + message: format!("Signature verification failed: {}", e), + }); + continue; + } + + debug!( + " [Query {}] Assertion for '{}' verified via QueryEngine.", + i, found.subject + ); + result.assertions_verified += 1; + } + Err(e) => { + result.errors.push(SimulationError { + tick, + kind: ErrorKind::QueryFailure, + message: format!("Query execution failed: {}", e), + }); + } + } + } + + // ======================================================================== + // 8. Arena 1.2: Recency Lens Test + // ======================================================================== + info!("🔬 Arena 1.2: Testing Recency Lens..."); + result.recency_test_passed = + run_recency_lens_test(&journal, &store, &agents, &mut result).await; + + // ======================================================================== + // 9. Arena 1.3: Lifecycle Filtering Test + // ======================================================================== + info!("🔬 Arena 1.3: Testing Lifecycle Filtering..."); + result.lifecycle_test_passed = run_lifecycle_test(&journal, &store, &agents, &mut result).await; + + // Wait for these new assertions to be ingested + tokio::time::sleep(std::time::Duration::from_millis(config.ingestion_wait_ms)).await; + + // ======================================================================== + // 10. Arena 1.4: Query Audit Verification + // ======================================================================== + info!("🔬 Arena 1.4: Testing Query Audit Trail..."); + result.audit_test_passed = run_audit_test(&store, &agents, &mut result).await; + + // ======================================================================== + // ARENA 2: Voting & Consensus + // ======================================================================== + + info!("🗳️ Arena 2: Verifying Voting & Consensus..."); + + // ======================================================================== + // 11. Arena 2.2: Conflicting Assertions with Votes + // ======================================================================== + info!("🗳️ Arena 2.2: Testing Vote-Aware Consensus..."); + result.vote_consensus_test_passed = + run_vote_consensus_test(&journal, &store, &agents, &mut result).await; + + // Wait for votes to be ingested + tokio::time::sleep(std::time::Duration::from_millis(config.ingestion_wait_ms)).await; + + // ======================================================================== + // 12. Arena 2.3: Troll Vote Resistance + // ======================================================================== + info!("🗳️ Arena 2.3: Testing Troll Vote Resistance..."); + result.troll_resistance_test_passed = + run_troll_resistance_test(&journal, &store, &agents, &mut result).await; + + // Wait for final ingestion + tokio::time::sleep(std::time::Duration::from_millis(config.ingestion_wait_ms)).await; + + // 13. Log summary + if result.is_success() { + info!("{}", result.summary()); + } else { + warn!("{}", result.summary()); + for err in &result.errors { + warn!(" [Tick {}] {:?}: {}", err.tick, err.kind, err.message); + } + } + + Ok(result) +} + +// ============================================================================ +// Arena 1.2: Recency Lens Test +// ============================================================================ + +/// Test that RecencyLens correctly selects the most recent assertion. +/// +/// Creates two assertions for the same subject+predicate with different timestamps, +/// then verifies that the lens resolves to the newer one. +async fn run_recency_lens_test( + journal: &Arc>, + store: &Arc, + agents: &[Agent], + result: &mut SimulationResult, +) -> bool { + let agent = &agents[0]; + let subject = "RecencyTest_Entity"; + let predicate = "test_property"; + + // Create older assertion (timestamp = 1000) + let old_assertion = agent.sign_assertion_with_options( + subject, + predicate, + ObjectValue::Text("old_value".to_string()), + LifecycleStage::Proposed, + Some(1000), + ); + + // Create newer assertion (timestamp = 2000) + let new_assertion = agent.sign_assertion_with_options( + subject, + predicate, + ObjectValue::Text("new_value".to_string()), + LifecycleStage::Proposed, + Some(2000), + ); + + // Write both to WAL + if let Err(e) = write_assertion_to_wal(journal, &old_assertion).await { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::WriteFailure, + message: format!("Recency test: failed to write old assertion: {}", e), + }); + return false; + } + + if let Err(e) = write_assertion_to_wal(journal, &new_assertion).await { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::WriteFailure, + message: format!("Recency test: failed to write new assertion: {}", e), + }); + return false; + } + + // Wait for ingestion + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + + // Query to get candidates + let engine = QueryEngine::new(store.clone()); + let query = Query::builder().subject(subject).predicate(predicate).build(); + + let query_result = match engine.execute(&query).await { + Ok(r) => r, + Err(e) => { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::QueryFailure, + message: format!("Recency test: query failed: {}", e), + }); + return false; + } + }; + + if query_result.assertions.len() < 2 { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::QueryFailure, + message: format!( + "Recency test: expected 2 assertions, got {}", + query_result.assertions.len() + ), + }); + return false; + } + + // Apply RecencyLens + let lens = RecencyLens; + let resolution = lens.resolve(&query_result.assertions); + + match resolution.winner { + Some(winner) => { + // Winner should be the newer assertion (timestamp = 2000) + if winner.timestamp == 2000 { + if let ObjectValue::Text(ref value) = winner.object { + if value == "new_value" { + debug!(" Recency lens correctly selected newest assertion"); + result.queries_executed += 1; + return true; + } + } + } + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::LensResolutionFailure, + message: format!( + "Recency test: wrong winner selected (timestamp={}, expected 2000)", + winner.timestamp + ), + }); + false + } + None => { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::LensResolutionFailure, + message: "Recency test: lens returned no winner".to_string(), + }); + false + } + } +} + +// ============================================================================ +// Arena 1.3: Lifecycle Filtering Test +// ============================================================================ + +/// Test that lifecycle filtering correctly filters assertions. +/// +/// Creates a Proposed and an Approved assertion for the same subject+predicate, +/// then verifies that querying with lifecycle=Approved returns only the Approved one. +async fn run_lifecycle_test( + journal: &Arc>, + store: &Arc, + agents: &[Agent], + result: &mut SimulationResult, +) -> bool { + let agent = &agents[0]; + let subject = "LifecycleTest_Entity"; + let predicate = "jwt_algorithm"; + + // Proposed assertion (the bug - using RS256) + let proposed = agent.sign_assertion_with_options( + subject, + predicate, + ObjectValue::Text("RS256".to_string()), + LifecycleStage::Proposed, + Some(1000), + ); + + // Approved assertion (the fix - using ES256) + let approved = agent.sign_assertion_with_options( + subject, + predicate, + ObjectValue::Text("ES256".to_string()), + LifecycleStage::Approved, + Some(2000), + ); + + // Write both to WAL + if let Err(e) = write_assertion_to_wal(journal, &proposed).await { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::WriteFailure, + message: format!("Lifecycle test: failed to write proposed: {}", e), + }); + return false; + } + + if let Err(e) = write_assertion_to_wal(journal, &approved).await { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::WriteFailure, + message: format!("Lifecycle test: failed to write approved: {}", e), + }); + return false; + } + + // Wait for ingestion + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + + // Query with lifecycle filter + let engine = QueryEngine::new(store.clone()); + let query = Query::builder() + .subject(subject) + .predicate(predicate) + .lifecycle(LifecycleStage::Approved) + .build(); + + let query_result = match engine.execute(&query).await { + Ok(r) => r, + Err(e) => { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::QueryFailure, + message: format!("Lifecycle test: query failed: {}", e), + }); + return false; + } + }; + + // Should return exactly 1 assertion (the Approved one) + if query_result.assertions.len() != 1 { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::QueryFailure, + message: format!( + "Lifecycle test: expected 1 Approved assertion, got {}", + query_result.assertions.len() + ), + }); + return false; + } + + let found = &query_result.assertions[0]; + if found.lifecycle != LifecycleStage::Approved { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::QueryFailure, + message: format!("Lifecycle test: expected Approved, got {:?}", found.lifecycle), + }); + return false; + } + + // Verify it's the ES256 value (the fix) + if let ObjectValue::Text(ref value) = found.object { + if value == "ES256" { + debug!(" Lifecycle filter correctly returned only Approved assertion (ES256)"); + result.queries_executed += 1; + return true; + } + } + + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::QueryFailure, + message: "Lifecycle test: wrong object value returned".to_string(), + }); + false +} + +// ============================================================================ +// Arena 1.4: Query Audit Verification +// ============================================================================ + +/// Test that query audits are correctly stored and retrievable. +/// +/// Creates a query audit with an agent ID, stores it, then verifies it can be +/// retrieved via `get_audits_for_agent()`. +async fn run_audit_test( + store: &Arc, + agents: &[Agent], + result: &mut SimulationResult, +) -> bool { + let audit_store = GenericAuditStore::new(store.clone()); + let agent = &agents[0]; + let agent_id = agent.public_key(); + + // Create a query audit + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + + let query_id: QueryId = *blake3::hash(b"test_query").as_bytes(); + + let audit = QueryAudit { + query_id, + agent_id: Some(agent_id), + timestamp, + params: QueryParams { + subject: Some("AuditTest_Entity".to_string()), + predicate: Some("test_property".to_string()), + lifecycle: Some(LifecycleStage::Approved), + epoch: None, + lens: Some("Recency".to_string()), + }, + result_hash: Some([1u8; 32]), + result_confidence: 0.95, + contributing_assertions: vec![ContributingAssertion { + assertion_hash: [2u8; 32], + weight: 1.0, + source_hash: [3u8; 32], + lifecycle: LifecycleStage::Approved, + }], + }; + + // Store the audit + if let Err(e) = audit_store.put_audit(&audit).await { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::AuditFailure, + message: format!("Audit test: failed to store audit: {}", e), + }); + return false; + } + + // Retrieve audits for this agent + let audits = match audit_store.get_audits_for_agent(&agent_id, 0, None, 10).await { + Ok(a) => a, + Err(e) => { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::AuditFailure, + message: format!("Audit test: failed to retrieve audits: {}", e), + }); + return false; + } + }; + + // Verify we got our audit back + if audits.is_empty() { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::AuditFailure, + message: "Audit test: no audits found for agent".to_string(), + }); + return false; + } + + let found = &audits[0]; + if found.query_id != query_id { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::AuditFailure, + message: "Audit test: query_id mismatch".to_string(), + }); + return false; + } + + if found.agent_id != Some(agent_id) { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::AuditFailure, + message: "Audit test: agent_id mismatch".to_string(), + }); + return false; + } + + // Verify contributing assertions + if found.contributing_assertions.len() != 1 { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::AuditFailure, + message: format!( + "Audit test: expected 1 contributing assertion, got {}", + found.contributing_assertions.len() + ), + }); + return false; + } + + debug!(" Audit trail correctly stored and retrieved for agent"); + true +} + +// ============================================================================ +// Arena 2.2: Vote-Aware Consensus Test +// ============================================================================ + +/// Test that VoteAwareConsensusLens correctly selects the assertion with most votes. +/// +/// Scenario: +/// - Scientist_Alpha asserts "Protein_X binds Receptor_Y" (confidence 0.8) +/// - Scientist_Beta asserts "Protein_X binds Receptor_Z" (confidence 0.8) +/// - Alpha votes for own assertion (weight 1.0) +/// - Beta votes for own assertion (weight 1.0) +/// - Believer (third agent) votes for Alpha's assertion +/// - Query with VoteAwareConsensusLens +/// - Verify Alpha's assertion wins (2 votes vs 1) +async fn run_vote_consensus_test( + journal: &Arc>, + store: &Arc, + agents: &[Agent], + result: &mut SimulationResult, +) -> bool { + // Need at least 3 agents: Alpha, Beta, Believer + if agents.len() < 3 { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::VoteConsensusFailure, + message: "Vote consensus test: need at least 3 agents".to_string(), + }); + return false; + } + + let alpha = &agents[0]; + let beta = &agents[1]; + let believer = &agents[2]; + + let subject = "Protein_X"; + let predicate = "binds"; + + // Alpha's assertion: Protein_X binds Receptor_Y + let alpha_assertion = alpha.sign_assertion_with_options( + subject, + predicate, + ObjectValue::Text("Receptor_Y".to_string()), + LifecycleStage::Proposed, + Some(1000), + ); + + // Beta's conflicting assertion: Protein_X binds Receptor_Z + let beta_assertion = beta.sign_assertion_with_options( + subject, + predicate, + ObjectValue::Text("Receptor_Z".to_string()), + LifecycleStage::Proposed, + Some(1001), + ); + + // Write both assertions to WAL + if let Err(e) = write_assertion_to_wal(journal, &alpha_assertion).await { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::WriteFailure, + message: format!("Vote consensus test: failed to write Alpha assertion: {}", e), + }); + return false; + } + result.assertions_written += 1; + + if let Err(e) = write_assertion_to_wal(journal, &beta_assertion).await { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::WriteFailure, + message: format!("Vote consensus test: failed to write Beta assertion: {}", e), + }); + return false; + } + result.assertions_written += 1; + + // Wait for assertions to be ingested + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + + // Compute assertion hashes + let alpha_hash = compute_assertion_hash(&alpha_assertion); + let beta_hash = compute_assertion_hash(&beta_assertion); + + // Alpha votes for own assertion (weight 1.0) + let alpha_vote = alpha.vote(alpha_hash, 1.0); + if let Err(e) = write_vote_to_wal(journal, &alpha_vote).await { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::VoteWriteFailure, + message: format!("Vote consensus test: failed to write Alpha vote: {}", e), + }); + return false; + } + result.votes_written += 1; + + // Beta votes for own assertion (weight 1.0) + let beta_vote = beta.vote(beta_hash, 1.0); + if let Err(e) = write_vote_to_wal(journal, &beta_vote).await { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::VoteWriteFailure, + message: format!("Vote consensus test: failed to write Beta vote: {}", e), + }); + return false; + } + result.votes_written += 1; + + // Believer votes for Alpha's assertion (weight 1.0) - this tips the balance + let believer_vote = believer.vote(alpha_hash, 1.0); + if let Err(e) = write_vote_to_wal(journal, &believer_vote).await { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::VoteWriteFailure, + message: format!("Vote consensus test: failed to write Believer vote: {}", e), + }); + return false; + } + result.votes_written += 1; + + // Wait for votes to be ingested (IngestWorker now uses VoteStore.put_vote()) + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + + // Query to get candidates + let engine = QueryEngine::new(store.clone()); + let query = Query::builder().subject(subject).predicate(predicate).build(); + + let query_result = match engine.execute(&query).await { + Ok(r) => r, + Err(e) => { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::QueryFailure, + message: format!("Vote consensus test: query failed: {}", e), + }); + return false; + } + }; + + if query_result.assertions.len() < 2 { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::QueryFailure, + message: format!( + "Vote consensus test: expected 2 assertions, got {}", + query_result.assertions.len() + ), + }); + return false; + } + + // Apply VoteAwareConsensusLens + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let lens = VoteAwareConsensusLens::new(vote_store); + let resolution = lens.resolve_async(&query_result.assertions).await; + + match resolution.winner { + Some(winner) => { + // Winner should be Alpha's assertion (Receptor_Y) - it has 2 votes vs Beta's 1 + if let ObjectValue::Text(ref value) = winner.object { + if value == "Receptor_Y" { + debug!( + " Vote-aware consensus correctly selected Alpha's assertion (2 votes vs 1)" + ); + result.queries_executed += 1; + return true; + } + } + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::VoteConsensusFailure, + message: format!( + "Vote consensus test: wrong winner selected (expected Receptor_Y, got {:?})", + winner.object + ), + }); + false + } + None => { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::VoteConsensusFailure, + message: "Vote consensus test: lens returned no winner".to_string(), + }); + false + } + } +} + +// ============================================================================ +// Arena 2.3: Troll Vote Resistance Test +// ============================================================================ + +/// Test that trolls cannot overturn consensus with self-votes. +/// +/// Scenario: +/// - Scientist asserts high-confidence fact about Entity_X +/// - Scientist votes for own assertion +/// - Troll creates low-confidence contradicting assertion +/// - Troll votes for own assertion +/// - Another scientist (ally) also votes for Scientist's assertion +/// - Verify Scientist's assertion still wins despite Troll vote +async fn run_troll_resistance_test( + journal: &Arc>, + store: &Arc, + agents: &[Agent], + result: &mut SimulationResult, +) -> bool { + // Need at least 3 agents: Scientist, Troll, Ally + if agents.len() < 3 { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::VoteConsensusFailure, + message: "Troll resistance test: need at least 3 agents".to_string(), + }); + return false; + } + + let scientist = &agents[0]; + let troll = &agents[1]; + let ally = &agents[2]; + + let subject = "Entity_X"; + let predicate = "property"; + + // Scientist's high-confidence assertion + let scientist_assertion = scientist.sign_assertion_with_options( + subject, + predicate, + ObjectValue::Text("verified_value".to_string()), + LifecycleStage::Proposed, + Some(2000), + ); + + // Troll's low-confidence contradicting assertion + let troll_assertion = troll.sign_assertion_with_options( + subject, + predicate, + ObjectValue::Text("fake_value".to_string()), + LifecycleStage::Proposed, + Some(2001), + ); + + // Write both assertions to WAL + if let Err(e) = write_assertion_to_wal(journal, &scientist_assertion).await { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::WriteFailure, + message: format!("Troll resistance test: failed to write scientist assertion: {}", e), + }); + return false; + } + result.assertions_written += 1; + + if let Err(e) = write_assertion_to_wal(journal, &troll_assertion).await { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::WriteFailure, + message: format!("Troll resistance test: failed to write troll assertion: {}", e), + }); + return false; + } + result.assertions_written += 1; + + // Wait for assertions to be ingested + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + + // Compute assertion hashes + let scientist_hash = compute_assertion_hash(&scientist_assertion); + let troll_hash = compute_assertion_hash(&troll_assertion); + + // Scientist votes for own assertion (weight 1.0) + let scientist_vote = scientist.vote(scientist_hash, 1.0); + if let Err(e) = write_vote_to_wal(journal, &scientist_vote).await { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::VoteWriteFailure, + message: format!("Troll resistance test: failed to write scientist vote: {}", e), + }); + return false; + } + result.votes_written += 1; + + // Troll votes for own assertion (weight 1.0) + let troll_vote = troll.vote(troll_hash, 1.0); + if let Err(e) = write_vote_to_wal(journal, &troll_vote).await { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::VoteWriteFailure, + message: format!("Troll resistance test: failed to write troll vote: {}", e), + }); + return false; + } + result.votes_written += 1; + + // Ally votes for scientist's assertion (weight 1.0) - tips balance in scientist's favor + let ally_vote = ally.vote(scientist_hash, 1.0); + if let Err(e) = write_vote_to_wal(journal, &ally_vote).await { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::VoteWriteFailure, + message: format!("Troll resistance test: failed to write ally vote: {}", e), + }); + return false; + } + result.votes_written += 1; + + // Wait for votes to be ingested (IngestWorker now uses VoteStore.put_vote()) + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + + // Query to get candidates + let engine = QueryEngine::new(store.clone()); + let query = Query::builder().subject(subject).predicate(predicate).build(); + + let query_result = match engine.execute(&query).await { + Ok(r) => r, + Err(e) => { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::QueryFailure, + message: format!("Troll resistance test: query failed: {}", e), + }); + return false; + } + }; + + if query_result.assertions.len() < 2 { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::QueryFailure, + message: format!( + "Troll resistance test: expected 2 assertions, got {}", + query_result.assertions.len() + ), + }); + return false; + } + + // Apply VoteAwareConsensusLens + let vote_store = Arc::new(GenericVoteStore::new(store.clone())); + let lens = VoteAwareConsensusLens::new(vote_store); + let resolution = lens.resolve_async(&query_result.assertions).await; + + match resolution.winner { + Some(winner) => { + // Winner should be scientist's assertion (verified_value) - it has 2 votes vs troll's 1 + if let ObjectValue::Text(ref value) = winner.object { + if value == "verified_value" { + debug!(" Troll resistance: consensus correctly resisted troll (2 votes vs 1)"); + result.queries_executed += 1; + return true; + } + } + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::VoteConsensusFailure, + message: format!( + "Troll resistance test: troll won! (expected verified_value, got {:?})", + winner.object + ), + }); + false + } + None => { + result.errors.push(SimulationError { + tick: 0, + kind: ErrorKind::VoteConsensusFailure, + message: "Troll resistance test: lens returned no winner".to_string(), + }); + false + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn test_simulation_default_config_succeeds() { + let config = SimulationConfig::default(); + let result = run_simulation(config).await.expect("Simulation should not fail setup"); + + assert!(result.is_success(), "Simulation should succeed: {:?}", result.errors); + // Arena 0 + Arena 2 assertions: 10 base + 2 (vote consensus) + 2 (troll resistance) + assert_eq!(result.assertions_written, 14); + assert_eq!(result.assertions_verified, 10); + // Arena 2 votes: 3 (vote consensus) + 3 (troll resistance) + assert_eq!(result.votes_written, 6); + assert!(result.recency_test_passed, "Recency test should pass"); + assert!(result.lifecycle_test_passed, "Lifecycle test should pass"); + assert!(result.audit_test_passed, "Audit test should pass"); + assert!(result.vote_consensus_test_passed, "Vote consensus test should pass"); + assert!(result.troll_resistance_test_passed, "Troll resistance test should pass"); + } + + #[tokio::test] + async fn test_simulation_custom_config() { + let config = SimulationConfig { agent_count: 5, tick_count: 20, ingestion_wait_ms: 600 }; + let result = run_simulation(config).await.expect("Simulation should not fail setup"); + + assert!(result.is_success()); + // 20 base + 2 (vote consensus) + 2 (troll resistance) + assert_eq!(result.assertions_written, 24); + assert_eq!(result.assertions_verified, 20); + assert_eq!(result.votes_written, 6); + assert_eq!(result.agent_count, 5); + assert_eq!(result.tick_count, 20); + } + + #[tokio::test] + async fn test_simulation_result_summary() { + let success = SimulationResult { + assertions_written: 10, + assertions_verified: 10, + queries_executed: 12, + votes_written: 6, + recency_test_passed: true, + lifecycle_test_passed: true, + audit_test_passed: true, + vote_consensus_test_passed: true, + troll_resistance_test_passed: true, + errors: vec![], + agent_count: 3, + tick_count: 10, + }; + assert!(success.summary().contains("✅")); + assert!(success.summary().contains("recency=✓")); + assert!(success.summary().contains("lifecycle=✓")); + assert!(success.summary().contains("audit=✓")); + assert!(success.summary().contains("vote_consensus=✓")); + assert!(success.summary().contains("troll_resist=✓")); + + let failure = SimulationResult { + assertions_written: 10, + assertions_verified: 8, + queries_executed: 10, + votes_written: 6, + recency_test_passed: false, + lifecycle_test_passed: true, + audit_test_passed: true, + vote_consensus_test_passed: true, + troll_resistance_test_passed: false, + errors: vec![SimulationError { + tick: 5, + kind: ErrorKind::VerificationFailure, + message: "Test error".to_string(), + }], + agent_count: 3, + tick_count: 10, + }; + assert!(failure.summary().contains("❌")); + assert!(failure.summary().contains("recency=✗")); + assert!(failure.summary().contains("troll_resist=✗")); + } +} diff --git a/crates/stemedb-sim/src/main.rs b/crates/stemedb-sim/src/main.rs index 48546e0..374be0d 100644 --- a/crates/stemedb-sim/src/main.rs +++ b/crates/stemedb-sim/src/main.rs @@ -1,166 +1,53 @@ -//! StemeDB Spine Simulator +//! StemeDB Spine Simulator Binary //! -//! This simulation validates the "Spine" (Durability + Schema + Ingestion) by simulating +// CLI binaries use println! for user-facing output (not tracing) +#![allow(clippy::print_stdout, clippy::print_stderr)] +//! +//! This binary validates the "Spine" (Durability + Schema + Ingestion) by simulating //! multiple agents creating, signing, and writing assertions to the WAL, which are then //! asynchronously ingested into the Storage Engine. +//! +//! # Usage +//! +//! ```bash +//! cargo run --bin stemedb-sim +//! ``` +//! +//! # Exit Codes +//! +//! - 0: Simulation completed successfully +//! - 1: Simulation completed with verification errors +//! - 2: Simulation setup failed (fatal error) -use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; -use rand::rngs::OsRng; -use rkyv::ser::serializers::AllocSerializer; -use rkyv::ser::Serializer; -use rkyv::Deserialize; -use std::sync::Arc; -use stemedb_core::types::{Assertion, ObjectValue, SignatureEntry}; -use stemedb_ingest::Ingestor; -use stemedb_storage::{KVStore, SledStore}; -use stemedb_wal::Journal; -use tokio::sync::Mutex; -use tracing::info; - -/// A simulated agent with a cryptographic identity. -struct Agent { - pub id: String, - signing_key: SigningKey, - verifying_key: VerifyingKey, -} - -impl Agent { - pub fn new(id: &str) -> Self { - let mut csprng = OsRng; - let signing_key = SigningKey::generate(&mut csprng); - let verifying_key = VerifyingKey::from(&signing_key); - Self { id: id.to_string(), signing_key, verifying_key } - } - - /// Create and sign an assertion. - pub fn sign_assertion(&self, subject: &str, predicate: &str, object: ObjectValue) -> Assertion { - let timestamp = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_secs()) - .unwrap_or(0); - - // For simulation, we sign the concatenation of subject and predicate - // In a real system, we'd sign the hash of the fact data. - let message = format!("{}:{}", subject, predicate); - let signature: Signature = self.signing_key.sign(message.as_bytes()); - - Assertion { - subject: subject.to_string(), - predicate: predicate.to_string(), - object, - parent_hash: None, - source_hash: [0u8; 32], - visual_hash: None, - epoch: None, - signatures: vec![SignatureEntry { - agent_id: self.verifying_key.to_bytes(), - signature: signature.to_bytes(), - timestamp, - }], - confidence: 1.0, - timestamp, - vector: None, - } - } -} +use std::process::ExitCode; +use stemedb_sim::{run_simulation, SimulationConfig}; #[tokio::main] -async fn main() -> Result<(), Box> { +async fn main() -> ExitCode { + // Initialize tracing tracing_subscriber::fmt::init(); - info!("🚀 Starting StemeDB Spine Simulation: 'The Arena'"); + // Run with default configuration + let config = SimulationConfig::default(); - // 1. Setup Storage (WAL + KV) - let temp_wal_dir = tempfile::tempdir()?; - let temp_db_dir = tempfile::tempdir()?; + match run_simulation(config).await { + Ok(result) => { + println!("\n{}", result.summary()); - let journal = Arc::new(Mutex::new(Journal::open(temp_wal_dir.path())?)); - let store = Arc::new(SledStore::open(temp_db_dir.path())?); - - info!(" WAL initialized at {:?}", temp_wal_dir.path()); - info!(" KV Store initialized at {:?}", temp_db_dir.path()); - - // 2. Start Ingestor - let mut ingestor = Ingestor::new(journal.clone(), store.clone()); - ingestor.start(); - info!(" Ingestor started (background worker)."); - - // 3. Setup Agents - let agents = vec![ - Agent::new("Scientist_Alpha"), - Agent::new("Scientist_Beta"), - Agent::new("Troll_Prime"), - ]; - info!(" Swarm of {} agents instantiated.", agents.len()); - - // 4. Run Simulation Ticks - let mut assertions = Vec::new(); - - for i in 0..10 { - let agent = &agents[i % agents.len()]; - let assertion = agent.sign_assertion( - &format!("Entity_{}", i), - "has_property", - ObjectValue::Text(format!("Value_{}", i)), - ); - - // Serialize the assertion - let mut serializer = AllocSerializer::<4096>::default(); - serializer.serialize_value(&assertion)?; - let bytes = serializer.into_serializer().into_inner(); - - // Write to WAL (Fast Path) - { - let mut journal_lock = journal.lock().await; - let offset = journal_lock.append(bytes.to_vec())?; - info!(" [Tick {}] Agent '{}' wrote to WAL at offset {}", i, agent.id, offset); + if result.is_success() { + println!("\n🎉 The Arena: Spine validation PASSED."); + ExitCode::SUCCESS + } else { + println!("\n💥 The Arena: Spine validation FAILED."); + for err in &result.errors { + println!(" [Tick {}] {:?}: {}", err.tick, err.kind, err.message); + } + ExitCode::from(1) + } + } + Err(e) => { + eprintln!("\n🔥 Fatal setup error: {}", e); + ExitCode::from(2) } - - assertions.push(assertion); } - - // 5. Wait for Ingestion (Eventual Consistency) - info!("⏳ Waiting for ingestion to catch up..."); - // In a real test we'd poll or use channels, but for sim we just wait a bit - tokio::time::sleep(std::time::Duration::from_millis(500)).await; - - // 6. Verify the Store (Query Path) - info!("🔬 Verifying Storage integrity..."); - - for (i, original_assertion) in assertions.iter().enumerate() { - // Construct the key used by the ingestor: H:{Subject}:{Predicate} - let key = format!("H:{}:{}", original_assertion.subject, original_assertion.predicate) - .into_bytes(); - - // Read from KV Store - let stored_bytes = - store.get(&key).await?.ok_or_else(|| format!("Assertion {} not found in store!", i))?; - - // Deserialize and validate - let archived = rkyv::check_archived_root::(&stored_bytes) - .map_err(|e| format!("Stored Record is corrupt or invalid: {:?}", e))?; - - let deserialized: Assertion = archived.deserialize(&mut rkyv::Infallible)?; - - // Verify consistency - assert_eq!(original_assertion.subject, deserialized.subject); - assert_eq!(original_assertion.object, deserialized.object); - - // Verify signature - let sig_entry = &deserialized.signatures[0]; - let verifying_key = VerifyingKey::from_bytes(&sig_entry.agent_id)?; - let signature = Signature::from_bytes(&sig_entry.signature); - - let message = format!("{}:{}", deserialized.subject, deserialized.predicate); - verifying_key.verify(message.as_bytes(), &signature)?; - - info!( - " [Verify {}] Assertion for '{}' retrieved from KV Store and verified.", - i, deserialized.subject - ); - } - - info!("✅ Simulation 'The Arena' completed successfully. Spine is robust."); - - Ok(()) } diff --git a/crates/stemedb-sim/tests/smoke.rs b/crates/stemedb-sim/tests/smoke.rs new file mode 100644 index 0000000..c1336a6 --- /dev/null +++ b/crates/stemedb-sim/tests/smoke.rs @@ -0,0 +1,301 @@ +//! Smoke tests for the StemeDB simulation. +//! +//! These tests validate that the simulation infrastructure works correctly +//! and can be run in CI. They exercise the core simulation loop and verify +//! that the Spine (WAL + Ingestor + KV Store), Cortex (Query + Lenses), +//! and Ballot Box (Votes + VoteAwareConsensusLens) correctly process data. + +use stemedb_sim::{run_simulation, ErrorKind, SimulationConfig, SimulationResult}; + +/// Verify the default simulation configuration succeeds. +/// +/// This is the primary smoke test - if this passes, Spine, Cortex, and Ballot Box are working. +#[tokio::test] +async fn smoke_default_simulation_succeeds() { + let config = SimulationConfig::default(); + let result = run_simulation(config).await.expect("Simulation setup should not fail"); + + assert!(result.is_success(), "Default simulation should succeed. Errors: {:?}", result.errors); + // All Arena 1 tests should pass + assert!(result.recency_test_passed, "Recency lens test should pass"); + assert!(result.lifecycle_test_passed, "Lifecycle filtering test should pass"); + assert!(result.audit_test_passed, "Query audit test should pass"); + // All Arena 2 tests should pass + assert!(result.vote_consensus_test_passed, "Vote consensus test should pass"); + assert!(result.troll_resistance_test_passed, "Troll resistance test should pass"); + assert!(result.votes_written >= 6, "Should have written at least 6 votes"); +} + +/// Verify simulation works with increased load. +#[tokio::test] +async fn smoke_high_volume_simulation() { + let config = SimulationConfig { + agent_count: 10, + tick_count: 50, + ingestion_wait_ms: 1000, // More time for larger workload + }; + + let result = run_simulation(config).await.expect("Simulation setup should not fail"); + + assert!( + result.is_success(), + "High-volume simulation should succeed. Errors: {:?}", + result.errors + ); + // 50 base + 2 (vote consensus) + 2 (troll resistance) + assert_eq!(result.assertions_written, 54); + assert_eq!(result.assertions_verified, 50); + // All Arena 1 + 2 tests should pass + assert!(result.recency_test_passed); + assert!(result.lifecycle_test_passed); + assert!(result.audit_test_passed); + assert!(result.vote_consensus_test_passed); + assert!(result.troll_resistance_test_passed); +} + +/// Verify simulation result accessors work correctly. +#[test] +fn test_simulation_result_is_success() { + // Success case: all assertions verified, no errors, all tests pass + let success = SimulationResult { + assertions_written: 10, + assertions_verified: 10, + queries_executed: 12, + votes_written: 6, + recency_test_passed: true, + lifecycle_test_passed: true, + audit_test_passed: true, + vote_consensus_test_passed: true, + troll_resistance_test_passed: true, + errors: vec![], + agent_count: 3, + tick_count: 10, + }; + assert!(success.is_success()); + + // Note: mismatched assertions_written != assertions_verified is allowed + // because Arena 2 tests write additional test assertions. + let with_mismatch = SimulationResult { + assertions_written: 10, + assertions_verified: 8, + queries_executed: 10, + votes_written: 6, + recency_test_passed: true, + lifecycle_test_passed: true, + audit_test_passed: true, + vote_consensus_test_passed: true, + troll_resistance_test_passed: true, + errors: vec![], + agent_count: 3, + tick_count: 10, + }; + // This is now allowed - mismatched counts don't fail + assert!(with_mismatch.is_success()); + + // Failure case: has errors + let with_errors = SimulationResult { + assertions_written: 10, + assertions_verified: 10, + queries_executed: 12, + votes_written: 6, + recency_test_passed: true, + lifecycle_test_passed: true, + audit_test_passed: true, + vote_consensus_test_passed: true, + troll_resistance_test_passed: true, + errors: vec![stemedb_sim::SimulationError { + tick: 5, + kind: ErrorKind::VerificationFailure, + message: "Test error".to_string(), + }], + agent_count: 3, + tick_count: 10, + }; + assert!(!with_errors.is_success()); + + // Failure case: recency test failed + let recency_failed = SimulationResult { + assertions_written: 10, + assertions_verified: 10, + queries_executed: 12, + votes_written: 6, + recency_test_passed: false, + lifecycle_test_passed: true, + audit_test_passed: true, + vote_consensus_test_passed: true, + troll_resistance_test_passed: true, + errors: vec![], + agent_count: 3, + tick_count: 10, + }; + assert!(!recency_failed.is_success()); + + // Failure case: lifecycle test failed + let lifecycle_failed = SimulationResult { + assertions_written: 10, + assertions_verified: 10, + queries_executed: 12, + votes_written: 6, + recency_test_passed: true, + lifecycle_test_passed: false, + audit_test_passed: true, + vote_consensus_test_passed: true, + troll_resistance_test_passed: true, + errors: vec![], + agent_count: 3, + tick_count: 10, + }; + assert!(!lifecycle_failed.is_success()); + + // Failure case: audit test failed + let audit_failed = SimulationResult { + assertions_written: 10, + assertions_verified: 10, + queries_executed: 12, + votes_written: 6, + recency_test_passed: true, + lifecycle_test_passed: true, + audit_test_passed: false, + vote_consensus_test_passed: true, + troll_resistance_test_passed: true, + errors: vec![], + agent_count: 3, + tick_count: 10, + }; + assert!(!audit_failed.is_success()); + + // Failure case: vote consensus test failed + let vote_consensus_failed = SimulationResult { + assertions_written: 10, + assertions_verified: 10, + queries_executed: 12, + votes_written: 6, + recency_test_passed: true, + lifecycle_test_passed: true, + audit_test_passed: true, + vote_consensus_test_passed: false, + troll_resistance_test_passed: true, + errors: vec![], + agent_count: 3, + tick_count: 10, + }; + assert!(!vote_consensus_failed.is_success()); + + // Failure case: troll resistance test failed + let troll_resistance_failed = SimulationResult { + assertions_written: 10, + assertions_verified: 10, + queries_executed: 12, + votes_written: 6, + recency_test_passed: true, + lifecycle_test_passed: true, + audit_test_passed: true, + vote_consensus_test_passed: true, + troll_resistance_test_passed: false, + errors: vec![], + agent_count: 3, + tick_count: 10, + }; + assert!(!troll_resistance_failed.is_success()); +} + +/// Verify summary formatting. +#[test] +fn test_simulation_result_summary_format() { + let success = SimulationResult { + assertions_written: 10, + assertions_verified: 10, + queries_executed: 12, + votes_written: 6, + recency_test_passed: true, + lifecycle_test_passed: true, + audit_test_passed: true, + vote_consensus_test_passed: true, + troll_resistance_test_passed: true, + errors: vec![], + agent_count: 3, + tick_count: 10, + }; + let summary = success.summary(); + assert!(summary.contains("✅"), "Success should show checkmark"); + assert!(summary.contains("10"), "Should show assertion count"); + assert!(summary.contains("6"), "Should show vote count"); + assert!(summary.contains("recency=✓"), "Should show recency passed"); + assert!(summary.contains("lifecycle=✓"), "Should show lifecycle passed"); + assert!(summary.contains("audit=✓"), "Should show audit passed"); + assert!(summary.contains("vote_consensus=✓"), "Should show vote consensus passed"); + assert!(summary.contains("troll_resist=✓"), "Should show troll resistance passed"); + + let failure = SimulationResult { + assertions_written: 10, + assertions_verified: 8, + queries_executed: 10, + votes_written: 6, + recency_test_passed: false, + lifecycle_test_passed: true, + audit_test_passed: true, + vote_consensus_test_passed: true, + troll_resistance_test_passed: false, + errors: vec![stemedb_sim::SimulationError { + tick: 5, + kind: ErrorKind::VerificationFailure, + message: "Test".to_string(), + }], + agent_count: 3, + tick_count: 10, + }; + let summary = failure.summary(); + assert!(summary.contains("❌"), "Failure should show X"); + assert!(summary.contains("1 error"), "Should show error count"); + assert!(summary.contains("recency=✗"), "Should show recency failed"); + assert!(summary.contains("troll_resist=✗"), "Should show troll resistance failed"); +} + +/// Verify all error kinds are representable. +#[test] +fn test_error_kinds_are_complete() { + // This test documents all error kinds - if a new one is added, + // this test should be updated to cover it. + let kinds = [ + ErrorKind::WriteFailure, + ErrorKind::VerificationFailure, + ErrorKind::SignatureInvalid, + ErrorKind::StorageCorruption, + ErrorKind::SerializationFailure, + ErrorKind::QueryFailure, + ErrorKind::LensResolutionFailure, + ErrorKind::AuditFailure, + ErrorKind::VoteWriteFailure, + ErrorKind::VoteConsensusFailure, + ]; + + for kind in kinds { + let error = + stemedb_sim::SimulationError { tick: 0, kind, message: format!("{:?} test", kind) }; + // Verify Debug trait works + let debug_str = format!("{:?}", error); + assert!(!debug_str.is_empty()); + } +} + +/// Verify minimum viable configuration works. +/// Note: Minimal simulation requires at least 3 agents for voting tests. +#[tokio::test] +async fn smoke_minimal_simulation() { + let config = SimulationConfig { agent_count: 3, tick_count: 1, ingestion_wait_ms: 300 }; + + let result = run_simulation(config).await.expect("Simulation setup should not fail"); + + assert!(result.is_success(), "Minimal simulation should succeed: {:?}", result.errors); + // 1 base + 2 (vote consensus) + 2 (troll resistance) + assert_eq!(result.assertions_written, 5); + assert_eq!(result.assertions_verified, 1); + assert_eq!(result.agent_count, 3); + assert_eq!(result.tick_count, 1); + // All Arena 1 + 2 tests should pass + assert!(result.recency_test_passed); + assert!(result.lifecycle_test_passed); + assert!(result.audit_test_passed); + assert!(result.vote_consensus_test_passed); + assert!(result.troll_resistance_test_passed); +} diff --git a/crates/stemedb-storage/Cargo.toml b/crates/stemedb-storage/Cargo.toml index 4c122a7..6233410 100644 --- a/crates/stemedb-storage/Cargo.toml +++ b/crates/stemedb-storage/Cargo.toml @@ -14,6 +14,10 @@ sled = "0.34" thiserror = "1.0" tracing = "0.1" async-trait = "0.1" +blake3 = "1.5" +hex = "0.4" +rkyv = { version = "0.7", features = ["validation"] } [dev-dependencies] -tokio = { version = "1.36", features = ["macros", "rt"] } +tokio = { version = "1", features = ["macros", "rt"] } +tempfile = "3.10" diff --git a/crates/stemedb-storage/src/audit_store.rs b/crates/stemedb-storage/src/audit_store.rs new file mode 100644 index 0000000..b3b4ca5 --- /dev/null +++ b/crates/stemedb-storage/src/audit_store.rs @@ -0,0 +1,502 @@ +//! Query audit trail storage for incident investigation. +//! +//! Every query is logged with provenance to enable "Why did you think that?" +//! debugging. This is critical for SRE incident investigation and agent +//! decision auditing. +//! +//! # Storage Layout +//! +//! | Key Pattern | Value | Purpose | +//! |-------------|-------|---------| +//! | `AUD:{query_id}` | Serialized QueryAudit | Individual audit records | +//! | `AUDA:{agent_id}:{timestamp}:{query_id}` | Empty | Agent index for temporal queries | +//! +//! # Design Philosophy +//! +//! Following the "Deep Module" principle: +//! - Simple interface hiding complex indexing +//! - O(1) individual audit lookups +//! - Agent+time range queries via prefix scan +//! +//! All operations are append-only (audits are never modified or deleted). + +use crate::error::Result; +use crate::traits::KVStore; +use async_trait::async_trait; +use stemedb_core::types::{QueryAudit, QueryId}; +use tracing::{debug, instrument}; + +/// Key prefix for individual audit records. +const AUDIT_PREFIX: &[u8] = b"AUD:"; +/// Key prefix for agent-based temporal index. +#[allow(dead_code)] // Documented for reference; actual key construction uses format!() +const AGENT_AUDIT_PREFIX: &[u8] = b"AUDA:"; + +/// Specialized storage trait for query audit operations. +/// +/// This trait provides audit-specific operations on top of a generic KVStore, +/// enabling efficient audit logging and retrieval for incident investigation. +/// +/// # Example +/// +/// ```ignore +/// let audit_store = GenericAuditStore::new(kv_store); +/// +/// // Log a query audit +/// audit_store.put_audit(&audit).await?; +/// +/// // Retrieve a specific audit +/// let audit = audit_store.get_audit(&query_id).await?; +/// +/// // Find all audits for an agent in a time range +/// let audits = audit_store.get_audits_for_agent(&agent_id, from, to).await?; +/// ``` +#[async_trait] +pub trait AuditStore: Send + Sync { + /// Store a query audit record. + /// + /// This operation: + /// 1. Serializes the audit using rkyv + /// 2. Stores at `AUD:{query_id}` + /// 3. Creates agent index entry at `AUDA:{agent_id}:{timestamp}:{query_id}` + /// + /// # Returns + /// The query_id for reference. + async fn put_audit(&self, audit: &QueryAudit) -> Result; + + /// Get a specific audit record by its query ID. + /// + /// # Returns + /// The audit record if found, None otherwise. + async fn get_audit(&self, query_id: &QueryId) -> Result>; + + /// Get audit records for a specific agent within a time range. + /// + /// Uses the agent index for efficient temporal queries. + /// + /// # Arguments + /// * `agent_id` - The agent's public key + /// * `from_timestamp` - Start of time range (inclusive) + /// * `to_timestamp` - End of time range (inclusive), None for unbounded + /// * `limit` - Maximum number of records to return + /// + /// # Returns + /// Vector of audit records, sorted by timestamp ascending, capped at limit. + async fn get_audits_for_agent( + &self, + agent_id: &[u8; 32], + from_timestamp: u64, + to_timestamp: Option, + limit: usize, + ) -> Result>; + + /// List recent audit records across all agents. + /// + /// Scans all `AUD:` keys and returns the most recent audits. + /// + /// # Arguments + /// * `limit` - Maximum number of records to return + /// + /// # Returns + /// Vector of audit records, sorted by timestamp descending (most recent first). + async fn list_recent_audits(&self, limit: usize) -> Result>; + + /// Check if any audits exist for an agent. + async fn has_audits_for_agent(&self, agent_id: &[u8; 32]) -> Result; +} + +/// AuditStore implementation backed by a generic KVStore. +/// +/// This implementation maintains an agent index for efficient temporal queries. +pub struct GenericAuditStore { + store: S, +} + +impl GenericAuditStore { + /// Create a new AuditStore backed by the given KVStore. + pub fn new(store: S) -> Self { + Self { store } + } + + /// Construct the key for an individual audit record. + fn audit_key(query_id: &QueryId) -> Vec { + let mut key = AUDIT_PREFIX.to_vec(); + key.extend_from_slice(&hex::encode(query_id).into_bytes()); + key + } + + /// Construct the agent index key. + fn agent_index_key(agent_id: &[u8; 32], timestamp: u64, query_id: &QueryId) -> Vec { + // Format: AUDA:{agent_hex}:{timestamp_be}:{query_hex} + // Using big-endian timestamp for lexicographic ordering + let agent_hex = hex::encode(agent_id); + let timestamp_hex = format!("{:016x}", timestamp); // Zero-padded hex for sorting + let query_hex = hex::encode(query_id); + format!("AUDA:{}:{}:{}", agent_hex, timestamp_hex, query_hex).into_bytes() + } + + /// Construct the prefix for scanning an agent's audits from a timestamp. + #[allow(dead_code)] // Reserved for future optimized range queries + fn agent_scan_prefix(agent_id: &[u8; 32], from_timestamp: u64) -> Vec { + let agent_hex = hex::encode(agent_id); + let timestamp_hex = format!("{:016x}", from_timestamp); + format!("AUDA:{}:{}", agent_hex, timestamp_hex).into_bytes() + } + + /// Construct the prefix for scanning all audits for an agent. + fn agent_full_prefix(agent_id: &[u8; 32]) -> Vec { + let agent_hex = hex::encode(agent_id); + format!("AUDA:{}:", agent_hex).into_bytes() + } + + /// Serialize an audit using the canonical serde helpers. + fn serialize_audit(audit: &QueryAudit) -> Result> { + crate::serde_helpers::serialize(audit) + } + + /// Deserialize an audit using the canonical serde helpers. + fn deserialize_audit(data: &[u8]) -> Result { + crate::serde_helpers::deserialize(data) + } + + /// Extract query_id from an agent index key. + fn extract_query_id_from_key(key: &[u8]) -> Option { + // Key format: AUDA:{agent_hex}:{timestamp_hex}:{query_hex} + let key_str = std::str::from_utf8(key).ok()?; + let parts: Vec<&str> = key_str.split(':').collect(); + if parts.len() != 4 { + return None; + } + let query_hex = parts[3]; + let bytes = hex::decode(query_hex).ok()?; + if bytes.len() != 32 { + return None; + } + let mut query_id = [0u8; 32]; + query_id.copy_from_slice(&bytes); + Some(query_id) + } + + /// Extract timestamp from an agent index key. + fn extract_timestamp_from_key(key: &[u8]) -> Option { + let key_str = std::str::from_utf8(key).ok()?; + let parts: Vec<&str> = key_str.split(':').collect(); + if parts.len() != 4 { + return None; + } + u64::from_str_radix(parts[2], 16).ok() + } +} + +#[async_trait] +impl AuditStore for GenericAuditStore { + #[instrument(skip(self, audit), fields(query_id = %hex::encode(audit.query_id)))] + async fn put_audit(&self, audit: &QueryAudit) -> Result { + // Serialize the audit + let serialized = Self::serialize_audit(audit)?; + + // Store the audit record + let key = Self::audit_key(&audit.query_id); + self.store.put(&key, &serialized).await?; + + debug!( + query_id = %hex::encode(audit.query_id), + "Stored query audit" + ); + + // Create agent index entry if agent_id is present + if let Some(agent_id) = &audit.agent_id { + let index_key = Self::agent_index_key(agent_id, audit.timestamp, &audit.query_id); + // Store empty value - the key itself contains all the info + self.store.put(&index_key, &[]).await?; + debug!( + agent_id = %hex::encode(agent_id), + timestamp = audit.timestamp, + "Created agent audit index" + ); + } + + Ok(audit.query_id) + } + + #[instrument(skip(self), fields(query_id = %hex::encode(query_id)))] + async fn get_audit(&self, query_id: &QueryId) -> Result> { + let key = Self::audit_key(query_id); + match self.store.get(&key).await? { + Some(data) => { + let audit = Self::deserialize_audit(&data)?; + Ok(Some(audit)) + } + None => Ok(None), + } + } + + #[instrument(skip(self), fields(agent_id = %hex::encode(agent_id), from = from_timestamp, limit))] + async fn get_audits_for_agent( + &self, + agent_id: &[u8; 32], + from_timestamp: u64, + to_timestamp: Option, + limit: usize, + ) -> Result> { + // Scan the agent index + let prefix = Self::agent_full_prefix(agent_id); + let entries = self.store.scan_prefix(&prefix).await?; + + let mut audits = Vec::new(); + + for (key, _value) in entries { + // Extract timestamp and filter + let Some(timestamp) = Self::extract_timestamp_from_key(&key) else { + continue; + }; + + // Check time range + if timestamp < from_timestamp { + continue; + } + if let Some(to) = to_timestamp { + if timestamp > to { + continue; + } + } + + // Extract query_id and fetch the full audit + let Some(query_id) = Self::extract_query_id_from_key(&key) else { + continue; + }; + + if let Some(audit) = self.get_audit(&query_id).await? { + audits.push(audit); + // Early termination once we have enough (before sorting) + // Note: We collect more than limit to allow proper sorting + // A future optimization could use timestamp-ordered keys + if audits.len() >= limit * 2 { + break; + } + } + } + + // Sort by timestamp ascending + audits.sort_by_key(|a| a.timestamp); + + // Apply limit after sorting + audits.truncate(limit); + + debug!(count = audits.len(), "Retrieved audits for agent"); + Ok(audits) + } + + #[instrument(skip(self), fields(limit))] + async fn list_recent_audits(&self, limit: usize) -> Result> { + let entries = self.store.scan_prefix(AUDIT_PREFIX).await?; + + let mut audits = Vec::with_capacity(entries.len().min(limit)); + + for (_key, data) in entries { + match Self::deserialize_audit(&data) { + Ok(audit) => audits.push(audit), + Err(e) => { + debug!(error = %e, "Skipping malformed audit record"); + } + } + } + + // Sort by timestamp descending (most recent first) + audits.sort_by(|a, b| b.timestamp.cmp(&a.timestamp)); + + // Apply limit + audits.truncate(limit); + + debug!(count = audits.len(), "Listed recent audits"); + Ok(audits) + } + + #[instrument(skip(self), fields(agent_id = %hex::encode(agent_id)))] + async fn has_audits_for_agent(&self, agent_id: &[u8; 32]) -> Result { + let prefix = Self::agent_full_prefix(agent_id); + let entries = self.store.scan_prefix(&prefix).await?; + Ok(!entries.is_empty()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::SledStore; + use stemedb_core::types::{ContributingAssertion, LifecycleStage}; + + fn create_test_audit( + query_id: QueryId, + agent_id: Option<[u8; 32]>, + timestamp: u64, + ) -> QueryAudit { + QueryAudit { + query_id, + agent_id, + timestamp, + params: stemedb_core::types::QueryParams { + subject: Some("Tesla".to_string()), + predicate: Some("revenue".to_string()), + lifecycle: Some(LifecycleStage::Approved), + epoch: None, + lens: Some("Recency".to_string()), + }, + result_hash: Some([1u8; 32]), + result_confidence: 0.95, + contributing_assertions: vec![ContributingAssertion { + assertion_hash: [2u8; 32], + weight: 1.0, + source_hash: [3u8; 32], + lifecycle: LifecycleStage::Approved, + }], + } + } + + #[tokio::test] + async fn test_put_and_get_audit() { + let store = SledStore::open_temp().expect("Failed to create store"); + let audit_store = GenericAuditStore::new(store); + + let query_id = [10u8; 32]; + let agent_id = Some([1u8; 32]); + let audit = create_test_audit(query_id, agent_id, 1000); + + // Put audit + let returned_id = audit_store.put_audit(&audit).await.expect("Failed to put audit"); + assert_eq!(returned_id, query_id); + + // Get audit back + let retrieved = audit_store.get_audit(&query_id).await.expect("Failed to get audit"); + assert!(retrieved.is_some()); + + let retrieved_audit = retrieved.expect("Audit should exist"); + assert_eq!(retrieved_audit.query_id, query_id); + assert_eq!(retrieved_audit.agent_id, agent_id); + assert_eq!(retrieved_audit.timestamp, 1000); + assert!((retrieved_audit.result_confidence - 0.95).abs() < f32::EPSILON); + } + + #[tokio::test] + async fn test_get_audits_for_agent() { + let store = SledStore::open_temp().expect("Failed to create store"); + let audit_store = GenericAuditStore::new(store); + + let agent1 = [1u8; 32]; + let agent2 = [2u8; 32]; + + // Create audits for different agents and times + let audit1 = create_test_audit([10u8; 32], Some(agent1), 1000); + let audit2 = create_test_audit([11u8; 32], Some(agent1), 2000); + let audit3 = create_test_audit([12u8; 32], Some(agent1), 3000); + let audit4 = create_test_audit([13u8; 32], Some(agent2), 2500); + + audit_store.put_audit(&audit1).await.expect("put"); + audit_store.put_audit(&audit2).await.expect("put"); + audit_store.put_audit(&audit3).await.expect("put"); + audit_store.put_audit(&audit4).await.expect("put"); + + // Get all audits for agent1 + let agent1_audits = + audit_store.get_audits_for_agent(&agent1, 0, None, 100).await.expect("get"); + assert_eq!(agent1_audits.len(), 3); + + // Get audits for agent1 in time range + let agent1_range = + audit_store.get_audits_for_agent(&agent1, 1500, Some(2500), 100).await.expect("get"); + assert_eq!(agent1_range.len(), 1); + assert_eq!(agent1_range[0].timestamp, 2000); + + // Get audits for agent2 + let agent2_audits = + audit_store.get_audits_for_agent(&agent2, 0, None, 100).await.expect("get"); + assert_eq!(agent2_audits.len(), 1); + + // Test limit parameter + let limited = audit_store.get_audits_for_agent(&agent1, 0, None, 2).await.expect("get"); + assert_eq!(limited.len(), 2); + } + + #[tokio::test] + async fn test_list_recent_audits() { + let store = SledStore::open_temp().expect("Failed to create store"); + let audit_store = GenericAuditStore::new(store); + + // Create audits with different timestamps + for i in 0..5 { + let mut query_id = [0u8; 32]; + query_id[0] = i; + let audit = create_test_audit(query_id, Some([1u8; 32]), 1000 + (i as u64) * 100); + audit_store.put_audit(&audit).await.expect("put"); + } + + // List recent with limit + let recent = audit_store.list_recent_audits(3).await.expect("list"); + assert_eq!(recent.len(), 3); + + // Should be in descending timestamp order + assert_eq!(recent[0].timestamp, 1400); + assert_eq!(recent[1].timestamp, 1300); + assert_eq!(recent[2].timestamp, 1200); + } + + #[tokio::test] + async fn test_audit_without_agent() { + let store = SledStore::open_temp().expect("Failed to create store"); + let audit_store = GenericAuditStore::new(store); + + // Audit without agent_id (anonymous query) + let query_id = [20u8; 32]; + let audit = create_test_audit(query_id, None, 1000); + + audit_store.put_audit(&audit).await.expect("put"); + + // Should still be retrievable + let retrieved = audit_store.get_audit(&query_id).await.expect("get"); + assert!(retrieved.is_some()); + assert!(retrieved.expect("exists").agent_id.is_none()); + } + + #[tokio::test] + async fn test_has_audits_for_agent() { + let store = SledStore::open_temp().expect("Failed to create store"); + let audit_store = GenericAuditStore::new(store); + + let agent1 = [1u8; 32]; + let agent2 = [2u8; 32]; + + // No audits initially + assert!(!audit_store.has_audits_for_agent(&agent1).await.expect("has")); + assert!(!audit_store.has_audits_for_agent(&agent2).await.expect("has")); + + // Add audit for agent1 + let audit = create_test_audit([10u8; 32], Some(agent1), 1000); + audit_store.put_audit(&audit).await.expect("put"); + + // Now agent1 has audits, agent2 still doesn't + assert!(audit_store.has_audits_for_agent(&agent1).await.expect("has")); + assert!(!audit_store.has_audits_for_agent(&agent2).await.expect("has")); + } + + #[tokio::test] + async fn test_get_nonexistent_audit() { + let store = SledStore::open_temp().expect("Failed to create store"); + let audit_store = GenericAuditStore::new(store); + + let nonexistent = [99u8; 32]; + let result = audit_store.get_audit(&nonexistent).await.expect("get"); + + assert!(result.is_none(), "Should return None for nonexistent audit"); + } + + #[tokio::test] + async fn test_empty_agent_audits() { + let store = SledStore::open_temp().expect("Failed to create store"); + let audit_store = GenericAuditStore::new(store); + + let agent = [1u8; 32]; + let audits = audit_store.get_audits_for_agent(&agent, 0, None, 100).await.expect("get"); + + assert!(audits.is_empty(), "Should return empty vec for agent with no audits"); + } +} diff --git a/crates/stemedb-storage/src/index_store.rs b/crates/stemedb-storage/src/index_store.rs new file mode 100644 index 0000000..79559d5 --- /dev/null +++ b/crates/stemedb-storage/src/index_store.rs @@ -0,0 +1,387 @@ +//! Specialized storage for assertion indexes. +//! +//! Following the architecture spec, we maintain multiple indexes for efficient queries: +//! - `S:{subject}` - Subject-only index (list of assertion hashes) +//! - `SP:{subject}:{predicate}` - Compound subject+predicate index (list of assertion hashes) +//! +//! # Design Philosophy +//! +//! This module follows the "Deep Module" principle from Philosophy of Software Design: +//! - Simple interface hiding complex index management +//! - O(1) lookups when both subject and predicate are known +//! - Efficient append-only semantics (no overwrites) +//! +//! # Storage Layout +//! +//! | Key Pattern | Value | Purpose | +//! |-------------|-------|---------| +//! | `S:{subject}` | Vec (rkyv) | Subject adjacency index | +//! | `SP:{subject}:{predicate}` | Vec (rkyv) | Compound index for fast lookups | +//! +//! All operations are append-only and content-addressed. + +use crate::error::Result; +use crate::traits::KVStore; +use async_trait::async_trait; +use stemedb_core::types::Hash; +use tracing::{debug, instrument}; + +/// Key prefix for subject-only index. +const SUBJECT_PREFIX: &[u8] = b"S:"; + +/// Key prefix for compound subject+predicate index. +const SUBJECT_PREDICATE_PREFIX: &[u8] = b"SP:"; + +/// Specialized storage trait for assertion index operations. +/// +/// This trait provides index-specific operations on top of a generic KVStore, +/// enabling efficient assertion lookup by subject and/or predicate. +/// +/// # Example +/// +/// ```ignore +/// let index_store = GenericIndexStore::new(kv_store); +/// +/// // Add assertion to indexes +/// index_store.add_to_indexes("Tesla", "revenue", assertion_hash).await?; +/// +/// // Lookup by subject only +/// let hashes = index_store.get_by_subject("Tesla").await?; +/// +/// // Lookup by subject and predicate (faster) +/// let hashes = index_store.get_by_subject_predicate("Tesla", "revenue").await?; +/// ``` +#[async_trait] +pub trait IndexStore: Send + Sync { + /// Add an assertion hash to both subject and compound indexes. + /// + /// This operation: + /// 1. Appends hash to `S:{subject}` index + /// 2. Appends hash to `SP:{subject}:{predicate}` index + /// + /// # Arguments + /// * `subject` - The assertion subject + /// * `predicate` - The assertion predicate + /// * `assertion_hash` - The content-addressed hash of the assertion + async fn add_to_indexes( + &self, + subject: &str, + predicate: &str, + assertion_hash: &Hash, + ) -> Result<()>; + + /// Get all assertion hashes for a given subject. + /// + /// Reads from the `S:{subject}` index. + /// + /// # Returns + /// Vector of assertion hashes, empty if no assertions exist. + async fn get_by_subject(&self, subject: &str) -> Result>; + + /// Get all assertion hashes for a given subject and predicate. + /// + /// Reads from the `SP:{subject}:{predicate}` index. + /// This is more efficient than `get_by_subject` when the predicate is known. + /// + /// # Returns + /// Vector of assertion hashes, empty if no assertions exist. + async fn get_by_subject_predicate(&self, subject: &str, predicate: &str) -> Result>; + + /// Check if any assertions exist for a given subject. + async fn has_subject(&self, subject: &str) -> Result; + + /// Check if any assertions exist for a given subject and predicate. + async fn has_subject_predicate(&self, subject: &str, predicate: &str) -> Result; +} + +/// IndexStore implementation backed by a generic KVStore. +/// +/// This implementation stores indexes as rkyv-serialized Vec for efficient +/// zero-copy deserialization. +pub struct GenericIndexStore { + store: S, +} + +impl GenericIndexStore { + /// Create a new IndexStore backed by the given KVStore. + pub fn new(store: S) -> Self { + Self { store } + } + + /// Construct the key for the subject index. + fn subject_key(subject: &str) -> Vec { + let mut key = SUBJECT_PREFIX.to_vec(); + key.extend_from_slice(subject.as_bytes()); + key + } + + /// Construct the key for the compound subject+predicate index. + fn subject_predicate_key(subject: &str, predicate: &str) -> Vec { + let mut key = SUBJECT_PREDICATE_PREFIX.to_vec(); + key.extend_from_slice(subject.as_bytes()); + key.push(b':'); + key.extend_from_slice(predicate.as_bytes()); + key + } + + /// Serialize a hash list using the canonical serde helpers. + fn serialize_hash_list(hashes: &Vec) -> Result> { + crate::serde_helpers::serialize(hashes) + } + + /// Deserialize a hash list using the canonical serde helpers. + fn deserialize_hash_list(data: &[u8]) -> Result> { + crate::serde_helpers::deserialize(data) + } + + /// Append a hash to an index (read-modify-write). + /// + /// This is not lock-free, but is safe for the current use case where + /// ingestion is single-threaded per assertion. + async fn append_to_index(&self, key: Vec, new_hash: &Hash) -> Result<()> { + let mut hashes = match self.store.get(&key).await? { + Some(data) => Self::deserialize_hash_list(&data)?, + None => Vec::new(), + }; + + // Append only if not already present (idempotency) + if !hashes.contains(new_hash) { + hashes.push(*new_hash); + let serialized = Self::serialize_hash_list(&hashes)?; + self.store.put(&key, &serialized).await?; + } + + Ok(()) + } +} + +#[async_trait] +impl IndexStore for GenericIndexStore { + #[instrument(skip(self, assertion_hash), fields(subject = %subject, predicate = %predicate, hash = %hex::encode(assertion_hash)))] + async fn add_to_indexes( + &self, + subject: &str, + predicate: &str, + assertion_hash: &Hash, + ) -> Result<()> { + // Update subject index: S:{subject} + let subject_key = Self::subject_key(subject); + self.append_to_index(subject_key, assertion_hash).await?; + + // Update compound index: SP:{subject}:{predicate} + let sp_key = Self::subject_predicate_key(subject, predicate); + self.append_to_index(sp_key, assertion_hash).await?; + + debug!( + subject, + predicate, + hash = %hex::encode(assertion_hash), + "Added to indexes" + ); + + Ok(()) + } + + #[instrument(skip(self), fields(subject = %subject))] + async fn get_by_subject(&self, subject: &str) -> Result> { + let key = Self::subject_key(subject); + match self.store.get(&key).await? { + Some(data) => { + let hashes = Self::deserialize_hash_list(&data)?; + debug!(subject, count = hashes.len(), "Retrieved by subject"); + Ok(hashes) + } + None => { + debug!(subject, "No subject index found"); + Ok(Vec::new()) + } + } + } + + #[instrument(skip(self), fields(subject = %subject, predicate = %predicate))] + async fn get_by_subject_predicate(&self, subject: &str, predicate: &str) -> Result> { + let key = Self::subject_predicate_key(subject, predicate); + match self.store.get(&key).await? { + Some(data) => { + let hashes = Self::deserialize_hash_list(&data)?; + debug!(subject, predicate, count = hashes.len(), "Retrieved by subject+predicate"); + Ok(hashes) + } + None => { + debug!(subject, predicate, "No compound index found"); + Ok(Vec::new()) + } + } + } + + #[instrument(skip(self), fields(subject = %subject))] + async fn has_subject(&self, subject: &str) -> Result { + let key = Self::subject_key(subject); + Ok(self.store.get(&key).await?.is_some()) + } + + #[instrument(skip(self), fields(subject = %subject, predicate = %predicate))] + async fn has_subject_predicate(&self, subject: &str, predicate: &str) -> Result { + let key = Self::subject_predicate_key(subject, predicate); + Ok(self.store.get(&key).await?.is_some()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::SledStore; + + #[tokio::test] + async fn test_add_and_get_by_subject() { + let store = SledStore::open_temp().expect("Failed to create store"); + let index_store = GenericIndexStore::new(store); + + let subject = "Tesla"; + let predicate = "revenue"; + let hash1 = [1u8; 32]; + let hash2 = [2u8; 32]; + + // Add two assertions with same subject + index_store.add_to_indexes(subject, predicate, &hash1).await.expect("add 1"); + index_store.add_to_indexes(subject, "profit", &hash2).await.expect("add 2"); + + // Should retrieve both by subject + let hashes = index_store.get_by_subject(subject).await.expect("get"); + assert_eq!(hashes.len(), 2); + assert!(hashes.contains(&hash1)); + assert!(hashes.contains(&hash2)); + } + + #[tokio::test] + async fn test_add_and_get_by_subject_predicate() { + let store = SledStore::open_temp().expect("Failed to create store"); + let index_store = GenericIndexStore::new(store); + + let subject = "Tesla"; + let predicate = "revenue"; + let hash1 = [1u8; 32]; + let hash2 = [2u8; 32]; + let hash3 = [3u8; 32]; + + // Add assertions + index_store.add_to_indexes(subject, predicate, &hash1).await.expect("add 1"); + index_store.add_to_indexes(subject, predicate, &hash2).await.expect("add 2"); + index_store.add_to_indexes(subject, "profit", &hash3).await.expect("add 3"); + + // Compound index should only return hashes for exact subject+predicate match + let hashes = index_store.get_by_subject_predicate(subject, predicate).await.expect("get"); + assert_eq!(hashes.len(), 2); + assert!(hashes.contains(&hash1)); + assert!(hashes.contains(&hash2)); + assert!(!hashes.contains(&hash3)); + } + + #[tokio::test] + async fn test_idempotent_insert() { + let store = SledStore::open_temp().expect("Failed to create store"); + let index_store = GenericIndexStore::new(store); + + let subject = "Tesla"; + let predicate = "revenue"; + let hash = [1u8; 32]; + + // Add same hash multiple times + index_store.add_to_indexes(subject, predicate, &hash).await.expect("add 1"); + index_store.add_to_indexes(subject, predicate, &hash).await.expect("add 2"); + index_store.add_to_indexes(subject, predicate, &hash).await.expect("add 3"); + + // Should only appear once + let hashes = index_store.get_by_subject_predicate(subject, predicate).await.expect("get"); + assert_eq!(hashes.len(), 1); + assert_eq!(hashes[0], hash); + } + + #[tokio::test] + async fn test_empty_index_returns_empty_vec() { + let store = SledStore::open_temp().expect("Failed to create store"); + let index_store = GenericIndexStore::new(store); + + let hashes = index_store.get_by_subject("Nonexistent").await.expect("get"); + assert!(hashes.is_empty(), "Should return empty vec, not error"); + + let hashes = + index_store.get_by_subject_predicate("Nonexistent", "property").await.expect("get"); + assert!(hashes.is_empty(), "Should return empty vec, not error"); + } + + #[tokio::test] + async fn test_has_subject() { + let store = SledStore::open_temp().expect("Failed to create store"); + let index_store = GenericIndexStore::new(store); + + let subject = "Tesla"; + let predicate = "revenue"; + let hash = [1u8; 32]; + + // Initially false + assert!(!index_store.has_subject(subject).await.expect("has")); + + // Add assertion + index_store.add_to_indexes(subject, predicate, &hash).await.expect("add"); + + // Now true + assert!(index_store.has_subject(subject).await.expect("has")); + } + + #[tokio::test] + async fn test_has_subject_predicate() { + let store = SledStore::open_temp().expect("Failed to create store"); + let index_store = GenericIndexStore::new(store); + + let subject = "Tesla"; + let predicate = "revenue"; + let hash = [1u8; 32]; + + // Initially false + assert!(!index_store.has_subject_predicate(subject, predicate).await.expect("has")); + + // Add assertion + index_store.add_to_indexes(subject, predicate, &hash).await.expect("add"); + + // Now true for exact match + assert!(index_store.has_subject_predicate(subject, predicate).await.expect("has")); + + // Still false for different predicate + assert!(!index_store.has_subject_predicate(subject, "profit").await.expect("has")); + } + + #[tokio::test] + async fn test_multiple_subjects_isolated() { + let store = SledStore::open_temp().expect("Failed to create store"); + let index_store = GenericIndexStore::new(store); + + let hash1 = [1u8; 32]; + let hash2 = [2u8; 32]; + + index_store.add_to_indexes("Tesla", "revenue", &hash1).await.expect("add"); + index_store.add_to_indexes("Apple", "revenue", &hash2).await.expect("add"); + + // Each subject should only see its own assertions + let tesla_hashes = index_store.get_by_subject("Tesla").await.expect("get"); + assert_eq!(tesla_hashes.len(), 1); + assert_eq!(tesla_hashes[0], hash1); + + let apple_hashes = index_store.get_by_subject("Apple").await.expect("get"); + assert_eq!(apple_hashes.len(), 1); + assert_eq!(apple_hashes[0], hash2); + } + + #[tokio::test] + async fn test_serialization_round_trip() { + // Property test: ensure serialization is lossless + let hashes = vec![[1u8; 32], [2u8; 32], [3u8; 32]]; + + let serialized = + GenericIndexStore::::serialize_hash_list(&hashes).expect("serialize"); + let deserialized = GenericIndexStore::::deserialize_hash_list(&serialized) + .expect("deserialize"); + + assert_eq!(hashes, deserialized); + } +} diff --git a/crates/stemedb-storage/src/lib.rs b/crates/stemedb-storage/src/lib.rs index c9adc1f..8c3ead6 100644 --- a/crates/stemedb-storage/src/lib.rs +++ b/crates/stemedb-storage/src/lib.rs @@ -2,14 +2,153 @@ //! //! This crate provides the `KVStore` trait for pluggable storage backends //! and a concrete implementation using `sled`. +//! +//! # The Ballot Box +//! +//! The [`VoteStore`] trait provides specialized operations for high-velocity +//! vote ingestion. This is the core of the Ballot Box pattern - separating +//! votes from assertions to enable thousands of agents to vote simultaneously. +//! +//! ```ignore +//! use stemedb_storage::{SledStore, GenericVoteStore, VoteStore}; +//! +//! let kv_store = SledStore::open("./data")?; +//! let vote_store = GenericVoteStore::new(kv_store); +//! +//! // High-velocity vote ingestion +//! let vote_hash = vote_store.put_vote(&vote).await?; +//! +//! // O(1) aggregation via caches +//! let count = vote_store.get_vote_count(&assertion_hash).await?; +//! let weight = vote_store.get_aggregate_weight(&assertion_hash).await?; +//! ``` +//! +//! # TrustRank +//! +//! The [`TrustRankStore`] trait provides reputation tracking for The Hive +//! learning loop. Agent reputation scores affect how their assertions are +//! weighted in the Authority lens. +//! +//! ```ignore +//! use stemedb_storage::{SledStore, GenericTrustRankStore, TrustRankStore}; +//! +//! let kv_store = SledStore::open("./data")?; +//! let trust_store = GenericTrustRankStore::new(kv_store); +//! +//! // Get agent's current reputation +//! let trust = trust_store.get_trust_rank(&agent_id).await?; +//! +//! // Update reputation based on accuracy +//! trust_store.record_outcome(&agent_id, was_accurate, timestamp).await?; +//! +//! // Apply confidence half-life decay +//! trust_store.decay_trust_ranks(current_timestamp, None).await?; +//! ``` +//! +//! # Query Audit Trail +//! +//! The [`AuditStore`] trait provides query audit logging for incident investigation. +//! Every query is logged with provenance to enable "Why did you think that?" debugging. +//! +//! ```ignore +//! use stemedb_storage::{SledStore, GenericAuditStore, AuditStore}; +//! +//! let kv_store = SledStore::open("./data")?; +//! let audit_store = GenericAuditStore::new(kv_store); +//! +//! // Log a query audit +//! audit_store.put_audit(&audit).await?; +//! +//! // Retrieve a specific audit +//! let audit = audit_store.get_audit(&query_id).await?; +//! +//! // Find all audits for an agent in a time range +//! let audits = audit_store.get_audits_for_agent(&agent_id, from, to).await?; +//! ``` +//! +//! # TrustPack ("App Store for Trust") +//! +//! The [`TrustPackStore`] trait provides curated agent lists for filtering consensus. +//! Users subscribe to domain expert packs to see reality through trusted lenses. +//! +//! ```ignore +//! use stemedb_storage::{SledStore, GenericTrustPackStore, TrustPackStore}; +//! +//! let kv_store = SledStore::open("./data")?; +//! let pack_store = GenericTrustPackStore::new(kv_store); +//! +//! // Create and store a pack +//! let pack = TrustPack::new(pack_id, "Mayo_Clinic_Experts".to_string(), maintainer_key); +//! pack_store.put_pack(&pack).await?; +//! +//! // Add trusted agents to the pack +//! pack_store.add_agent_to_pack(&pack_id, &agent_id).await?; +//! +//! // Check membership +//! let is_trusted = pack_store.is_agent_in_pack(&pack_id, &agent_id).await?; +//! ``` +//! +//! # The Meter (Economic Throttling) +//! +//! The [`QuotaStore`] trait provides token bucket quota enforcement to prevent +//! runaway agents from exhausting system resources. +//! +//! ```ignore +//! use stemedb_storage::{SledStore, GenericQuotaStore, QuotaStore, OperationType}; +//! +//! let kv_store = SledStore::open("./data")?; +//! let quota_store = GenericQuotaStore::new(kv_store); +//! +//! // Check and record cost for an operation +//! let result = quota_store.check_and_record( +//! &agent_id, +//! OperationType::Assert, +//! payload_bytes, +//! timestamp, +//! ).await?; +//! +//! if result.allowed { +//! // Process the operation +//! println!("Remaining quota: {}", result.remaining); +//! } else { +//! // Reject: quota exceeded +//! println!("Quota exceeded, resets at {}", result.reset_at); +//! } +//! ``` +/// Query audit trail storage for incident investigation. +pub mod audit_store; /// Error types and Result wrapper for storage operations. pub mod error; +/// Specialized storage for assertion indexes. +pub mod index_store; +/// Economic throttling via Token Bucket quotas (The Meter). +pub mod quota_store; +/// Storage-layer serialization helpers. +pub(crate) mod serde_helpers; /// Sled implementation of the storage backend. pub mod sled_backend; +/// Assertion supersession storage (Error Correction). +pub mod supersession_store; /// Core traits for key-value storage. pub mod traits; +/// TrustPack curation lists (App Store for Trust). +pub mod trust_pack_store; +/// TrustRank reputation storage (The Hive). +pub mod trust_rank_store; +/// High-velocity vote storage (The Ballot Box). +pub mod vote_store; +pub use audit_store::{AuditStore, GenericAuditStore}; pub use error::{Result, StorageError}; +pub use index_store::{GenericIndexStore, IndexStore}; +pub use quota_store::{ + CostConfig, GenericQuotaStore, OperationType, QuotaCheckResult, QuotaRecord, QuotaStore, + DEFAULT_QUOTA_LIMIT, +}; pub use sled_backend::SledStore; +pub use supersession_store::{GenericSupersessionStore, SupersessionStore}; pub use traits::KVStore; +pub use trust_pack_store::{GenericTrustPackStore, TrustPackStore}; +pub use trust_rank_store::{GenericTrustRankStore, TrustRank, TrustRankStore}; +pub use vote_store::{GenericVoteStore, VoteStore}; diff --git a/crates/stemedb-storage/src/quota_store.rs b/crates/stemedb-storage/src/quota_store.rs new file mode 100644 index 0000000..7188e1b --- /dev/null +++ b/crates/stemedb-storage/src/quota_store.rs @@ -0,0 +1,694 @@ +//! Economic throttling via Token Bucket quotas (The Meter). +//! +//! This module implements per-agent per-hour quota tracking to prevent +//! runaway agents from exhausting system resources. +//! +//! # Storage Layout +//! +//! | Key Pattern | Value | Purpose | +//! |-------------|-------|---------| +//! | `QT:{agent_id}:{hour}` | Serialized QuotaRecord | Per-agent per-hour usage | +//! | `QL:{agent_id}` | u64 (LE) | Per-agent quota limit override | +//! +//! # Cost Model +//! +//! | Operation | Base Cost | Notes | +//! |-----------|-----------|-------| +//! | Assert | 10 tokens | Writing truth is expensive | +//! | Vote | 1 token | Voting is cheap | +//! | Query | 5 tokens | + 1 per Lens applied | +//! | Payload | +1/KB | Prevents spamming massive blobs | +//! +//! # Design Philosophy +//! +//! Token Bucket algorithm allows bursts while enforcing long-term limits. +//! Hourly windows force cool-down periods if an agent goes haywire. + +use crate::error::{Result, StorageError}; +use crate::traits::KVStore; +use async_trait::async_trait; +use tracing::{debug, instrument, warn}; + +/// Key prefix for quota records. +#[allow(dead_code)] // Documented for reference; actual key construction uses format!() +const QUOTA_PREFIX: &[u8] = b"QT:"; + +/// Key prefix for per-agent quota limit overrides. +const QUOTA_LIMIT_PREFIX: &[u8] = b"QL:"; + +/// Default quota limit per agent per hour (10,000 tokens). +pub const DEFAULT_QUOTA_LIMIT: u64 = 10_000; + +/// Cost configuration for operations. +#[derive(Debug, Clone, Copy)] +pub struct CostConfig { + /// Base cost for creating an assertion (default: 10). + pub assert_cost: u64, + /// Base cost for casting a vote (default: 1). + pub vote_cost: u64, + /// Base cost for a query (default: 5). + pub query_base_cost: u64, + /// Additional cost per lens applied to a query (default: 1). + pub query_lens_cost: u64, + /// Cost per kilobyte of payload (default: 1). + pub payload_kb_cost: u64, +} + +impl Default for CostConfig { + fn default() -> Self { + Self { + assert_cost: 10, + vote_cost: 1, + query_base_cost: 5, + query_lens_cost: 1, + payload_kb_cost: 1, + } + } +} + +impl CostConfig { + /// Calculate the cost for an assertion operation. + /// + /// # Arguments + /// * `payload_bytes` - Size of the assertion payload in bytes + pub fn cost_for_assert(&self, payload_bytes: usize) -> u64 { + let kb = (payload_bytes as u64).saturating_add(1023) / 1024; // Round up + self.assert_cost.saturating_add(kb.saturating_mul(self.payload_kb_cost)) + } + + /// Calculate the cost for a vote operation. + /// + /// # Arguments + /// * `payload_bytes` - Size of the vote payload in bytes + pub fn cost_for_vote(&self, payload_bytes: usize) -> u64 { + let kb = (payload_bytes as u64).saturating_add(1023) / 1024; + self.vote_cost.saturating_add(kb.saturating_mul(self.payload_kb_cost)) + } + + /// Calculate the cost for a query operation. + /// + /// # Arguments + /// * `lens_count` - Number of lenses applied + /// * `payload_bytes` - Size of the query params in bytes (usually small) + pub fn cost_for_query(&self, lens_count: u64, payload_bytes: usize) -> u64 { + let kb = (payload_bytes as u64).saturating_add(1023) / 1024; + self.query_base_cost + .saturating_add(lens_count.saturating_mul(self.query_lens_cost)) + .saturating_add(kb.saturating_mul(self.payload_kb_cost)) + } +} + +/// Operation type for cost calculation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OperationType { + /// Creating a new assertion. + Assert, + /// Casting a vote. + Vote, + /// Querying assertions. + Query { + /// Number of lenses applied. + lens_count: u64, + }, +} + +/// Quota record for a single agent in a single hour window. +#[derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize, Debug, Clone, PartialEq)] +#[archive(check_bytes)] +pub struct QuotaRecord { + /// The agent's Ed25519 public key. + pub agent_id: [u8; 32], + /// Unix timestamp of the hour window start (truncated to hour). + pub window_start: u64, + /// Total tokens consumed in this window. + pub tokens_used: u64, + /// Number of operations in this window. + pub operation_count: u64, + /// Last operation timestamp. + pub last_operation: u64, +} + +impl QuotaRecord { + /// Create a new quota record for an agent and hour window. + pub fn new(agent_id: [u8; 32], window_start: u64) -> Self { + Self { agent_id, window_start, tokens_used: 0, operation_count: 0, last_operation: 0 } + } + + /// Record a cost against this quota. + /// + /// # Arguments + /// * `cost` - Number of tokens to consume + /// * `timestamp` - Current timestamp + pub fn record(&mut self, cost: u64, timestamp: u64) { + self.tokens_used = self.tokens_used.saturating_add(cost); + self.operation_count = self.operation_count.saturating_add(1); + self.last_operation = timestamp; + } + + /// Check if the quota would be exceeded by a given cost. + /// + /// # Arguments + /// * `cost` - Proposed cost to check + /// * `limit` - Quota limit for this window + /// + /// # Returns + /// `true` if the operation would exceed the quota + pub fn would_exceed(&self, cost: u64, limit: u64) -> bool { + self.tokens_used.saturating_add(cost) > limit + } + + /// Calculate remaining tokens in the quota. + /// + /// # Arguments + /// * `limit` - Quota limit for this window + pub fn remaining(&self, limit: u64) -> u64 { + limit.saturating_sub(self.tokens_used) + } +} + +/// Result of a quota check. +#[derive(Debug, Clone)] +pub struct QuotaCheckResult { + /// Whether the operation is allowed. + pub allowed: bool, + /// Remaining tokens after this operation (if allowed). + pub remaining: u64, + /// Quota limit for this window. + pub limit: u64, + /// Unix timestamp when this quota window resets. + pub reset_at: u64, + /// Cost that was (or would be) charged. + pub cost: u64, +} + +/// Specialized storage trait for quota tracking operations. +/// +/// This trait provides economic throttling operations on top of a generic KVStore, +/// enabling per-agent per-hour quota enforcement. +#[async_trait] +pub trait QuotaStore: Send + Sync { + /// Check if an operation is allowed and record the cost if so. + /// + /// This is the main entry point for quota enforcement. It: + /// 1. Calculates the cost for the operation + /// 2. Checks if the agent has sufficient quota + /// 3. Records the cost if allowed + /// + /// # Arguments + /// * `agent_id` - The agent's Ed25519 public key + /// * `operation` - Type of operation being performed + /// * `payload_bytes` - Size of the request payload + /// * `timestamp` - Current Unix timestamp + /// + /// # Returns + /// `QuotaCheckResult` indicating whether the operation is allowed + async fn check_and_record( + &self, + agent_id: &[u8; 32], + operation: OperationType, + payload_bytes: usize, + timestamp: u64, + ) -> Result; + + /// Get the current quota status for an agent without recording any cost. + /// + /// # Arguments + /// * `agent_id` - The agent's Ed25519 public key + /// * `timestamp` - Current Unix timestamp (to determine window) + /// + /// # Returns + /// Current quota status including remaining tokens + async fn get_quota_status( + &self, + agent_id: &[u8; 32], + timestamp: u64, + ) -> Result; + + /// Set a custom quota limit for an agent. + /// + /// # Arguments + /// * `agent_id` - The agent's Ed25519 public key + /// * `limit` - New quota limit (tokens per hour) + async fn set_quota_limit(&self, agent_id: &[u8; 32], limit: u64) -> Result<()>; + + /// Get the quota limit for an agent. + /// + /// Returns the custom limit if set, otherwise the default. + /// + /// # Arguments + /// * `agent_id` - The agent's Ed25519 public key + async fn get_quota_limit(&self, agent_id: &[u8; 32]) -> Result; + + /// Get the cost configuration. + fn cost_config(&self) -> &CostConfig; +} + +/// QuotaStore implementation backed by a generic KVStore. +#[derive(Clone)] +pub struct GenericQuotaStore { + store: S, + cost_config: CostConfig, + default_limit: u64, +} + +impl GenericQuotaStore { + /// Create a new QuotaStore with default configuration. + pub fn new(store: S) -> Self { + Self { store, cost_config: CostConfig::default(), default_limit: DEFAULT_QUOTA_LIMIT } + } + + /// Create a new QuotaStore with custom configuration. + pub fn with_config(store: S, cost_config: CostConfig, default_limit: u64) -> Self { + Self { store, cost_config, default_limit } + } + + /// Get the hour window start for a given timestamp. + /// + /// Truncates to the start of the hour (seconds since epoch, divisible by 3600). + fn hour_window(timestamp: u64) -> u64 { + (timestamp / 3600) * 3600 + } + + /// Get the reset timestamp (start of next hour). + fn reset_timestamp(timestamp: u64) -> u64 { + Self::hour_window(timestamp) + 3600 + } + + /// Construct the key for a quota record. + fn quota_key(agent_id: &[u8; 32], window_start: u64) -> Vec { + let agent_hex = hex::encode(agent_id); + format!("QT:{}:{}", agent_hex, window_start).into_bytes() + } + + /// Construct the key for a quota limit override. + fn limit_key(agent_id: &[u8; 32]) -> Vec { + let mut key = QUOTA_LIMIT_PREFIX.to_vec(); + key.extend_from_slice(agent_id); + key + } + + /// Serialize a QuotaRecord using the canonical serde helpers. + fn serialize_record(record: &QuotaRecord) -> Result> { + crate::serde_helpers::serialize(record) + } + + /// Deserialize a QuotaRecord using the canonical serde helpers. + fn deserialize_record(data: &[u8]) -> Result { + crate::serde_helpers::deserialize(data) + } + + /// Calculate cost for an operation. + fn calculate_cost(&self, operation: OperationType, payload_bytes: usize) -> u64 { + match operation { + OperationType::Assert => self.cost_config.cost_for_assert(payload_bytes), + OperationType::Vote => self.cost_config.cost_for_vote(payload_bytes), + OperationType::Query { lens_count } => { + self.cost_config.cost_for_query(lens_count, payload_bytes) + } + } + } +} + +#[async_trait] +impl QuotaStore for GenericQuotaStore { + #[instrument(skip(self), fields(agent_id = %hex::encode(agent_id), operation = ?operation, payload_bytes))] + async fn check_and_record( + &self, + agent_id: &[u8; 32], + operation: OperationType, + payload_bytes: usize, + timestamp: u64, + ) -> Result { + let window_start = Self::hour_window(timestamp); + let reset_at = Self::reset_timestamp(timestamp); + let cost = self.calculate_cost(operation, payload_bytes); + let limit = self.get_quota_limit(agent_id).await?; + + // Get or create quota record for this window + let key = Self::quota_key(agent_id, window_start); + let mut record = match self.store.get(&key).await? { + Some(data) => Self::deserialize_record(&data)?, + None => QuotaRecord::new(*agent_id, window_start), + }; + + // Check if operation would exceed quota + if record.would_exceed(cost, limit) { + warn!( + agent_id = %hex::encode(agent_id), + cost, + tokens_used = record.tokens_used, + limit, + "Quota exceeded" + ); + return Ok(QuotaCheckResult { + allowed: false, + remaining: record.remaining(limit), + limit, + reset_at, + cost, + }); + } + + // Record the cost + record.record(cost, timestamp); + let remaining = record.remaining(limit); + + // Persist + let serialized = Self::serialize_record(&record)?; + self.store.put(&key, &serialized).await?; + + debug!(cost, tokens_used = record.tokens_used, remaining, "Quota recorded"); + + Ok(QuotaCheckResult { allowed: true, remaining, limit, reset_at, cost }) + } + + #[instrument(skip(self), fields(agent_id = %hex::encode(agent_id)))] + async fn get_quota_status( + &self, + agent_id: &[u8; 32], + timestamp: u64, + ) -> Result { + let window_start = Self::hour_window(timestamp); + let reset_at = Self::reset_timestamp(timestamp); + let limit = self.get_quota_limit(agent_id).await?; + + let key = Self::quota_key(agent_id, window_start); + let record = match self.store.get(&key).await? { + Some(data) => Self::deserialize_record(&data)?, + None => QuotaRecord::new(*agent_id, window_start), + }; + + Ok(QuotaCheckResult { + allowed: true, // Status check doesn't consume quota + remaining: record.remaining(limit), + limit, + reset_at, + cost: 0, + }) + } + + #[instrument(skip(self), fields(agent_id = %hex::encode(agent_id), limit))] + async fn set_quota_limit(&self, agent_id: &[u8; 32], limit: u64) -> Result<()> { + let key = Self::limit_key(agent_id); + self.store.put(&key, &limit.to_le_bytes()).await?; + debug!("Set custom quota limit"); + Ok(()) + } + + #[instrument(skip(self), fields(agent_id = %hex::encode(agent_id)))] + async fn get_quota_limit(&self, agent_id: &[u8; 32]) -> Result { + let key = Self::limit_key(agent_id); + match self.store.get(&key).await? { + Some(bytes) if bytes.len() == 8 => { + let arr: [u8; 8] = bytes + .try_into() + .map_err(|_| StorageError::Serialization("Invalid limit bytes".to_string()))?; + Ok(u64::from_le_bytes(arr)) + } + _ => Ok(self.default_limit), + } + } + + fn cost_config(&self) -> &CostConfig { + &self.cost_config + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::SledStore; + + fn test_agent() -> [u8; 32] { + [1u8; 32] + } + + #[test] + fn test_cost_config_assert() { + let config = CostConfig::default(); + + // Small payload + assert_eq!(config.cost_for_assert(100), 11); // 10 base + 1 for <1KB + + // Exactly 1KB + assert_eq!(config.cost_for_assert(1024), 11); // 10 base + 1 for 1KB + + // 2KB + assert_eq!(config.cost_for_assert(2048), 12); // 10 base + 2 for 2KB + + // 10KB + assert_eq!(config.cost_for_assert(10240), 20); // 10 base + 10 for 10KB + } + + #[test] + fn test_cost_config_vote() { + let config = CostConfig::default(); + + // Small vote (typical) + assert_eq!(config.cost_for_vote(100), 2); // 1 base + 1 for <1KB + } + + #[test] + fn test_cost_config_query() { + let config = CostConfig::default(); + + // Simple query, no lens + assert_eq!(config.cost_for_query(0, 50), 6); // 5 base + 0 lens + 1 payload + + // Query with 1 lens + assert_eq!(config.cost_for_query(1, 50), 7); // 5 base + 1 lens + 1 payload + + // Query with 3 lenses + assert_eq!(config.cost_for_query(3, 50), 9); // 5 base + 3 lens + 1 payload + } + + #[test] + fn test_hour_window() { + // 2024-01-15 09:30:00 UTC = 1705315800 + let timestamp = 1705315800; + let window = GenericQuotaStore::::hour_window(timestamp); + + // 1705315800 / 3600 = 473698.833... -> 473698 * 3600 = 1705312800 + assert_eq!(window, 1705312800); + assert_eq!(window % 3600, 0); + } + + #[test] + fn test_reset_timestamp() { + let timestamp = 1705315800; // :30 past the hour + let reset = GenericQuotaStore::::reset_timestamp(timestamp); + + // Window is 1705312800, next hour is +3600 = 1705316400 + assert_eq!(reset, 1705316400); + } + + #[test] + fn test_quota_record_basic() { + let agent_id = test_agent(); + let mut record = QuotaRecord::new(agent_id, 1705314000); + + assert_eq!(record.tokens_used, 0); + assert_eq!(record.operation_count, 0); + assert_eq!(record.remaining(10000), 10000); + assert!(!record.would_exceed(100, 10000)); + + record.record(100, 1705314100); + + assert_eq!(record.tokens_used, 100); + assert_eq!(record.operation_count, 1); + assert_eq!(record.remaining(10000), 9900); + } + + #[test] + fn test_quota_record_would_exceed() { + let agent_id = test_agent(); + let mut record = QuotaRecord::new(agent_id, 1705314000); + + record.tokens_used = 9900; + + assert!(!record.would_exceed(100, 10000)); // Exactly at limit + assert!(record.would_exceed(101, 10000)); // Over limit + } + + #[tokio::test] + async fn test_check_and_record_basic() { + let store = SledStore::open_temp().expect("store"); + let quota_store = GenericQuotaStore::new(store); + + let agent_id = test_agent(); + let timestamp = 1705315800; + + // First operation should succeed + let result = quota_store + .check_and_record(&agent_id, OperationType::Assert, 100, timestamp) + .await + .expect("check"); + + assert!(result.allowed); + assert_eq!(result.cost, 11); // 10 base + 1 KB + assert_eq!(result.remaining, 10000 - 11); + assert_eq!(result.limit, 10000); + } + + #[tokio::test] + async fn test_quota_enforcement() { + let store = SledStore::open_temp().expect("store"); + let quota_store = GenericQuotaStore::with_config( + store, + CostConfig::default(), + 100, // Low limit for testing + ); + + let agent_id = test_agent(); + let timestamp = 1705315800; + + // First operation (cost 11) should succeed + let result = quota_store + .check_and_record(&agent_id, OperationType::Assert, 100, timestamp) + .await + .expect("check"); + assert!(result.allowed); + + // Consume most of the quota + for _ in 0..8 { + let result = quota_store + .check_and_record(&agent_id, OperationType::Assert, 100, timestamp) + .await + .expect("check"); + assert!(result.allowed); + } + + // Next operation should fail (9 * 11 = 99, need 11 more, only 1 left) + let result = quota_store + .check_and_record(&agent_id, OperationType::Assert, 100, timestamp) + .await + .expect("check"); + assert!(!result.allowed); + assert_eq!(result.remaining, 1); // 100 - 99 = 1 + } + + #[tokio::test] + async fn test_quota_resets_each_hour() { + let store = SledStore::open_temp().expect("store"); + let quota_store = GenericQuotaStore::with_config(store, CostConfig::default(), 50); + + let agent_id = test_agent(); + let hour1 = 1705314000; // 10:00:00 + let hour2 = 1705317600; // 11:00:00 + + // Exhaust quota in hour 1 + for _ in 0..4 { + let result = quota_store + .check_and_record(&agent_id, OperationType::Assert, 100, hour1) + .await + .expect("check"); + assert!(result.allowed); + } + + // Should be denied in hour 1 + let result = quota_store + .check_and_record(&agent_id, OperationType::Assert, 100, hour1) + .await + .expect("check"); + assert!(!result.allowed); + + // Should succeed in hour 2 (new window) + let result = quota_store + .check_and_record(&agent_id, OperationType::Assert, 100, hour2) + .await + .expect("check"); + assert!(result.allowed); + assert_eq!(result.remaining, 50 - 11); + } + + #[tokio::test] + async fn test_custom_quota_limit() { + let store = SledStore::open_temp().expect("store"); + let quota_store = GenericQuotaStore::new(store); + + let agent_id = test_agent(); + + // Default limit + let limit = quota_store.get_quota_limit(&agent_id).await.expect("limit"); + assert_eq!(limit, DEFAULT_QUOTA_LIMIT); + + // Set custom limit + quota_store.set_quota_limit(&agent_id, 50_000).await.expect("set"); + + let limit = quota_store.get_quota_limit(&agent_id).await.expect("limit"); + assert_eq!(limit, 50_000); + } + + #[tokio::test] + async fn test_get_quota_status() { + let store = SledStore::open_temp().expect("store"); + let quota_store = GenericQuotaStore::new(store); + + let agent_id = test_agent(); + let timestamp = 1705315800; + + // Check status before any operations + let status = quota_store.get_quota_status(&agent_id, timestamp).await.expect("status"); + assert!(status.allowed); + assert_eq!(status.remaining, 10000); + assert_eq!(status.cost, 0); + + // Do an operation + quota_store + .check_and_record(&agent_id, OperationType::Vote, 50, timestamp) + .await + .expect("record"); + + // Check status after operation + let status = quota_store.get_quota_status(&agent_id, timestamp).await.expect("status"); + assert_eq!(status.remaining, 10000 - 2); // Vote cost = 2 + } + + #[tokio::test] + async fn test_different_operation_types() { + let store = SledStore::open_temp().expect("store"); + let quota_store = GenericQuotaStore::new(store); + + let agent_id = test_agent(); + let timestamp = 1705315800; + + // Assert + let result = quota_store + .check_and_record(&agent_id, OperationType::Assert, 100, timestamp) + .await + .expect("assert"); + assert_eq!(result.cost, 11); // 10 + 1 + + // Vote + let result = quota_store + .check_and_record(&agent_id, OperationType::Vote, 100, timestamp) + .await + .expect("vote"); + assert_eq!(result.cost, 2); // 1 + 1 + + // Query with lens + let result = quota_store + .check_and_record(&agent_id, OperationType::Query { lens_count: 2 }, 50, timestamp) + .await + .expect("query"); + assert_eq!(result.cost, 8); // 5 + 2 + 1 + } + + #[tokio::test] + async fn test_serialization_roundtrip() { + let record = QuotaRecord { + agent_id: [42u8; 32], + window_start: 1705314000, + tokens_used: 500, + operation_count: 25, + last_operation: 1705315000, + }; + + let serialized = + GenericQuotaStore::::serialize_record(&record).expect("serialize"); + let deserialized = + GenericQuotaStore::::deserialize_record(&serialized).expect("deserialize"); + + assert_eq!(record, deserialized); + } +} diff --git a/crates/stemedb-storage/src/serde_helpers.rs b/crates/stemedb-storage/src/serde_helpers.rs new file mode 100644 index 0000000..1526de9 --- /dev/null +++ b/crates/stemedb-storage/src/serde_helpers.rs @@ -0,0 +1,77 @@ +//! Storage-layer serialization helpers that map core serde errors to StorageError. +//! +//! This module provides a single source of truth for serialization in the storage layer, +//! eliminating duplication of the error mapping pattern across all store implementations. +//! +//! # Usage +//! +//! ```ignore +//! use crate::serde_helpers::{serialize, deserialize}; +//! +//! fn store_item(&self, item: &MyItem) -> Result<()> { +//! let bytes = serialize(item)?; +//! self.kv.put(&key, &bytes)?; +//! Ok(()) +//! } +//! +//! fn load_item(&self, key: &[u8]) -> Result { +//! let bytes = self.kv.get(key)?.ok_or_else(|| StorageError::NotFound(...))?; +//! deserialize(&bytes) +//! } +//! ``` + +use crate::error::{Result, StorageError}; + +/// Serialize a value using the canonical stemedb_core::serde module. +/// +/// Maps serialization errors to [`StorageError::Serialization`]. +pub fn serialize(value: &T) -> Result> +where + T: rkyv::Serialize>, +{ + stemedb_core::serde::serialize(value).map_err(|e| StorageError::Serialization(e.to_string())) +} + +/// Deserialize a value using the canonical stemedb_core::serde module. +/// +/// Maps deserialization errors to [`StorageError::Serialization`]. +pub fn deserialize(data: &[u8]) -> Result +where + T: rkyv::Archive, + T::Archived: for<'a> rkyv::CheckBytes> + + rkyv::Deserialize, +{ + stemedb_core::serde::deserialize(data).map_err(|e| StorageError::Serialization(e.to_string())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Debug, PartialEq, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] + #[archive(check_bytes)] + struct TestItem { + id: u64, + name: String, + } + + #[test] + fn test_roundtrip() { + let item = TestItem { id: 42, name: "test".to_string() }; + + let bytes = serialize(&item).expect("serialize should succeed"); + let recovered: TestItem = deserialize(&bytes).expect("deserialize should succeed"); + + assert_eq!(item, recovered); + } + + #[test] + fn test_deserialize_invalid_data() { + let garbage = vec![0xFF, 0xFE, 0xFD]; + let result: Result = deserialize(&garbage); + + assert!(result.is_err()); + let err = result.unwrap_err(); + assert!(matches!(err, StorageError::Serialization(_))); + } +} diff --git a/crates/stemedb-storage/src/sled_backend.rs b/crates/stemedb-storage/src/sled_backend.rs index 09c4255..6110183 100644 --- a/crates/stemedb-storage/src/sled_backend.rs +++ b/crates/stemedb-storage/src/sled_backend.rs @@ -18,7 +18,9 @@ impl SledStore { } /// Open a temporary Sled database for testing. - #[cfg(test)] + /// + /// The database will be automatically deleted when dropped. + /// Useful for unit tests in this and other crates. pub fn open_temp() -> Result { let config = sled::Config::new().temporary(true); let db = config.open().map_err(StorageError::Sled)?; @@ -57,6 +59,55 @@ impl KVStore for SledStore { self.db.flush_async().await.map_err(StorageError::Sled)?; Ok(()) } + + async fn fetch_and_add_u64(&self, key: &[u8], delta: u64) -> Result { + let result = self + .db + .update_and_fetch(key, |old| { + let current = old + .and_then(|b| <[u8; 8]>::try_from(b).ok()) + .map(u64::from_le_bytes) + .unwrap_or(0); + Some(current.saturating_add(delta).to_le_bytes().to_vec()) + }) + .map_err(StorageError::Sled)?; + + // Result is Some because our update_fn always returns Some + let bytes = result.ok_or_else(|| { + StorageError::Serialization("fetch_and_add_u64 returned None unexpectedly".to_string()) + })?; + let arr: [u8; 8] = bytes.as_ref().try_into().map_err(|_| { + StorageError::Serialization("fetch_and_add_u64 returned wrong size".to_string()) + })?; + Ok(u64::from_le_bytes(arr)) + } + + async fn compare_and_swap_f32(&self, key: &[u8], update_fn: F) -> Result + where + F: Fn(f32) -> f32 + Send + Sync, + { + let result = self + .db + .update_and_fetch(key, |old| { + let current = old + .and_then(|b| <[u8; 4]>::try_from(b).ok()) + .map(f32::from_le_bytes) + .unwrap_or(0.0); + let new_value = update_fn(current); + Some(new_value.to_le_bytes().to_vec()) + }) + .map_err(StorageError::Sled)?; + + let bytes = result.ok_or_else(|| { + StorageError::Serialization( + "compare_and_swap_f32 returned None unexpectedly".to_string(), + ) + })?; + let arr: [u8; 4] = bytes.as_ref().try_into().map_err(|_| { + StorageError::Serialization("compare_and_swap_f32 returned wrong size".to_string()) + })?; + Ok(f32::from_le_bytes(arr)) + } } #[cfg(test)] diff --git a/crates/stemedb-storage/src/supersession_store.rs b/crates/stemedb-storage/src/supersession_store.rs new file mode 100644 index 0000000..6db32fa --- /dev/null +++ b/crates/stemedb-storage/src/supersession_store.rs @@ -0,0 +1,344 @@ +//! Specialized storage for assertion supersession records. +//! +//! The supersession pattern enables error correction without violating append-only +//! semantics. Instead of mutating an assertion, we create a supersession record +//! that points from the old (target) to the new (replacement) assertion. +//! +//! # Storage Layout +//! +//! | Key Pattern | Value | Purpose | +//! |-------------|-------|---------| +//! | `SUP:{target_hash}` | Serialized Supersession | Quick lookup: "Is this superseded?" | +//! | `SUP:IDX:{agent_id}:{timestamp}` | target_hash | Audit: "What did this agent supersede?" | +//! +//! # Use Case: 3am Incident Investigation +//! +//! 1. SRE finds agent deployed bad config +//! 2. Trace shows agent queried assertion X with hash `abc123` +//! 3. Supervisor creates supersession: `abc123` → `new_hash` (Invalidate) +//! 4. Future queries skip `abc123` automatically +//! 5. Audit trail preserved: "Who fixed it? When? Why?" + +use crate::error::{Result, StorageError}; +use crate::traits::KVStore; +use async_trait::async_trait; +use stemedb_core::serde::{deserialize, serialize}; +use stemedb_core::types::{Hash, Supersession}; +use tracing::{debug, instrument}; + +/// Key prefix for supersession records. +const SUPERSESSION_PREFIX: &[u8] = b"SUP:"; +/// Key prefix for agent supersession index. +const SUPERSESSION_INDEX_PREFIX: &[u8] = b"SUP:IDX:"; + +/// Specialized storage trait for supersession operations. +/// +/// This trait provides supersession-specific operations on top of a generic KVStore, +/// enabling error correction with full audit trail. +#[async_trait] +pub trait SupersessionStore: Send + Sync { + /// Store a supersession record. + /// + /// This operation: + /// 1. Serializes the supersession using rkyv + /// 2. Stores at `SUP:{target_hash}` + /// 3. Creates index entry at `SUP:IDX:{agent_id}:{timestamp}` + /// + /// # Returns + /// Ok(()) on success, error if serialization fails. + async fn put_supersession(&self, supersession: &Supersession) -> Result<()>; + + /// Check if an assertion has been superseded. + /// + /// # Arguments + /// * `target_hash` - The hash of the assertion to check + /// + /// # Returns + /// The supersession record if the assertion is superseded, None otherwise. + async fn get_supersession(&self, target_hash: &Hash) -> Result>; + + /// Check if an assertion is superseded (quick existence check). + /// + /// # Arguments + /// * `target_hash` - The hash of the assertion to check + /// + /// # Returns + /// true if the assertion has been superseded, false otherwise. + async fn is_superseded(&self, target_hash: &Hash) -> Result; + + /// Get all supersessions created by a specific agent within a time range. + /// + /// # Arguments + /// * `agent_id` - The Ed25519 public key of the agent + /// * `from_timestamp` - Start of time range (Unix timestamp, inclusive) + /// * `to_timestamp` - End of time range (Unix timestamp, inclusive, optional) + /// * `limit` - Maximum number of results to return (optional) + /// + /// # Returns + /// Vector of supersession records, ordered by timestamp descending. + async fn get_supersessions_by_agent( + &self, + agent_id: &[u8; 32], + from_timestamp: u64, + to_timestamp: Option, + limit: Option, + ) -> Result>; +} + +/// Generic implementation of SupersessionStore for any KVStore backend. +pub struct GenericSupersessionStore { + store: S, +} + +impl GenericSupersessionStore { + /// Create a new GenericSupersessionStore wrapping the given KVStore. + pub fn new(store: S) -> Self { + Self { store } + } + + /// Build the key for a supersession record. + fn supersession_key(target_hash: &Hash) -> Vec { + let mut key = SUPERSESSION_PREFIX.to_vec(); + key.extend_from_slice(target_hash); + key + } + + /// Build the key for the agent supersession index. + fn index_key(agent_id: &[u8; 32], timestamp: u64) -> Vec { + let mut key = SUPERSESSION_INDEX_PREFIX.to_vec(); + key.extend_from_slice(agent_id); + key.push(b':'); + key.extend_from_slice(×tamp.to_be_bytes()); + key + } + + /// Build the prefix for scanning an agent's supersessions. + fn index_prefix(agent_id: &[u8; 32]) -> Vec { + let mut key = SUPERSESSION_INDEX_PREFIX.to_vec(); + key.extend_from_slice(agent_id); + key.push(b':'); + key + } +} + +#[async_trait] +impl SupersessionStore for GenericSupersessionStore { + #[instrument(skip(self, supersession), fields(target_hash = ?supersession.target_hash))] + async fn put_supersession(&self, supersession: &Supersession) -> Result<()> { + // Serialize the supersession + let bytes = serialize(supersession).map_err(|e| { + StorageError::Serialization(format!("Failed to serialize supersession: {}", e)) + })?; + + // Store at primary key + let key = Self::supersession_key(&supersession.target_hash); + self.store.put(&key, &bytes).await?; + + // Store index entry (value is the target_hash for lookup) + let index_key = Self::index_key(&supersession.agent_id, supersession.timestamp); + self.store.put(&index_key, &supersession.target_hash).await?; + + debug!( + target_hash = ?supersession.target_hash, + supersession_type = ?supersession.supersession_type, + "Stored supersession record" + ); + + Ok(()) + } + + #[instrument(skip(self))] + async fn get_supersession(&self, target_hash: &Hash) -> Result> { + let key = Self::supersession_key(target_hash); + + match self.store.get(&key).await? { + Some(bytes) => { + let supersession: Supersession = deserialize(&bytes).map_err(|e| { + StorageError::Serialization(format!( + "Failed to deserialize supersession: {}", + e + )) + })?; + Ok(Some(supersession)) + } + None => Ok(None), + } + } + + #[instrument(skip(self))] + async fn is_superseded(&self, target_hash: &Hash) -> Result { + let key = Self::supersession_key(target_hash); + Ok(self.store.get(&key).await?.is_some()) + } + + #[instrument(skip(self), fields(agent_id = ?agent_id, from = from_timestamp, to = ?to_timestamp))] + async fn get_supersessions_by_agent( + &self, + agent_id: &[u8; 32], + from_timestamp: u64, + to_timestamp: Option, + limit: Option, + ) -> Result> { + let prefix = Self::index_prefix(agent_id); + let entries = self.store.scan_prefix(&prefix).await?; + + let to_ts = to_timestamp.unwrap_or(u64::MAX); + let max_results = limit.unwrap_or(1000); + + let mut supersessions = Vec::new(); + + for (key, target_hash_bytes) in entries { + // Extract timestamp from key (last 8 bytes after the prefix + agent_id + colon) + // Key format: SUP:IDX:{agent_id}:{timestamp} + let timestamp_start = SUPERSESSION_INDEX_PREFIX.len() + 32 + 1; // prefix + agent_id + ':' + if key.len() < timestamp_start + 8 { + continue; // Malformed key + } + + let timestamp_bytes: [u8; 8] = + key[timestamp_start..timestamp_start + 8].try_into().map_err(|_| { + StorageError::Serialization("Invalid timestamp in index key".to_string()) + })?; + let timestamp = u64::from_be_bytes(timestamp_bytes); + + // Filter by time range + if timestamp < from_timestamp || timestamp > to_ts { + continue; + } + + // Parse target hash + if target_hash_bytes.len() != 32 { + continue; // Malformed value + } + let target_hash: Hash = target_hash_bytes.try_into().map_err(|_| { + StorageError::Serialization("Invalid target hash in index".to_string()) + })?; + + // Fetch the actual supersession record + if let Some(supersession) = self.get_supersession(&target_hash).await? { + supersessions.push(supersession); + + if supersessions.len() >= max_results { + break; + } + } + } + + // Sort by timestamp descending (most recent first) + supersessions.sort_by(|a, b| b.timestamp.cmp(&a.timestamp)); + + Ok(supersessions) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::SledStore; + use stemedb_core::types::SupersessionType; + use tempfile::tempdir; + + async fn create_test_store() -> GenericSupersessionStore { + let dir = tempdir().expect("Failed to create temp dir"); + let store = SledStore::open(dir.path()).expect("Failed to open store"); + GenericSupersessionStore::new(store) + } + + #[tokio::test] + async fn test_put_and_get_supersession() { + let store = create_test_store().await; + + let supersession = Supersession { + target_hash: [1u8; 32], + supersession_type: SupersessionType::Invalidate, + reason: "Test invalidation".to_string(), + new_hash: Some([2u8; 32]), + timestamp: 1704067200, + agent_id: [3u8; 32], + signature: [4u8; 64], + }; + + store.put_supersession(&supersession).await.expect("Failed to put supersession"); + + let retrieved = + store.get_supersession(&[1u8; 32]).await.expect("Failed to get supersession"); + + assert!(retrieved.is_some()); + let retrieved = retrieved.expect("Expected supersession"); + assert_eq!(retrieved.target_hash, [1u8; 32]); + assert_eq!(retrieved.supersession_type, SupersessionType::Invalidate); + assert_eq!(retrieved.reason, "Test invalidation"); + } + + #[tokio::test] + async fn test_is_superseded() { + let store = create_test_store().await; + + // Not superseded initially + assert!(!store.is_superseded(&[1u8; 32]).await.expect("Failed to check")); + + let supersession = Supersession { + target_hash: [1u8; 32], + supersession_type: SupersessionType::Temporal, + reason: "Outdated".to_string(), + new_hash: Some([2u8; 32]), + timestamp: 1704067200, + agent_id: [3u8; 32], + signature: [4u8; 64], + }; + + store.put_supersession(&supersession).await.expect("Failed to put"); + + // Now superseded + assert!(store.is_superseded(&[1u8; 32]).await.expect("Failed to check")); + + // Other hash not superseded + assert!(!store.is_superseded(&[99u8; 32]).await.expect("Failed to check")); + } + + #[tokio::test] + async fn test_get_supersessions_by_agent() { + let store = create_test_store().await; + + let agent_id = [42u8; 32]; + + // Create multiple supersessions at different times + for i in 0..5 { + let supersession = Supersession { + target_hash: [i; 32], + supersession_type: SupersessionType::Invalidate, + reason: format!("Supersession {}", i), + new_hash: None, + timestamp: 1704067200 + (i as u64 * 100), + agent_id, + signature: [0u8; 64], + }; + store.put_supersession(&supersession).await.expect("Failed to put"); + } + + // Get all supersessions for agent + let results = store + .get_supersessions_by_agent(&agent_id, 0, None, None) + .await + .expect("Failed to get supersessions"); + + assert_eq!(results.len(), 5); + + // Should be sorted by timestamp descending + assert_eq!(results[0].target_hash, [4u8; 32]); // Most recent + + // Test with limit + let limited = + store.get_supersessions_by_agent(&agent_id, 0, None, Some(2)).await.expect("Failed"); + + assert_eq!(limited.len(), 2); + + // Test with time range + let ranged = store + .get_supersessions_by_agent(&agent_id, 1704067200 + 100, Some(1704067200 + 300), None) + .await + .expect("Failed"); + + assert_eq!(ranged.len(), 3); // timestamps 100, 200, 300 + } +} diff --git a/crates/stemedb-storage/src/traits.rs b/crates/stemedb-storage/src/traits.rs index f02528b..ccd5cda 100644 --- a/crates/stemedb-storage/src/traits.rs +++ b/crates/stemedb-storage/src/traits.rs @@ -1,5 +1,6 @@ use crate::error::Result; use async_trait::async_trait; +use std::sync::Arc; /// Abstract interface for Key-Value storage backends. /// @@ -21,4 +22,59 @@ pub trait KVStore: Send + Sync { /// Flush any pending writes to disk. async fn flush(&self) -> Result<()>; + + /// Atomically add to a u64 counter stored at key. + /// + /// If key doesn't exist, initializes to 0 before adding. + /// Returns the new value after addition. + /// + /// This is critical for correctness in high-velocity vote ingestion, + /// where multiple concurrent writers update the same vote count. + async fn fetch_and_add_u64(&self, key: &[u8], delta: u64) -> Result; + + /// Atomically update an f32 value using compare-and-swap semantics. + /// + /// If key doesn't exist, initializes to 0.0 before applying the update. + /// The `update_fn` receives the current value and returns the new value. + /// Returns the new value after update. + /// + /// Used for aggregate weight caches where we need thread-safe f32 updates. + async fn compare_and_swap_f32(&self, key: &[u8], update_fn: F) -> Result + where + F: Fn(f32) -> f32 + Send + Sync; +} + +/// Implement KVStore for Arc to enable sharing stores across components. +#[async_trait] +impl KVStore for Arc { + async fn get(&self, key: &[u8]) -> Result>> { + (**self).get(key).await + } + + async fn put(&self, key: &[u8], value: &[u8]) -> Result<()> { + (**self).put(key, value).await + } + + async fn delete(&self, key: &[u8]) -> Result<()> { + (**self).delete(key).await + } + + async fn scan_prefix(&self, prefix: &[u8]) -> Result, Vec)>> { + (**self).scan_prefix(prefix).await + } + + async fn flush(&self) -> Result<()> { + (**self).flush().await + } + + async fn fetch_and_add_u64(&self, key: &[u8], delta: u64) -> Result { + (**self).fetch_and_add_u64(key, delta).await + } + + async fn compare_and_swap_f32(&self, key: &[u8], update_fn: F) -> Result + where + F: Fn(f32) -> f32 + Send + Sync, + { + (**self).compare_and_swap_f32(key, update_fn).await + } } diff --git a/crates/stemedb-storage/src/trust_pack_store.rs b/crates/stemedb-storage/src/trust_pack_store.rs new file mode 100644 index 0000000..034475b --- /dev/null +++ b/crates/stemedb-storage/src/trust_pack_store.rs @@ -0,0 +1,481 @@ +//! Specialized storage for TrustPack curation lists. +//! +//! The TrustPack system enables the "App Store for Trust" model where users +//! subscribe to curated lists of trusted agents to filter consensus through +//! domain expertise. +//! +//! # Storage Layout +//! +//! | Key Pattern | Value | Purpose | +//! |-------------|-------|---------| +//! | `TP:{pack_id}` | Serialized TrustPack | Pack definition and agent membership | +//! +//! # Design Philosophy +//! +//! This module follows the "Deep Module" principle from Philosophy of Software Design: +//! - Simple interface hiding pack management complexity +//! - Content-addressed pack IDs (BLAKE3 hash) +//! - Idempotent agent add/remove operations +//! - Efficient membership checks +//! +//! All operations are defensive against missing data (missing pack returns None). + +use crate::error::{Result, StorageError}; +use crate::traits::KVStore; +use async_trait::async_trait; +use stemedb_core::types::{PackId, TrustPack}; +use tracing::{debug, instrument}; + +/// Key prefix for TrustPack entries. +const TRUST_PACK_PREFIX: &[u8] = b"TP:"; + +/// Specialized storage trait for TrustPack operations. +/// +/// This trait provides pack-specific operations on top of a generic KVStore, +/// enabling efficient trust pack management for curated consensus filtering. +/// +/// # Example +/// +/// ```ignore +/// let pack_store = GenericTrustPackStore::new(kv_store); +/// let pack_id = pack_store.put_pack(&pack).await?; +/// pack_store.add_agent_to_pack(&pack_id, &agent_id).await?; +/// let is_member = pack_store.is_agent_in_pack(&pack_id, &agent_id).await?; +/// ``` +#[async_trait] +pub trait TrustPackStore: Send + Sync { + /// Store a TrustPack and return its ID. + /// + /// This operation serializes the pack and stores it at `TP:{pack_id}`. + /// + /// # Arguments + /// * `pack` - The TrustPack to store + /// + /// # Returns + /// The pack's ID (from the pack itself, not computed) + async fn put_pack(&self, pack: &TrustPack) -> Result; + + /// Get a TrustPack by its ID. + /// + /// # Arguments + /// * `pack_id` - Content-addressed pack ID + /// + /// # Returns + /// The pack if found, None otherwise + async fn get_pack(&self, pack_id: &PackId) -> Result>; + + /// Add an agent to a pack. + /// + /// This operation: + /// 1. Loads the pack + /// 2. Adds the agent (idempotent) + /// 3. Stores the updated pack + /// + /// # Arguments + /// * `pack_id` - ID of the pack to modify + /// * `agent_id` - Agent to add + /// + /// # Errors + /// Returns error if pack does not exist + async fn add_agent_to_pack(&self, pack_id: &PackId, agent_id: &[u8; 32]) -> Result<()>; + + /// Remove an agent from a pack. + /// + /// This operation: + /// 1. Loads the pack + /// 2. Removes the agent (no-op if not present) + /// 3. Stores the updated pack + /// + /// # Arguments + /// * `pack_id` - ID of the pack to modify + /// * `agent_id` - Agent to remove + /// + /// # Errors + /// Returns error if pack does not exist + async fn remove_agent_from_pack(&self, pack_id: &PackId, agent_id: &[u8; 32]) -> Result<()>; + + /// Check if an agent is a member of a pack. + /// + /// # Arguments + /// * `pack_id` - Pack to check + /// * `agent_id` - Agent to check for + /// + /// # Returns + /// `true` if agent is in pack, `false` if not or pack doesn't exist + async fn is_agent_in_pack(&self, pack_id: &PackId, agent_id: &[u8; 32]) -> Result; + + /// List all TrustPack IDs in the store. + /// + /// Scans all keys with prefix `TP:` and extracts pack IDs. + /// + /// # Returns + /// Vector of pack IDs, empty if no packs exist + async fn list_packs(&self) -> Result>; +} + +/// TrustPackStore implementation backed by a generic KVStore. +/// +/// This implementation stores TrustPack data at `TP:{pack_id}` and provides +/// all operations for pack management and agent membership. +pub struct GenericTrustPackStore { + store: S, +} + +impl GenericTrustPackStore { + /// Create a new TrustPackStore backed by the given KVStore. + pub fn new(store: S) -> Self { + Self { store } + } + + /// Construct the key for a TrustPack entry. + fn trust_pack_key(pack_id: &PackId) -> Vec { + let mut key = TRUST_PACK_PREFIX.to_vec(); + key.extend_from_slice(pack_id); + key + } + + /// Serialize a TrustPack using the canonical serde helpers. + fn serialize_pack(pack: &TrustPack) -> Result> { + crate::serde_helpers::serialize(pack) + } + + /// Deserialize a TrustPack using the canonical serde helpers. + fn deserialize_pack(data: &[u8]) -> Result { + crate::serde_helpers::deserialize(data) + } +} + +#[async_trait] +impl TrustPackStore for GenericTrustPackStore { + #[instrument(skip(self, pack), fields(pack_id = %hex::encode(pack.id), pack_name = %pack.name, agent_count = pack.agent_count()))] + async fn put_pack(&self, pack: &TrustPack) -> Result { + let serialized = Self::serialize_pack(pack)?; + let key = Self::trust_pack_key(&pack.id); + self.store.put(&key, &serialized).await?; + + debug!( + maintainer = %hex::encode(pack.maintainer), + "Stored TrustPack" + ); + + Ok(pack.id) + } + + #[instrument(skip(self), fields(pack_id = %hex::encode(pack_id)))] + async fn get_pack(&self, pack_id: &PackId) -> Result> { + let key = Self::trust_pack_key(pack_id); + match self.store.get(&key).await? { + Some(data) => { + let pack = Self::deserialize_pack(&data)?; + debug!( + pack_name = %pack.name, + agent_count = pack.agent_count(), + "Retrieved TrustPack" + ); + Ok(Some(pack)) + } + None => { + debug!("TrustPack not found"); + Ok(None) + } + } + } + + #[instrument(skip(self), fields(pack_id = %hex::encode(pack_id), agent_id = %hex::encode(agent_id)))] + async fn add_agent_to_pack(&self, pack_id: &PackId, agent_id: &[u8; 32]) -> Result<()> { + let mut pack = self.get_pack(pack_id).await?.ok_or_else(|| { + StorageError::NotFound(format!("Pack not found: {}", hex::encode(pack_id))) + })?; + + let old_count = pack.agent_count(); + pack.add_agent(*agent_id); + let new_count = pack.agent_count(); + + let serialized = Self::serialize_pack(&pack)?; + let key = Self::trust_pack_key(pack_id); + self.store.put(&key, &serialized).await?; + + debug!(old_count, new_count, added = new_count > old_count, "Updated pack membership"); + + Ok(()) + } + + #[instrument(skip(self), fields(pack_id = %hex::encode(pack_id), agent_id = %hex::encode(agent_id)))] + async fn remove_agent_from_pack(&self, pack_id: &PackId, agent_id: &[u8; 32]) -> Result<()> { + let mut pack = self.get_pack(pack_id).await?.ok_or_else(|| { + StorageError::NotFound(format!("Pack not found: {}", hex::encode(pack_id))) + })?; + + let old_count = pack.agent_count(); + pack.remove_agent(agent_id); + let new_count = pack.agent_count(); + + let serialized = Self::serialize_pack(&pack)?; + let key = Self::trust_pack_key(pack_id); + self.store.put(&key, &serialized).await?; + + debug!(old_count, new_count, removed = new_count < old_count, "Updated pack membership"); + + Ok(()) + } + + #[instrument(skip(self), fields(pack_id = %hex::encode(pack_id), agent_id = %hex::encode(agent_id)))] + async fn is_agent_in_pack(&self, pack_id: &PackId, agent_id: &[u8; 32]) -> Result { + match self.get_pack(pack_id).await? { + Some(pack) => { + let is_member = pack.contains_agent(agent_id); + debug!(is_member, "Checked pack membership"); + Ok(is_member) + } + None => { + debug!("Pack not found, returning false"); + Ok(false) + } + } + } + + #[instrument(skip(self))] + async fn list_packs(&self) -> Result> { + let prefix = TRUST_PACK_PREFIX.to_vec(); + let entries = self.store.scan_prefix(&prefix).await?; + + let pack_ids: Vec = entries + .into_iter() + .filter_map(|(key, _data)| { + // Extract pack_id from key: "TP:{pack_id}" + if key.len() == TRUST_PACK_PREFIX.len() + 32 { + let mut pack_id = [0u8; 32]; + pack_id.copy_from_slice(&key[TRUST_PACK_PREFIX.len()..]); + Some(pack_id) + } else { + None + } + }) + .collect(); + + debug!(count = pack_ids.len(), "Listed TrustPacks"); + Ok(pack_ids) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::SledStore; + + fn create_test_pack(id: PackId, name: &str, maintainer: [u8; 32]) -> TrustPack { + TrustPack::new(id, name.to_string(), maintainer) + } + + #[tokio::test] + async fn test_put_and_get_pack() { + let store = SledStore::open_temp().expect("Failed to create store"); + let pack_store = GenericTrustPackStore::new(store); + + let pack_id = [1u8; 32]; + let maintainer = [2u8; 32]; + let pack = create_test_pack(pack_id, "Test_Pack", maintainer); + + // Put pack + let returned_id = pack_store.put_pack(&pack).await.expect("Failed to put pack"); + assert_eq!(returned_id, pack_id); + + // Get pack back + let retrieved = pack_store.get_pack(&pack_id).await.expect("Failed to get pack"); + + assert!(retrieved.is_some()); + let retrieved_pack = retrieved.expect("Pack should exist"); + assert_eq!(retrieved_pack.id, pack_id); + assert_eq!(retrieved_pack.name, "Test_Pack"); + assert_eq!(retrieved_pack.maintainer, maintainer); + } + + #[tokio::test] + async fn test_add_agent_idempotent() { + let store = SledStore::open_temp().expect("Failed to create store"); + let pack_store = GenericTrustPackStore::new(store); + + let pack_id = [2u8; 32]; + let pack = create_test_pack(pack_id, "Agent_Pack", [3u8; 32]); + pack_store.put_pack(&pack).await.expect("put"); + + let agent_id = [10u8; 32]; + + // Add agent first time + pack_store.add_agent_to_pack(&pack_id, &agent_id).await.expect("add"); + let pack = pack_store.get_pack(&pack_id).await.expect("get").expect("pack exists"); + assert_eq!(pack.agent_count(), 1); + assert!(pack.contains_agent(&agent_id)); + + // Add same agent again (idempotent) + pack_store.add_agent_to_pack(&pack_id, &agent_id).await.expect("add"); + let pack = pack_store.get_pack(&pack_id).await.expect("get").expect("pack exists"); + assert_eq!(pack.agent_count(), 1, "Should still have only 1 agent"); + } + + #[tokio::test] + async fn test_remove_agent() { + let store = SledStore::open_temp().expect("Failed to create store"); + let pack_store = GenericTrustPackStore::new(store); + + let pack_id = [3u8; 32]; + let mut pack = create_test_pack(pack_id, "Remove_Pack", [4u8; 32]); + + let agent1 = [20u8; 32]; + let agent2 = [21u8; 32]; + pack.add_agent(agent1); + pack.add_agent(agent2); + + pack_store.put_pack(&pack).await.expect("put"); + + // Remove agent1 + pack_store.remove_agent_from_pack(&pack_id, &agent1).await.expect("remove"); + + let pack = pack_store.get_pack(&pack_id).await.expect("get").expect("pack exists"); + assert_eq!(pack.agent_count(), 1); + assert!(!pack.contains_agent(&agent1)); + assert!(pack.contains_agent(&agent2)); + + // Remove non-existent agent (no-op) + let agent3 = [22u8; 32]; + pack_store.remove_agent_from_pack(&pack_id, &agent3).await.expect("remove"); + let pack = pack_store.get_pack(&pack_id).await.expect("get").expect("pack exists"); + assert_eq!(pack.agent_count(), 1, "Count should be unchanged"); + } + + #[tokio::test] + async fn test_contains_agent() { + let store = SledStore::open_temp().expect("Failed to create store"); + let pack_store = GenericTrustPackStore::new(store); + + let pack_id = [4u8; 32]; + let mut pack = create_test_pack(pack_id, "Contains_Pack", [5u8; 32]); + + let agent = [30u8; 32]; + pack.add_agent(agent); + pack_store.put_pack(&pack).await.expect("put"); + + // Check present agent + let is_member = pack_store.is_agent_in_pack(&pack_id, &agent).await.expect("check"); + assert!(is_member); + + // Check absent agent + let other_agent = [31u8; 32]; + let is_member = pack_store.is_agent_in_pack(&pack_id, &other_agent).await.expect("check"); + assert!(!is_member); + } + + #[tokio::test] + async fn test_list_packs() { + let store = SledStore::open_temp().expect("Failed to create store"); + let pack_store = GenericTrustPackStore::new(store); + + // Initially empty + let packs = pack_store.list_packs().await.expect("list"); + assert!(packs.is_empty()); + + // Add several packs + for i in 0..5 { + let pack_id = [i; 32]; + let pack = create_test_pack(pack_id, &format!("Pack_{}", i), [i + 100; 32]); + pack_store.put_pack(&pack).await.expect("put"); + } + + // List all packs + let packs = pack_store.list_packs().await.expect("list"); + assert_eq!(packs.len(), 5); + + // Verify IDs are correct + for i in 0..5 { + let expected_id = [i; 32]; + assert!(packs.contains(&expected_id), "Should contain pack {}", i); + } + } + + #[tokio::test] + async fn test_missing_pack_returns_none() { + let store = SledStore::open_temp().expect("Failed to create store"); + let pack_store = GenericTrustPackStore::new(store); + + let nonexistent_id = [99u8; 32]; + + // Get non-existent pack + let result = pack_store.get_pack(&nonexistent_id).await.expect("get"); + assert!(result.is_none(), "Should return None, not error"); + + // is_agent_in_pack returns false for non-existent pack + let agent = [1u8; 32]; + let is_member = pack_store.is_agent_in_pack(&nonexistent_id, &agent).await.expect("check"); + assert!(!is_member, "Should return false for non-existent pack"); + } + + #[tokio::test] + async fn test_add_to_missing_pack_errors() { + let store = SledStore::open_temp().expect("Failed to create store"); + let pack_store = GenericTrustPackStore::new(store); + + let nonexistent_id = [98u8; 32]; + let agent = [1u8; 32]; + + // Attempting to add agent to non-existent pack should error + let result = pack_store.add_agent_to_pack(&nonexistent_id, &agent).await; + assert!(result.is_err(), "Should error when pack doesn't exist"); + } + + #[tokio::test] + async fn test_remove_from_missing_pack_errors() { + let store = SledStore::open_temp().expect("Failed to create store"); + let pack_store = GenericTrustPackStore::new(store); + + let nonexistent_id = [97u8; 32]; + let agent = [1u8; 32]; + + // Attempting to remove agent from non-existent pack should error + let result = pack_store.remove_agent_from_pack(&nonexistent_id, &agent).await; + assert!(result.is_err(), "Should error when pack doesn't exist"); + } + + #[tokio::test] + async fn test_serialization_roundtrip() { + let pack_id = [42u8; 32]; + let maintainer = [43u8; 32]; + let mut original = create_test_pack(pack_id, "Roundtrip_Pack", maintainer); + + original.add_agent([1u8; 32]); + original.add_agent([2u8; 32]); + original.add_agent([3u8; 32]); + + let serialized = + GenericTrustPackStore::::serialize_pack(&original).expect("serialize"); + let deserialized = + GenericTrustPackStore::::deserialize_pack(&serialized).expect("deserialize"); + + assert_eq!(original, deserialized); + assert_eq!(deserialized.agent_count(), 3); + } + + #[tokio::test] + async fn test_multiple_agents() { + let store = SledStore::open_temp().expect("Failed to create store"); + let pack_store = GenericTrustPackStore::new(store); + + let pack_id = [5u8; 32]; + let pack = create_test_pack(pack_id, "Multi_Agent_Pack", [6u8; 32]); + pack_store.put_pack(&pack).await.expect("put"); + + // Add multiple agents + for i in 40..50 { + let agent = [i; 32]; + pack_store.add_agent_to_pack(&pack_id, &agent).await.expect("add"); + } + + let pack = pack_store.get_pack(&pack_id).await.expect("get").expect("pack exists"); + assert_eq!(pack.agent_count(), 10); + + // Verify all agents are present + for i in 40..50 { + let agent = [i; 32]; + assert!(pack.contains_agent(&agent), "Should contain agent {}", i); + } + } +} diff --git a/crates/stemedb-storage/src/trust_rank_store.rs b/crates/stemedb-storage/src/trust_rank_store.rs new file mode 100644 index 0000000..b754879 --- /dev/null +++ b/crates/stemedb-storage/src/trust_rank_store.rs @@ -0,0 +1,617 @@ +//! Specialized storage for TrustRank reputation scores. +//! +//! The TrustRank system tracks per-agent reputation scores that affect how +//! their assertions are weighted in the Authority lens. This is the foundation +//! of "The Hive" learning loop. +//! +//! # Storage Layout +//! +//! | Key Pattern | Value | Purpose | +//! |-------------|-------|---------| +//! | `TR:{agent_id}` | Serialized TrustRank | Agent reputation data | +//! +//! # Design Philosophy +//! +//! This module follows the "Deep Module" principle from Philosophy of Software Design: +//! - Simple interface hiding complex reputation tracking +//! - Content-addressed agent IDs (public keys) +//! - Decay mechanics for confidence half-life +//! - Learning loop integration for accuracy tracking +//! +//! All operations are defensive against missing data (new agents start at default score). + +use crate::error::Result; +use crate::traits::KVStore; +use async_trait::async_trait; +use tracing::{debug, instrument}; + +/// Key prefix for TrustRank entries. +const TRUST_RANK_PREFIX: &[u8] = b"TR:"; + +/// Default TrustRank score for new agents. +const DEFAULT_TRUST_SCORE: f32 = 0.5; + +/// Default half-life for confidence decay (30 days in seconds). +const DEFAULT_HALF_LIFE_SECONDS: u64 = 30 * 24 * 60 * 60; + +/// TrustRank reputation data for an agent. +/// +/// This struct tracks the reputation score and learning metrics for a single agent. +/// All fields are updated atomically when reputation changes. +/// +/// # Invariants +/// +/// - `score` is always in range [0.0, 1.0] +/// - `last_updated` is Unix timestamp (seconds since epoch) +/// - `assertions_count >= accuracy_count` (can't be accurate more than total) +#[derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize, Debug, Clone, PartialEq)] +#[archive(check_bytes)] +pub struct TrustRank { + /// The agent's Ed25519 public key. + pub agent_id: [u8; 32], + /// Reputation score (0.0 to 1.0). + pub score: f32, + /// Unix timestamp of last update (seconds since epoch). + pub last_updated: u64, + /// Total number of assertions made by this agent. + pub assertions_count: u64, + /// Number of assertions that were deemed accurate. + pub accuracy_count: u64, +} + +impl TrustRank { + /// Create a new TrustRank for an agent with default initial score. + pub fn new(agent_id: [u8; 32], timestamp: u64) -> Self { + Self { + agent_id, + score: DEFAULT_TRUST_SCORE, + last_updated: timestamp, + assertions_count: 0, + accuracy_count: 0, + } + } + + /// Apply confidence half-life decay to the score. + /// + /// Formula: `score = score * (0.5 ^ (elapsed_days / half_life_days))` + /// + /// # Arguments + /// * `current_timestamp` - Current Unix timestamp in seconds + /// * `half_life_seconds` - Half-life duration in seconds + /// + /// # Returns + /// The decayed score, clamped to [0.0, 1.0] + pub fn apply_decay(&mut self, current_timestamp: u64, half_life_seconds: u64) -> f32 { + if current_timestamp <= self.last_updated { + return self.score; + } + + let elapsed_seconds = current_timestamp - self.last_updated; + let elapsed_days = elapsed_seconds as f64 / (24.0 * 60.0 * 60.0); + let half_life_days = half_life_seconds as f64 / (24.0 * 60.0 * 60.0); + + let decay_factor = 0.5_f64.powf(elapsed_days / half_life_days); + self.score = (self.score as f64 * decay_factor).clamp(0.0, 1.0) as f32; + self.last_updated = current_timestamp; + + self.score + } + + /// Update the score by a delta, clamping to [0.0, 1.0]. + /// + /// # Arguments + /// * `delta` - Amount to add to the score (can be negative) + /// * `timestamp` - Timestamp of this update + /// + /// # Returns + /// The new score after update and clamping + pub fn adjust_score(&mut self, delta: f32, timestamp: u64) -> f32 { + self.score = (self.score + delta).clamp(0.0, 1.0); + self.last_updated = timestamp; + self.score + } + + /// Record an assertion outcome for learning loop tracking. + /// + /// # Arguments + /// * `was_accurate` - Whether the assertion was correct + pub fn record_outcome(&mut self, was_accurate: bool) { + self.assertions_count = self.assertions_count.saturating_add(1); + if was_accurate { + self.accuracy_count = self.accuracy_count.saturating_add(1); + } + } + + /// Calculate the agent's accuracy rate. + /// + /// # Returns + /// Accuracy rate in [0.0, 1.0], or 0.0 if no assertions have been made + pub fn accuracy_rate(&self) -> f32 { + if self.assertions_count == 0 { + return 0.0; + } + self.accuracy_count as f32 / self.assertions_count as f32 + } +} + +/// Specialized storage trait for TrustRank operations. +/// +/// This trait provides reputation-specific operations on top of a generic KVStore, +/// enabling efficient trust score management for The Hive learning loop. +/// +/// # Example +/// +/// ```ignore +/// let trust_store = GenericTrustRankStore::new(kv_store); +/// let trust = trust_store.get_trust_rank(&agent_id).await?; +/// trust_store.update_trust_rank(&agent_id, 0.1, timestamp).await?; +/// ``` +#[async_trait] +pub trait TrustRankStore: Send + Sync { + /// Get the TrustRank for an agent. + /// + /// If the agent has no stored TrustRank, returns a new default instance. + /// + /// # Arguments + /// * `agent_id` - The agent's Ed25519 public key + /// + /// # Returns + /// The agent's TrustRank, or a default instance for new agents + async fn get_trust_rank(&self, agent_id: &[u8; 32]) -> Result; + + /// Update an agent's TrustRank score by a delta. + /// + /// This operation: + /// 1. Loads current TrustRank (or creates default) + /// 2. Applies the delta adjustment + /// 3. Stores the updated TrustRank + /// + /// # Arguments + /// * `agent_id` - The agent's Ed25519 public key + /// * `delta` - Amount to add to the score (can be negative) + /// * `timestamp` - Unix timestamp of this update + /// + /// # Returns + /// The new score after update + async fn update_trust_rank( + &self, + agent_id: &[u8; 32], + delta: f32, + timestamp: u64, + ) -> Result; + + /// Apply confidence half-life decay to all stored TrustRanks. + /// + /// Scans all TrustRank entries and applies decay based on elapsed time. + /// This should be run periodically (e.g., daily) to decay stale reputations. + /// + /// # Arguments + /// * `current_timestamp` - Current Unix timestamp in seconds + /// * `half_life_seconds` - Half-life duration (default: 30 days) + /// + /// # Returns + /// Number of TrustRanks that were decayed + async fn decay_trust_ranks( + &self, + current_timestamp: u64, + half_life_seconds: Option, + ) -> Result; + + /// Record an assertion outcome for learning loop tracking. + /// + /// Updates the agent's accuracy metrics and adjusts their score based on + /// the outcome. Accurate predictions increase reputation, inaccurate ones decrease it. + /// + /// # Arguments + /// * `agent_id` - The agent's Ed25519 public key + /// * `was_accurate` - Whether the assertion was correct + /// * `timestamp` - Unix timestamp of this outcome + /// + /// # Returns + /// The new trust score after recording the outcome + async fn record_outcome( + &self, + agent_id: &[u8; 32], + was_accurate: bool, + timestamp: u64, + ) -> Result; + + /// Store a TrustRank directly (for testing or batch operations). + /// + /// # Arguments + /// * `trust_rank` - The TrustRank to store + async fn put_trust_rank(&self, trust_rank: &TrustRank) -> Result<()>; +} + +/// TrustRankStore implementation backed by a generic KVStore. +/// +/// This implementation stores TrustRank data at `TR:{agent_id}` and provides +/// all operations for reputation management. +pub struct GenericTrustRankStore { + store: S, +} + +impl GenericTrustRankStore { + /// Create a new TrustRankStore backed by the given KVStore. + pub fn new(store: S) -> Self { + Self { store } + } + + /// Construct the key for a TrustRank entry. + fn trust_rank_key(agent_id: &[u8; 32]) -> Vec { + let mut key = TRUST_RANK_PREFIX.to_vec(); + key.extend_from_slice(agent_id); + key + } + + /// Serialize a TrustRank using the canonical serde helpers. + fn serialize_trust_rank(trust_rank: &TrustRank) -> Result> { + crate::serde_helpers::serialize(trust_rank) + } + + /// Deserialize a TrustRank using the canonical serde helpers. + fn deserialize_trust_rank(data: &[u8]) -> Result { + crate::serde_helpers::deserialize(data) + } +} + +#[async_trait] +impl TrustRankStore for GenericTrustRankStore { + #[instrument(skip(self), fields(agent_id = %hex::encode(agent_id)))] + async fn get_trust_rank(&self, agent_id: &[u8; 32]) -> Result { + let key = Self::trust_rank_key(agent_id); + match self.store.get(&key).await? { + Some(data) => { + let trust_rank = Self::deserialize_trust_rank(&data)?; + debug!(score = trust_rank.score, "Retrieved TrustRank"); + Ok(trust_rank) + } + None => { + // New agent, return default + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + let trust_rank = TrustRank::new(*agent_id, now); + debug!(score = trust_rank.score, "Created default TrustRank for new agent"); + Ok(trust_rank) + } + } + } + + #[instrument(skip(self), fields(agent_id = %hex::encode(agent_id), delta))] + async fn update_trust_rank( + &self, + agent_id: &[u8; 32], + delta: f32, + timestamp: u64, + ) -> Result { + let mut trust_rank = self.get_trust_rank(agent_id).await?; + let new_score = trust_rank.adjust_score(delta, timestamp); + + let serialized = Self::serialize_trust_rank(&trust_rank)?; + let key = Self::trust_rank_key(agent_id); + self.store.put(&key, &serialized).await?; + + debug!(new_score, "Updated TrustRank"); + Ok(new_score) + } + + #[instrument(skip(self), fields(current_timestamp, half_life_seconds))] + async fn decay_trust_ranks( + &self, + current_timestamp: u64, + half_life_seconds: Option, + ) -> Result { + let half_life = half_life_seconds.unwrap_or(DEFAULT_HALF_LIFE_SECONDS); + let prefix = TRUST_RANK_PREFIX.to_vec(); + let entries = self.store.scan_prefix(&prefix).await?; + + let mut decayed_count = 0; + + for (key, data) in entries { + let mut trust_rank = Self::deserialize_trust_rank(&data)?; + let old_score = trust_rank.score; + trust_rank.apply_decay(current_timestamp, half_life); + + // Only update if score actually changed + if (trust_rank.score - old_score).abs() > f32::EPSILON { + let serialized = Self::serialize_trust_rank(&trust_rank)?; + self.store.put(&key, &serialized).await?; + decayed_count += 1; + + debug!( + agent_id = %hex::encode(trust_rank.agent_id), + old_score, + new_score = trust_rank.score, + "Decayed TrustRank" + ); + } + } + + debug!(decayed_count, "Completed TrustRank decay"); + Ok(decayed_count) + } + + #[instrument(skip(self), fields(agent_id = %hex::encode(agent_id), was_accurate))] + async fn record_outcome( + &self, + agent_id: &[u8; 32], + was_accurate: bool, + timestamp: u64, + ) -> Result { + let mut trust_rank = self.get_trust_rank(agent_id).await?; + + // Record the outcome + trust_rank.record_outcome(was_accurate); + + // Adjust score based on accuracy + // Accurate: +0.05, Inaccurate: -0.1 (penalty is higher to discourage spam) + let delta = if was_accurate { 0.05 } else { -0.1 }; + let new_score = trust_rank.adjust_score(delta, timestamp); + + let serialized = Self::serialize_trust_rank(&trust_rank)?; + let key = Self::trust_rank_key(agent_id); + self.store.put(&key, &serialized).await?; + + debug!( + new_score, + accuracy_rate = trust_rank.accuracy_rate(), + "Recorded outcome and updated TrustRank" + ); + Ok(new_score) + } + + #[instrument(skip(self, trust_rank), fields(agent_id = %hex::encode(trust_rank.agent_id)))] + async fn put_trust_rank(&self, trust_rank: &TrustRank) -> Result<()> { + let serialized = Self::serialize_trust_rank(trust_rank)?; + let key = Self::trust_rank_key(&trust_rank.agent_id); + self.store.put(&key, &serialized).await?; + debug!(score = trust_rank.score, "Stored TrustRank"); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::SledStore; + + #[test] + fn test_trust_rank_new() { + let agent_id = [1u8; 32]; + let trust = TrustRank::new(agent_id, 1000); + + assert_eq!(trust.agent_id, agent_id); + assert_eq!(trust.score, DEFAULT_TRUST_SCORE); + assert_eq!(trust.last_updated, 1000); + assert_eq!(trust.assertions_count, 0); + assert_eq!(trust.accuracy_count, 0); + } + + #[test] + fn test_adjust_score_clamping() { + let mut trust = TrustRank::new([1u8; 32], 1000); + + // Add positive delta + let score = trust.adjust_score(0.3, 2000); + assert_eq!(score, 0.8); + + // Add too much, should clamp to 1.0 + let score = trust.adjust_score(0.5, 3000); + assert_eq!(score, 1.0); + + // Subtract too much, should clamp to 0.0 + let score = trust.adjust_score(-2.0, 4000); + assert_eq!(score, 0.0); + } + + #[test] + fn test_record_outcome() { + let mut trust = TrustRank::new([1u8; 32], 1000); + + trust.record_outcome(true); + assert_eq!(trust.assertions_count, 1); + assert_eq!(trust.accuracy_count, 1); + assert_eq!(trust.accuracy_rate(), 1.0); + + trust.record_outcome(false); + assert_eq!(trust.assertions_count, 2); + assert_eq!(trust.accuracy_count, 1); + assert_eq!(trust.accuracy_rate(), 0.5); + + trust.record_outcome(true); + assert_eq!(trust.assertions_count, 3); + assert_eq!(trust.accuracy_count, 2); + assert!((trust.accuracy_rate() - 0.666666).abs() < 0.001); + } + + #[test] + fn test_apply_decay() { + let mut trust = TrustRank::new([1u8; 32], 1000); + trust.score = 1.0; // Start at max + + // 30 days later (one half-life) + let thirty_days = 30 * 24 * 60 * 60; + let decayed = trust.apply_decay(1000 + thirty_days, DEFAULT_HALF_LIFE_SECONDS); + + // Should be approximately 0.5 + assert!((decayed - 0.5).abs() < 0.01); + + // 60 days later (two half-lives) + let sixty_days = 60 * 24 * 60 * 60; + trust.score = 1.0; // Reset + trust.last_updated = 1000; + let decayed = trust.apply_decay(1000 + sixty_days, DEFAULT_HALF_LIFE_SECONDS); + + // Should be approximately 0.25 + assert!((decayed - 0.25).abs() < 0.01); + } + + #[test] + fn test_decay_no_time_elapsed() { + let mut trust = TrustRank::new([1u8; 32], 1000); + trust.score = 0.8; + + let decayed = trust.apply_decay(1000, DEFAULT_HALF_LIFE_SECONDS); + + // No time elapsed, score should be unchanged + assert_eq!(decayed, 0.8); + } + + #[tokio::test] + async fn test_get_default_trust_rank() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = GenericTrustRankStore::new(store); + + let agent_id = [1u8; 32]; + let trust = trust_store.get_trust_rank(&agent_id).await.expect("get"); + + assert_eq!(trust.agent_id, agent_id); + assert_eq!(trust.score, DEFAULT_TRUST_SCORE); + } + + #[tokio::test] + async fn test_put_and_get_trust_rank() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = GenericTrustRankStore::new(store); + + let agent_id = [2u8; 32]; + let mut trust = TrustRank::new(agent_id, 1000); + trust.score = 0.75; + + trust_store.put_trust_rank(&trust).await.expect("put"); + + let retrieved = trust_store.get_trust_rank(&agent_id).await.expect("get"); + + assert_eq!(retrieved.score, 0.75); + assert_eq!(retrieved.agent_id, agent_id); + } + + #[tokio::test] + async fn test_update_trust_rank() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = GenericTrustRankStore::new(store); + + let agent_id = [3u8; 32]; + + // First update creates default + let score = trust_store.update_trust_rank(&agent_id, 0.2, 1000).await.expect("update"); + assert!((score - 0.7).abs() < f32::EPSILON); // 0.5 + 0.2 + + // Second update modifies existing + let score = trust_store.update_trust_rank(&agent_id, -0.3, 2000).await.expect("update"); + assert!((score - 0.4).abs() < 0.001); // 0.7 - 0.3 + } + + #[tokio::test] + async fn test_record_outcome_updates_score() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = GenericTrustRankStore::new(store); + + let agent_id = [4u8; 32]; + + // Record accurate outcome + let score = trust_store.record_outcome(&agent_id, true, 1000).await.expect("record"); + assert!((score - 0.55).abs() < 0.001); // 0.5 + 0.05 + + // Record inaccurate outcome + let score = trust_store.record_outcome(&agent_id, false, 2000).await.expect("record"); + assert!((score - 0.45).abs() < 0.001); // 0.55 - 0.1 + + // Verify accuracy tracking + let trust = trust_store.get_trust_rank(&agent_id).await.expect("get"); + assert_eq!(trust.assertions_count, 2); + assert_eq!(trust.accuracy_count, 1); + assert_eq!(trust.accuracy_rate(), 0.5); + } + + #[tokio::test] + async fn test_decay_trust_ranks() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = GenericTrustRankStore::new(store); + + // Create several agents with different scores + for i in 0..5 { + let agent_id = [i; 32]; + let mut trust = TrustRank::new(agent_id, 1000); + trust.score = 0.8; + trust_store.put_trust_rank(&trust).await.expect("put"); + } + + // Apply decay after 30 days (one half-life) + let thirty_days = 30 * 24 * 60 * 60; + let decayed_count = + trust_store.decay_trust_ranks(1000 + thirty_days, None).await.expect("decay"); + + assert_eq!(decayed_count, 5); + + // Verify all scores were decayed + for i in 0..5 { + let agent_id = [i; 32]; + let trust = trust_store.get_trust_rank(&agent_id).await.expect("get"); + // 0.8 * 0.5 = 0.4 + assert!((trust.score - 0.4).abs() < 0.01); + } + } + + #[tokio::test] + async fn test_decay_no_change_skips_update() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = GenericTrustRankStore::new(store); + + let agent_id = [5u8; 32]; + let trust = TrustRank::new(agent_id, 1000); + trust_store.put_trust_rank(&trust).await.expect("put"); + + // No time elapsed, should not update + let decayed_count = trust_store.decay_trust_ranks(1000, None).await.expect("decay"); + + assert_eq!(decayed_count, 0); + } + + #[tokio::test] + async fn test_serialization_roundtrip() { + let original = TrustRank { + agent_id: [42u8; 32], + score: 0.75, + last_updated: 123456, + assertions_count: 100, + accuracy_count: 85, + }; + + let serialized = + GenericTrustRankStore::::serialize_trust_rank(&original).expect("serialize"); + let deserialized = GenericTrustRankStore::::deserialize_trust_rank(&serialized) + .expect("deserialize"); + + assert_eq!(original, deserialized); + } + + #[tokio::test] + async fn test_custom_half_life() { + let store = SledStore::open_temp().expect("Failed to create store"); + let trust_store = GenericTrustRankStore::new(store); + + let agent_id = [6u8; 32]; + let mut trust = TrustRank::new(agent_id, 1000); + trust.score = 1.0; + trust_store.put_trust_rank(&trust).await.expect("put"); + + // Use 60-day half-life instead of 30 + let sixty_day_half_life = 60 * 24 * 60 * 60; + let thirty_days = 30 * 24 * 60 * 60; + + let decayed_count = trust_store + .decay_trust_ranks(1000 + thirty_days, Some(sixty_day_half_life)) + .await + .expect("decay"); + + assert_eq!(decayed_count, 1); + + let trust = trust_store.get_trust_rank(&agent_id).await.expect("get"); + + // After 30 days with 60-day half-life, should be ~0.707 (2^(-0.5)) + assert!((trust.score - 0.707).abs() < 0.01); + } +} diff --git a/crates/stemedb-storage/src/vote_store.rs b/crates/stemedb-storage/src/vote_store.rs new file mode 100644 index 0000000..13b617e --- /dev/null +++ b/crates/stemedb-storage/src/vote_store.rs @@ -0,0 +1,526 @@ +//! Specialized storage for high-velocity vote ingestion. +//! +//! The Ballot Box pattern separates votes from assertions to enable +//! thousands of agents to vote simultaneously without lock contention. +//! +//! # Storage Layout +//! +//! | Key Pattern | Value | Purpose | +//! |-------------|-------|---------| +//! | `V:{assertion_hash}:{vote_hash}` | Serialized Vote | Individual votes | +//! | `VC:{assertion_hash}` | u64 (LE) | Vote count cache | +//! | `VW:{assertion_hash}` | f32 (LE) | Aggregate weight cache | +//! +//! # Design Philosophy +//! +//! This module follows the "Deep Module" principle from Philosophy of Software Design: +//! - Simple interface hiding complex vote aggregation +//! - O(1) vote counts via counter cache +//! - Pre-calculated aggregate weights for Materialized Views +//! +//! All operations are append-only and content-addressed. + +use crate::error::{Result, StorageError}; +use crate::traits::KVStore; +use async_trait::async_trait; +use stemedb_core::types::{Hash, Vote}; +use tracing::{debug, instrument}; + +/// Key prefix for individual votes. +#[allow(dead_code)] // Documented for reference; actual key construction uses format!() +const VOTE_PREFIX: &[u8] = b"V:"; +/// Key prefix for vote count cache. +const VOTE_COUNT_PREFIX: &[u8] = b"VC:"; +/// Key prefix for aggregate weight cache. +const VOTE_WEIGHT_PREFIX: &[u8] = b"VW:"; + +/// Specialized storage trait for high-velocity vote operations. +/// +/// This trait provides vote-specific operations on top of a generic KVStore, +/// enabling efficient vote ingestion and aggregation for the Ballot Box pattern. +/// +/// # Example +/// +/// ```ignore +/// let vote_store = SledVoteStore::new(kv_store); +/// let vote_hash = vote_store.put_vote(&vote).await?; +/// let votes = vote_store.get_votes_for_assertion(&assertion_hash).await?; +/// ``` +#[async_trait] +pub trait VoteStore: Send + Sync { + /// Store a vote and return its content-addressed hash. + /// + /// This operation: + /// 1. Serializes the vote using rkyv + /// 2. Computes BLAKE3 hash for content addressing + /// 3. Stores at `V:{assertion_hash}:{vote_hash}` + /// 4. Updates vote count and aggregate weight caches + /// + /// # Returns + /// The BLAKE3 hash of the serialized vote (content address). + async fn put_vote(&self, vote: &Vote) -> Result; + + /// Get a specific vote by its hash. + /// + /// # Arguments + /// * `assertion_hash` - The assertion this vote is for + /// * `vote_hash` - The content-addressed hash of the vote + /// + /// # Returns + /// The vote if found, None otherwise. + async fn get_vote(&self, assertion_hash: &Hash, vote_hash: &Hash) -> Result>; + + /// Get all votes for a specific assertion. + /// + /// Scans all keys with prefix `V:{assertion_hash}:` and deserializes. + /// + /// # Performance + /// O(n) where n is the number of votes. For high-cardinality assertions, + /// consider using `get_vote_count` and `get_aggregate_weight` instead. + /// + /// # Returns + /// Vector of votes, empty if no votes exist. + async fn get_votes_for_assertion(&self, assertion_hash: &Hash) -> Result>; + + /// Get the number of votes for an assertion. + /// + /// Uses cached counter at `VC:{assertion_hash}` for O(1) performance. + /// + /// # Returns + /// Vote count, 0 if no votes exist. + async fn get_vote_count(&self, assertion_hash: &Hash) -> Result; + + /// Get the aggregate weight (sum of all vote weights) for an assertion. + /// + /// Uses cached value at `VW:{assertion_hash}` for O(1) performance. + /// The weight is the sum of all `vote.weight` values. + /// + /// # Returns + /// Aggregate weight, 0.0 if no votes exist. + async fn get_aggregate_weight(&self, assertion_hash: &Hash) -> Result; + + /// Check if any votes exist for an assertion. + /// + /// More efficient than `get_vote_count() > 0` as it can short-circuit. + async fn has_votes(&self, assertion_hash: &Hash) -> Result; +} + +/// VoteStore implementation backed by a generic KVStore. +/// +/// This implementation maintains caches for vote counts and aggregate weights +/// to enable O(1) lookups for the Materializer. +pub struct GenericVoteStore { + store: S, +} + +impl GenericVoteStore { + /// Create a new VoteStore backed by the given KVStore. + pub fn new(store: S) -> Self { + Self { store } + } + + /// Construct the key for an individual vote. + fn vote_key(assertion_hash: &Hash, vote_hash: &Hash) -> Vec { + let assertion_hex = hex::encode(assertion_hash); + let vote_hex = hex::encode(vote_hash); + format!("V:{}:{}", assertion_hex, vote_hex).into_bytes() + } + + /// Construct the prefix for scanning all votes on an assertion. + fn vote_scan_prefix(assertion_hash: &Hash) -> Vec { + let assertion_hex = hex::encode(assertion_hash); + format!("V:{}:", assertion_hex).into_bytes() + } + + /// Construct the key for the vote count cache. + fn vote_count_key(assertion_hash: &Hash) -> Vec { + let mut key = VOTE_COUNT_PREFIX.to_vec(); + key.extend_from_slice(assertion_hash); + key + } + + /// Construct the key for the aggregate weight cache. + fn vote_weight_key(assertion_hash: &Hash) -> Vec { + let mut key = VOTE_WEIGHT_PREFIX.to_vec(); + key.extend_from_slice(assertion_hash); + key + } + + /// Serialize a vote using the canonical serde helpers. + fn serialize_vote(vote: &Vote) -> Result> { + crate::serde_helpers::serialize(vote) + } + + /// Deserialize a vote using the canonical serde helpers. + fn deserialize_vote(data: &[u8]) -> Result { + crate::serde_helpers::deserialize(data) + } +} + +#[async_trait] +impl VoteStore for GenericVoteStore { + #[instrument(skip(self, vote), fields(assertion_hash = %hex::encode(vote.assertion_hash), weight = vote.weight))] + async fn put_vote(&self, vote: &Vote) -> Result { + // Serialize the vote + let serialized = Self::serialize_vote(vote)?; + + // Compute content-addressed hash + let vote_hash_bytes = blake3::hash(&serialized); + let vote_hash: Hash = *vote_hash_bytes.as_bytes(); + + // Store the vote + let key = Self::vote_key(&vote.assertion_hash, &vote_hash); + self.store.put(&key, &serialized).await?; + + debug!( + vote_hash = %hex::encode(vote_hash), + "Stored vote" + ); + + // Update vote count cache (atomic increment - prevents race conditions) + let count_key = Self::vote_count_key(&vote.assertion_hash); + let new_count = self.store.fetch_and_add_u64(&count_key, 1).await?; + + // Update aggregate weight cache (atomic CAS - prevents race conditions) + let weight_key = Self::vote_weight_key(&vote.assertion_hash); + let vote_weight = vote.weight; + let new_weight = self + .store + .compare_and_swap_f32(&weight_key, move |current| current + vote_weight) + .await?; + + debug!(new_count, new_weight, "Updated vote caches (atomic)"); + + Ok(vote_hash) + } + + #[instrument(skip(self), fields(assertion_hash = %hex::encode(assertion_hash), vote_hash = %hex::encode(vote_hash)))] + async fn get_vote(&self, assertion_hash: &Hash, vote_hash: &Hash) -> Result> { + let key = Self::vote_key(assertion_hash, vote_hash); + match self.store.get(&key).await? { + Some(data) => { + let vote = Self::deserialize_vote(&data)?; + Ok(Some(vote)) + } + None => Ok(None), + } + } + + #[instrument(skip(self), fields(assertion_hash = %hex::encode(assertion_hash)))] + async fn get_votes_for_assertion(&self, assertion_hash: &Hash) -> Result> { + let prefix = Self::vote_scan_prefix(assertion_hash); + let entries = self.store.scan_prefix(&prefix).await?; + + let mut votes = Vec::with_capacity(entries.len()); + for (_key, data) in entries { + let vote = Self::deserialize_vote(&data)?; + votes.push(vote); + } + + debug!(count = votes.len(), "Retrieved votes for assertion"); + Ok(votes) + } + + #[instrument(skip(self), fields(assertion_hash = %hex::encode(assertion_hash)))] + async fn get_vote_count(&self, assertion_hash: &Hash) -> Result { + let key = Self::vote_count_key(assertion_hash); + match self.store.get(&key).await? { + Some(bytes) if bytes.len() == 8 => { + let arr: [u8; 8] = bytes.try_into().map_err(|_| { + StorageError::Serialization("Invalid vote count bytes".to_string()) + })?; + Ok(u64::from_le_bytes(arr)) + } + _ => Ok(0), + } + } + + #[instrument(skip(self), fields(assertion_hash = %hex::encode(assertion_hash)))] + async fn get_aggregate_weight(&self, assertion_hash: &Hash) -> Result { + let key = Self::vote_weight_key(assertion_hash); + match self.store.get(&key).await? { + Some(bytes) if bytes.len() == 4 => { + let arr: [u8; 4] = bytes + .try_into() + .map_err(|_| StorageError::Serialization("Invalid weight bytes".to_string()))?; + Ok(f32::from_le_bytes(arr)) + } + _ => Ok(0.0), + } + } + + #[instrument(skip(self), fields(assertion_hash = %hex::encode(assertion_hash)))] + async fn has_votes(&self, assertion_hash: &Hash) -> Result { + let count = self.get_vote_count(assertion_hash).await?; + Ok(count > 0) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::SledStore; + use std::sync::Arc; + + fn create_test_vote(assertion_hash: Hash, weight: f32) -> Vote { + Vote { assertion_hash, agent_id: [1u8; 32], weight, signature: [2u8; 64], timestamp: 1000 } + } + + #[tokio::test] + async fn test_put_and_get_vote() { + let store = SledStore::open_temp().expect("Failed to create store"); + let vote_store = GenericVoteStore::new(store); + + let assertion_hash = [0u8; 32]; + let vote = create_test_vote(assertion_hash, 0.8); + + // Put vote + let vote_hash = vote_store.put_vote(&vote).await.expect("Failed to put vote"); + + // Get vote back + let retrieved = + vote_store.get_vote(&assertion_hash, &vote_hash).await.expect("Failed to get vote"); + + assert!(retrieved.is_some()); + let retrieved_vote = retrieved.expect("Vote should exist"); + assert_eq!(retrieved_vote.weight, 0.8); + assert_eq!(retrieved_vote.assertion_hash, assertion_hash); + } + + #[tokio::test] + async fn test_get_votes_for_assertion() { + let store = SledStore::open_temp().expect("Failed to create store"); + let vote_store = GenericVoteStore::new(store); + + let assertion_hash = [1u8; 32]; + let other_assertion = [2u8; 32]; + + // Add multiple votes for the same assertion + let vote1 = create_test_vote(assertion_hash, 0.5); + let vote2 = Vote { + agent_id: [3u8; 32], // Different agent + ..create_test_vote(assertion_hash, 0.7) + }; + let vote_other = create_test_vote(other_assertion, 0.9); + + vote_store.put_vote(&vote1).await.expect("put"); + vote_store.put_vote(&vote2).await.expect("put"); + vote_store.put_vote(&vote_other).await.expect("put"); + + // Get votes for assertion + let votes = vote_store.get_votes_for_assertion(&assertion_hash).await.expect("get"); + + assert_eq!(votes.len(), 2); + + // Get votes for other assertion + let other_votes = vote_store.get_votes_for_assertion(&other_assertion).await.expect("get"); + + assert_eq!(other_votes.len(), 1); + } + + #[tokio::test] + async fn test_vote_count_cache() { + let store = SledStore::open_temp().expect("Failed to create store"); + let vote_store = GenericVoteStore::new(store); + + let assertion_hash = [3u8; 32]; + + // Initially zero + let count = vote_store.get_vote_count(&assertion_hash).await.expect("count"); + assert_eq!(count, 0); + + // Add votes and check count increments + for i in 0..5 { + let vote = Vote { agent_id: [i; 32], ..create_test_vote(assertion_hash, 0.5) }; + vote_store.put_vote(&vote).await.expect("put"); + + let count = vote_store.get_vote_count(&assertion_hash).await.expect("count"); + assert_eq!(count, (i as u64) + 1); + } + } + + #[tokio::test] + async fn test_aggregate_weight_cache() { + let store = SledStore::open_temp().expect("Failed to create store"); + let vote_store = GenericVoteStore::new(store); + + let assertion_hash = [4u8; 32]; + + // Initially zero + let weight = vote_store.get_aggregate_weight(&assertion_hash).await.expect("weight"); + assert!((weight - 0.0).abs() < f32::EPSILON); + + // Add votes with known weights + let weights = [0.3, 0.5, 0.7, 0.2]; + let mut expected_total = 0.0_f32; + + for (i, &w) in weights.iter().enumerate() { + let vote = + Vote { agent_id: [i as u8; 32], weight: w, ..create_test_vote(assertion_hash, w) }; + vote_store.put_vote(&vote).await.expect("put"); + expected_total += w; + + let actual = vote_store.get_aggregate_weight(&assertion_hash).await.expect("weight"); + + // Float comparison with tolerance + assert!( + (actual - expected_total).abs() < 0.001, + "Expected {}, got {}", + expected_total, + actual + ); + } + } + + #[tokio::test] + async fn test_has_votes() { + let store = SledStore::open_temp().expect("Failed to create store"); + let vote_store = GenericVoteStore::new(store); + + let assertion_hash = [5u8; 32]; + + // No votes initially + assert!(!vote_store.has_votes(&assertion_hash).await.expect("has")); + + // Add a vote + let vote = create_test_vote(assertion_hash, 0.5); + vote_store.put_vote(&vote).await.expect("put"); + + // Now has votes + assert!(vote_store.has_votes(&assertion_hash).await.expect("has")); + } + + #[tokio::test] + async fn test_empty_assertion_returns_empty_vec() { + let store = SledStore::open_temp().expect("Failed to create store"); + let vote_store = GenericVoteStore::new(store); + + let nonexistent = [99u8; 32]; + let votes = vote_store.get_votes_for_assertion(&nonexistent).await.expect("get"); + + assert!(votes.is_empty(), "Should return empty vec, not error"); + } + + #[tokio::test] + async fn test_content_addressing() { + let store = SledStore::open_temp().expect("Failed to create store"); + let vote_store = GenericVoteStore::new(store); + + let assertion_hash = [6u8; 32]; + let vote = create_test_vote(assertion_hash, 0.5); + + // Same vote should produce same hash + let hash1 = vote_store.put_vote(&vote).await.expect("put"); + let hash2 = vote_store.put_vote(&vote).await.expect("put"); + + assert_eq!(hash1, hash2, "Same vote should produce same hash"); + + // Count should still increment (idempotent storage but not idempotent counting) + // This is by design - duplicate vote detection is a higher-level concern + let count = vote_store.get_vote_count(&assertion_hash).await.expect("count"); + assert_eq!(count, 2); + } + + #[tokio::test] + async fn test_high_velocity_simulation() { + // Simulate many agents voting on the same assertion + let store = SledStore::open_temp().expect("Failed to create store"); + let vote_store = Arc::new(GenericVoteStore::new(store)); + + let assertion_hash = [7u8; 32]; + let num_votes = 100; + + // Simulate concurrent voting (sequential for simplicity in test) + for i in 0..num_votes { + let vote = Vote { + assertion_hash, + agent_id: { + let mut id = [0u8; 32]; + id[0] = (i % 256) as u8; + id[1] = (i / 256) as u8; + id + }, + weight: 0.5 + (i as f32 * 0.001), + signature: [i as u8; 64], + timestamp: 1000 + i, + }; + vote_store.put_vote(&vote).await.expect("put"); + } + + // Verify counts + let count = vote_store.get_vote_count(&assertion_hash).await.expect("count"); + assert_eq!(count, num_votes); + + // Verify we can retrieve all votes + let votes = vote_store.get_votes_for_assertion(&assertion_hash).await.expect("get"); + assert_eq!(votes.len(), num_votes as usize); + } + + /// Test concurrent vote ingestion for race condition safety. + /// + /// Spawns multiple tasks voting on the same assertion concurrently. + /// Without atomic operations, this would lose updates due to + /// read-modify-write races. With atomic `fetch_and_add_u64` and + /// `compare_and_swap_f32`, all votes should be counted correctly. + #[tokio::test] + async fn test_concurrent_vote_ingestion() { + use tokio::task::JoinSet; + + let store = Arc::new(SledStore::open_temp().expect("Failed to create store")); + let vote_store = Arc::new(GenericVoteStore::new(store)); + + let assertion_hash = [8u8; 32]; + let num_concurrent_tasks = 10; + let votes_per_task = 10; + let vote_weight = 0.5_f32; + + let mut join_set = JoinSet::new(); + + for task_id in 0..num_concurrent_tasks { + let vs = vote_store.clone(); + join_set.spawn(async move { + for vote_idx in 0..votes_per_task { + let vote = Vote { + assertion_hash, + agent_id: { + let mut id = [0u8; 32]; + id[0] = task_id as u8; + id[1] = vote_idx as u8; + id + }, + weight: vote_weight, + signature: [task_id as u8; 64], + timestamp: 1000 + task_id as u64 * 100 + vote_idx as u64, + }; + vs.put_vote(&vote).await.expect("concurrent put should succeed"); + } + }); + } + + // Wait for all tasks to complete + while let Some(result) = join_set.join_next().await { + result.expect("task should not panic"); + } + + // Verify final vote count is exactly num_concurrent_tasks * votes_per_task + let expected_count = (num_concurrent_tasks * votes_per_task) as u64; + let actual_count = vote_store.get_vote_count(&assertion_hash).await.expect("count"); + assert_eq!( + actual_count, expected_count, + "Vote count should be {} (got {}). Race condition detected!", + expected_count, actual_count + ); + + // Verify aggregate weight is approximately correct + // (some float imprecision is expected with concurrent additions) + let expected_weight = (num_concurrent_tasks * votes_per_task) as f32 * vote_weight; + let actual_weight = vote_store.get_aggregate_weight(&assertion_hash).await.expect("weight"); + let tolerance = 0.01 * expected_weight; // 1% tolerance for float accumulation + assert!( + (actual_weight - expected_weight).abs() < tolerance, + "Aggregate weight should be ~{} (got {}). Race condition detected!", + expected_weight, + actual_weight + ); + } +} diff --git a/docs/app-concepts/consumer-health.md b/docs/app-concepts/consumer-health.md new file mode 100644 index 0000000..ac09709 --- /dev/null +++ b/docs/app-concepts/consumer-health.md @@ -0,0 +1,778 @@ +# Consumer Health Intelligence: Application Layer Guide + +> **Vertical:** Consumer-facing health information +> **Use Case:** [consumer-health-intelligence.md](../../use-cases/consumer-health-intelligence.md) +> **Status:** Design spec — implementation not started + +This guide describes the **application layer components** needed to build a Consumer Health Intelligence platform on Episteme. It covers what you build, not what Episteme provides. + +--- + +## Architecture Overview + +``` +┌─────────────────────────────────────────────────────────────────────────────┐ +│ CONSUMER HEALTH APP │ +├─────────────────────────────────────────────────────────────────────────────┤ +│ │ +│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ +│ │ PubMed │ │ Reddit │ │ FAERS │ │ FDA │ │ +│ │ Crawler │ │ Crawler │ │ Crawler │ │ Crawler │ │ +│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │ +│ │ │ │ │ │ +│ └────────────┬────┴────────┬────────┴─────────┬───────┘ │ +│ │ │ │ │ +│ ▼ ▼ ▼ │ +│ ┌───────────────────────────────────────────────┐ │ +│ │ NLP Extraction Pipeline │ │ +│ │ (claim identification, confidence scoring) │ │ +│ └───────────────────────┬───────────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌───────────────────────────────────────────────┐ │ +│ │ Source-Class Classifier │ │ +│ │ (tier assignment: 0=regulatory → 6=media) │ │ +│ └───────────────────────┬───────────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌───────────────────────────────────────────────┐ │ +│ │ Metadata Enrichment Service │ │ +│ │ (DOI lookup, journal info, engagement stats) │ │ +│ └───────────────────────┬───────────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌───────────────────────────────────────────────┐ │ +│ │ Agent Wallet │ │ +│ │ (key management, Ed25519 signing) │ │ +│ └───────────────────────┬───────────────────────┘ │ +│ │ │ +└──────────────────────────────────────┼───────────────────────────────────────┘ + │ POST /assert + ▼ +┌─────────────────────────────────────────────────────────────────────────────┐ +│ EPISTEME DATABASE │ +│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ +│ │ WAL │ │ KV │ │ Indexes │ │ Lenses │ │ MV │ │ +│ └─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │ +└─────────────────────────────────────────────────────────────────────────────┘ + │ GET /query + ▼ +┌─────────────────────────────────────────────────────────────────────────────┐ +│ CONSUMER HEALTH APP │ +│ │ +│ ┌───────────────────────────────────────────────┐ │ +│ │ Background Gardener │ │ +│ │ (cluster detection, escalation assertions) │ │ +│ └───────────────────────────────────────────────┘ │ +│ │ +│ ┌───────────────────────────────────────────────┐ │ +│ │ LLM Summary Generator │ │ +│ │ (plain-language synthesis of query results) │ │ +│ └───────────────────────────────────────────────┘ │ +│ │ +│ ┌───────────────────────────────────────────────┐ │ +│ │ Disagreement Dashboard │ │ +│ │ (web UI for consumers) │ │ +│ └───────────────────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────────────┘ +``` + +--- + +## Component 1: Ingestion Pipeline + +### 1.1 Data Sources + +| Source | API/Method | Volume Estimate | Source Class | +|--------|------------|-----------------|--------------| +| **PubMed/biorxiv** | NCBI E-utilities API | ~5,000 papers for GLP-1 | Tier 1-2 | +| **ClinicalTrials.gov** | ClinicalTrials.gov API | ~800 registered trials | Tier 1-2 | +| **FDA Labels** | DailyMed API / EDGAR scraping | ~50 documents | Tier 0 | +| **FAERS** | openFDA API | ~50,000 reports for semaglutide | Tier 3 | +| **Reddit** | Reddit API (r/Ozempic, r/loseit) | ~500,000 posts/comments | Tier 5 | +| **Patient Forums** | Web scraping | ~100,000 posts | Tier 5 | +| **News** | News API | ~10,000 articles | Tier 6 | +| **Social Media** | Platform APIs / Firehose | ~1,000,000+ mentions | Tier 6 | + +### 1.2 Crawler Implementation + +Each source needs a dedicated crawler. Here's the pattern: + +```go +// crawler/pubmed/crawler.go + +type PubMedCrawler struct { + apiKey string + baseURL string + rateLimit time.Duration +} + +func (c *PubMedCrawler) FetchArticles(query string, since time.Time) ([]RawArticle, error) { + // Call NCBI E-utilities API + // Respect rate limits (3 req/sec with API key) + // Return raw article data +} + +type RawArticle struct { + PMID string + Title string + Abstract string + Authors []string + Journal string + DOI string + PubDate time.Time + MeSHTerms []string + StudyDesign string // RCT, observational, meta-analysis, etc. +} +``` + +### 1.3 NLP Extraction Pipeline + +Transforms raw documents into structured claims. + +```go +// extraction/pipeline.go + +type ClaimExtractor struct { + llm LLMClient // Claude, GPT-4, or local model + promptStore PromptStore // Domain-specific extraction prompts +} + +type ExtractedClaim struct { + Subject string // e.g., "semaglutide/adverse-effects/gastroparesis" + Predicate string // e.g., "risk_level" + Object string // e.g., "No statistically significant increase" + Confidence float32 // Extraction confidence, not source authority + Evidence string // Quote from source supporting the claim +} + +func (e *ClaimExtractor) Extract(doc RawDocument) ([]ExtractedClaim, error) { + // Use LLM to identify claims in the document + // Map claims to subject/predicate ontology + // Assign extraction confidence based on clarity + // Return structured claims +} +``` + +**Prompt Engineering:** The extraction prompt is critical. It must: +- Define the claim ontology (what subjects/predicates are valid) +- Distinguish claims from context +- Extract supporting evidence for provenance +- Rate extraction confidence (not source authority) + +**Example prompt structure:** +``` +You are extracting health claims from a medical document. + +Ontology: +- Subjects: {drug}/adverse-effects/{condition}, {drug}/efficacy/{outcome} +- Predicates: risk_level, incidence_rate, relative_risk, clinical_significance + +For each claim found, return: +- subject: The specific topic (e.g., "semaglutide/adverse-effects/gastroparesis") +- predicate: What aspect is being claimed +- object: The claim value (use exact quotes where possible) +- confidence: Your confidence in the extraction accuracy (0.0-1.0) +- evidence: The exact text supporting this claim + +Document: +{document_text} +``` + +### 1.4 Source-Class Classifier + +Assigns tier based on source metadata. + +```go +// classification/source_class.go + +type SourceClassifier struct { + rules []ClassificationRule +} + +type ClassificationRule struct { + Name string + Predicate func(SourceMetadata) bool + Tier uint8 +} + +func (c *SourceClassifier) Classify(meta SourceMetadata) uint8 { + for _, rule := range c.rules { + if rule.Predicate(meta) { + return rule.Tier + } + } + return 6 // Default to lowest tier +} + +// Default pharma rules +var PharmaRules = []ClassificationRule{ + { + Name: "FDA Label", + Predicate: func(m SourceMetadata) bool { + return m.Source == "dailymed" || m.Source == "fda.gov" + }, + Tier: 0, + }, + { + Name: "Peer-Reviewed RCT", + Predicate: func(m SourceMetadata) bool { + return m.DOI != "" && m.StudyDesign == "RCT" && m.PeerReviewed + }, + Tier: 1, + }, + { + Name: "Meta-Analysis", + Predicate: func(m SourceMetadata) bool { + return m.StudyDesign == "meta-analysis" && m.PeerReviewed + }, + Tier: 1, + }, + { + Name: "Observational Study", + Predicate: func(m SourceMetadata) bool { + return m.DOI != "" && (m.StudyDesign == "cohort" || m.StudyDesign == "case-control") + }, + Tier: 2, + }, + { + Name: "FAERS Report", + Predicate: func(m SourceMetadata) bool { + return m.Source == "openfda" || m.Source == "faers" + }, + Tier: 3, + }, + { + Name: "Case Report", + Predicate: func(m SourceMetadata) bool { + return m.StudyDesign == "case-report" + }, + Tier: 4, + }, + { + Name: "Reddit", + Predicate: func(m SourceMetadata) bool { + return strings.Contains(m.URL, "reddit.com") + }, + Tier: 5, + }, + { + Name: "Patient Forum", + Predicate: func(m SourceMetadata) bool { + return m.Source == "patient-forum" + }, + Tier: 5, + }, + { + Name: "News", + Predicate: func(m SourceMetadata) bool { + return m.Source == "news-api" + }, + Tier: 6, + }, + { + Name: "Social Media", + Predicate: func(m SourceMetadata) bool { + return m.Source == "tiktok" || m.Source == "instagram" || m.Source == "twitter" + }, + Tier: 6, + }, +} +``` + +### 1.5 Metadata Enrichment + +Adds structured metadata before submission. + +```go +// enrichment/service.go + +type EnrichmentService struct { + crossref CrossRefClient + pubmed PubMedClient + reddit RedditClient +} + +type EnrichedMetadata struct { + // Academic sources + Journal string `json:"journal,omitempty"` + DOI string `json:"doi,omitempty"` + SampleSize int `json:"sample_size,omitempty"` + StudyDesign string `json:"study_design,omitempty"` + + // Social sources + Platform string `json:"platform,omitempty"` + Subreddit string `json:"subreddit,omitempty"` + Upvotes int `json:"upvotes,omitempty"` + Replies int `json:"replies,omitempty"` + + // Sentiment (computed during extraction) + Sentiment string `json:"sentiment,omitempty"` + SentimentPolarity float32 `json:"sentiment_polarity,omitempty"` +} + +func (e *EnrichmentService) Enrich(source SourceMetadata) (*EnrichedMetadata, error) { + meta := &EnrichedMetadata{} + + if source.DOI != "" { + // CrossRef lookup for journal, citations + crossrefData, _ := e.crossref.GetByDOI(source.DOI) + meta.Journal = crossrefData.ContainerTitle + } + + if strings.Contains(source.URL, "reddit.com") { + // Reddit API for engagement metrics + redditData, _ := e.reddit.GetPost(source.URL) + meta.Upvotes = redditData.Score + meta.Replies = redditData.NumComments + meta.Subreddit = redditData.Subreddit + } + + return meta, nil +} +``` + +### 1.6 Assembly & Submission + +Combines all components into a signed assertion. + +```go +// ingestion/submit.go + +type AssertionSubmitter struct { + episteme EpistemeClient + wallet AgentWallet + classifier SourceClassifier + enricher EnrichmentService +} + +func (s *AssertionSubmitter) Submit(claim ExtractedClaim, source SourceMetadata) error { + // 1. Classify source tier + tier := s.classifier.Classify(source) + + // 2. Enrich metadata + meta, _ := s.enricher.Enrich(source) + metaJSON, _ := json.Marshal(meta) + + // 3. Compute source hash + sourceHash := blake3.Sum256([]byte(source.URL + source.Content)) + + // 4. Build assertion + assertion := &CreateAssertionRequest{ + Subject: claim.Subject, + Predicate: claim.Predicate, + Object: ObjectText(claim.Object), + Confidence: claim.Confidence, + SourceClass: &tier, + SourceHash: hex.EncodeToString(sourceHash[:]), + SourceMetadata: string(metaJSON), + Lifecycle: "Proposed", + } + + // 5. Sign with agent key + signature, _ := s.wallet.Sign(assertion) + assertion.Signatures = []SignatureDTO{signature} + + // 6. Submit to Episteme + return s.episteme.Assert(assertion) +} +``` + +--- + +## Component 2: Background Gardener + +Monitors the knowledge graph for emerging signals. + +### 2.1 Cluster Detection + +```go +// gardener/cluster_detector.go + +type ClusterDetector struct { + episteme EpistemeClient + thresholds ClusterThresholds +} + +type ClusterThresholds struct { + MinAssertions int // Minimum assertions to be considered a cluster + TimeWindow time.Duration // Window for growth rate calculation + GrowthRateHigh float64 // Assertions per month considered "high" + TierGapTrigger bool // Trigger if Tier 5+ exists but Tier 1-2 doesn't +} + +type DetectedCluster struct { + Subject string + Predicate string + Tier5Count int + Tier1Count int + GrowthRate float64 // Assertions per month + HasClinicalGap bool // Tier 5+ exists, no Tier 1-2 + EarliestReport time.Time +} + +func (d *ClusterDetector) Scan() ([]DetectedCluster, error) { + // Query Episteme for all subject+predicate pairs + // For each pair, count assertions by tier + // Calculate growth rate over time window + // Flag clusters that meet thresholds +} +``` + +### 2.2 Escalation Assertion Generation + +```go +// gardener/escalation.go + +func (g *Gardener) GenerateEscalation(cluster DetectedCluster) *CreateAssertionRequest { + meta := map[string]interface{}{ + "trigger": "cluster_threshold", + "tier_5_count": cluster.Tier5Count, + "tier_1_count": cluster.Tier1Count, + "growth_rate": fmt.Sprintf("%.0f/month", cluster.GrowthRate), + "clinical_gap": cluster.HasClinicalGap, + "earliest_report": cluster.EarliestReport.Format(time.RFC3339), + } + metaJSON, _ := json.Marshal(meta) + + return &CreateAssertionRequest{ + Subject: cluster.Subject, + Predicate: "escalation_signal", + Object: ObjectText("Anecdotal cluster detected"), + Confidence: 0.6, // Moderate confidence in the signal + SourceClass: ptr(uint8(255)), // Meta-tier for system-generated + SourceMetadata: string(metaJSON), + Lifecycle: "UnderReview", + } +} +``` + +### 2.3 Scheduled Tasks + +```go +// gardener/scheduler.go + +func (g *Gardener) RunSchedule(ctx context.Context) { + // Every hour: Scan for new clusters + go g.runEvery(ctx, 1*time.Hour, g.ScanClusters) + + // Every day: Decay trust ranks + go g.runEvery(ctx, 24*time.Hour, g.DecayTrustRanks) + + // Every week: Generate summary reports + go g.runEvery(ctx, 7*24*time.Hour, g.GenerateReports) +} + +func (g *Gardener) DecayTrustRanks(ctx context.Context) error { + return g.episteme.Post("/v1/admin/decay-trust-ranks", nil) +} +``` + +--- + +## Component 3: Disagreement Dashboard + +### 3.1 Query Patterns + +The dashboard needs these Episteme queries: + +```go +// dashboard/queries.go + +// Get layered consensus for a topic +func (d *Dashboard) GetLayeredConsensus(subject string) (*LayeredResponse, error) { + return d.episteme.Query(&QueryParams{ + Subject: subject, + Lens: "LayeredConsensus", + }) +} + +// Get conflict map using Skeptic lens +func (d *Dashboard) GetConflictMap(subject string) (*SkepticResponse, error) { + return d.episteme.Query(&QueryParams{ + Subject: subject, + Lens: "Skeptic", + }) +} + +// Get historical state at a point in time +func (d *Dashboard) GetHistoricalState(subject string, asOf time.Time) (*QueryResponse, error) { + return d.episteme.Query(&QueryParams{ + Subject: subject, + Lens: "LayeredConsensus", + AsOf: asOf.Unix(), + }) +} + +// Get changes since last visit +func (d *Dashboard) GetChangesSince(subject string, since time.Time) (*QueryResponse, error) { + return d.episteme.Query(&QueryParams{ + Subject: subject, + Lens: "LayeredConsensus", + Since: since.Unix(), + }) +} +``` + +### 3.2 Response Transformation + +```go +// dashboard/transform.go + +type ConsumerView struct { + Topic string `json:"topic"` + Summary string `json:"summary"` // LLM-generated + ConflictScore float32 `json:"conflict_score"` + TierPositions []TierPosition `json:"tier_positions"` + ResolvedTopics []ResolvedTopic `json:"resolved"` + ActiveDisputes []ActiveDispute `json:"active_disputes"` + EmergingSignals []EmergingSignal `json:"emerging_signals"` + LastUpdated time.Time `json:"last_updated"` +} + +type TierPosition struct { + TierName string `json:"tier_name"` // "Clinical Evidence", "Patient Community" + TierNumber uint8 `json:"tier_number"` + Position string `json:"position"` + Confidence float32 `json:"confidence"` + AssertionCount int `json:"assertion_count"` +} + +func TransformForConsumer(layered *LayeredResponse, skeptic *SkepticResponse) *ConsumerView { + view := &ConsumerView{ + ConflictScore: layered.OverallConflictScore, + } + + for _, tier := range layered.Tiers { + view.TierPositions = append(view.TierPositions, TierPosition{ + TierName: tierToName(tier.Tier), + TierNumber: tier.Tier, + Position: summarizePosition(tier.Winner), + Confidence: tier.Winner.Confidence, + AssertionCount: tier.CandidatesCount, + }) + } + + // Categorize by conflict level + for _, topic := range skeptic.Topics { + if topic.ConflictScore < 0.2 { + view.ResolvedTopics = append(view.ResolvedTopics, ...) + } else if topic.ConflictScore < 0.7 { + view.ActiveDisputes = append(view.ActiveDisputes, ...) + } else { + view.EmergingSignals = append(view.EmergingSignals, ...) + } + } + + return view +} + +func tierToName(tier uint8) string { + names := map[uint8]string{ + 0: "Regulatory", + 1: "Clinical Evidence", + 2: "Real-World Evidence", + 3: "Pharmacovigilance", + 4: "Clinical Anecdote", + 5: "Patient Community", + 6: "Media", + } + return names[tier] +} +``` + +### 3.3 LLM Summary Generation + +```go +// dashboard/summary.go + +type SummaryGenerator struct { + llm LLMClient +} + +func (g *SummaryGenerator) GenerateSummary(view *ConsumerView) (string, error) { + prompt := fmt.Sprintf(` +Summarize the following health topic for a consumer in 2-3 sentences. +Be factual. Acknowledge uncertainty where it exists. Do not give medical advice. + +Topic: %s +Conflict Score: %.2f (0 = agreement, 1 = max disagreement) + +Tier Positions: +%s + +Output a concise, balanced summary. +`, view.Topic, view.ConflictScore, formatTierPositions(view.TierPositions)) + + return g.llm.Complete(prompt) +} +``` + +**Example output:** +> "Clinical trials show low incidence of gastroparesis with semaglutide; post-marketing reports and patient communities report higher rates. The FDA added gastroparesis to the label in January 2024. There is moderate disagreement between clinical evidence and real-world reports." + +--- + +## Component 4: Agent Wallet + +Manages signing keys for the ingestion pipeline. + +### 4.1 Key Storage + +```go +// wallet/wallet.go + +type AgentWallet struct { + keyPath string + privateKey ed25519.PrivateKey + publicKey ed25519.PublicKey +} + +func NewAgentWallet(keyPath string) (*AgentWallet, error) { + // Load or generate Ed25519 keypair + // Store private key securely (file permissions, encryption at rest) +} + +func (w *AgentWallet) Sign(assertion *CreateAssertionRequest) (*SignatureDTO, error) { + // Serialize assertion for signing + message := fmt.Sprintf("%s:%s", assertion.Subject, assertion.Predicate) + sig := ed25519.Sign(w.privateKey, []byte(message)) + + return &SignatureDTO{ + AgentID: hex.EncodeToString(w.publicKey), + Signature: hex.EncodeToString(sig), + Timestamp: time.Now().Unix(), + }, nil +} +``` + +### 4.2 Multi-Agent Setup + +For different source types, use different agent identities: + +```go +// wallet/multi.go + +type MultiAgentWallet struct { + agents map[string]*AgentWallet +} + +func (m *MultiAgentWallet) SignAs(agentName string, assertion *CreateAssertionRequest) (*SignatureDTO, error) { + agent, ok := m.agents[agentName] + if !ok { + return nil, fmt.Errorf("unknown agent: %s", agentName) + } + return agent.Sign(assertion) +} + +// Usage: +// - "pubmed-crawler" agent for academic sources +// - "reddit-crawler" agent for social sources +// - "gardener" agent for escalation assertions +``` + +--- + +## Deployment Architecture + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ Kubernetes Cluster │ +├─────────────────────────────────────────────────────────────────┤ +│ │ +│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ +│ │ PubMed │ │ Reddit │ │ FAERS │ Crawlers │ +│ │ Crawler │ │ Crawler │ │ Crawler │ (CronJob) │ +│ │ Pod │ │ Pod │ │ Pod │ │ +│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │ +│ │ │ │ │ +│ └────────────────┼────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌───────────────────────────────────────────────────────────┐ │ +│ │ Extraction Service │ │ +│ │ (Deployment, 3 replicas) │ │ +│ └───────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌───────────────────────────────────────────────────────────┐ │ +│ │ Episteme API │ │ +│ │ (Deployment, 3 replicas) │ │ +│ └───────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌───────────────────────────────────────────────────────────┐ │ +│ │ Dashboard API │ │ +│ │ (Deployment, 2 replicas) │ │ +│ └───────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌───────────────────────────────────────────────────────────┐ │ +│ │ Dashboard UI │ │ +│ │ (Static, CDN) │ │ +│ └───────────────────────────────────────────────────────────┘ │ +│ │ +│ ┌───────────────────────────────────────────────────────────┐ │ +│ │ Background Gardener │ │ +│ │ (CronJob, hourly) │ │ +│ └───────────────────────────────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────┘ +``` + +--- + +## Checklist: What You Need to Build + +### Crawlers (one per source) +- [ ] PubMed/biorxiv crawler (NCBI E-utilities) +- [ ] ClinicalTrials.gov crawler +- [ ] FDA DailyMed scraper +- [ ] openFDA FAERS consumer +- [ ] Reddit API consumer +- [ ] Patient forum scrapers +- [ ] News API consumer +- [ ] Social media sampler + +### Extraction Pipeline +- [ ] LLM-based claim extractor +- [ ] Subject/predicate ontology for pharma domain +- [ ] Extraction prompt library +- [ ] Confidence calibration + +### Classification & Enrichment +- [ ] Source-class classifier with pharma rules +- [ ] CrossRef integration for DOI lookup +- [ ] PubMed integration for study metadata +- [ ] Reddit API for engagement metrics +- [ ] Sentiment analysis model + +### Infrastructure +- [ ] Agent wallet with secure key storage +- [ ] Multi-agent identity management +- [ ] Rate limiting for external APIs +- [ ] Retry logic and error handling + +### Gardener +- [ ] Cluster detection algorithm +- [ ] Escalation assertion generator +- [ ] TrustRank decay scheduler +- [ ] Alert/notification system + +### Dashboard +- [ ] Query orchestration layer +- [ ] Response transformation +- [ ] LLM summary generator +- [ ] React/Vue frontend +- [ ] Time-travel UI +- [ ] Change notification system + +--- + +## See Also + +- [Use Case: Consumer Health Intelligence](../../use-cases/consumer-health-intelligence.md) — Full scenario walkthrough +- [App Concepts Index](./index.md) — General application layer patterns +- [Roadmap: Phase 3](../../roadmap.md) — Database features needed +- [ADK-Go Integration](../../.claude/guides/integrations/adk-go-episteme.md) — Agent framework integration diff --git a/docs/app-concepts/index.md b/docs/app-concepts/index.md new file mode 100644 index 0000000..61dba69 --- /dev/null +++ b/docs/app-concepts/index.md @@ -0,0 +1,201 @@ +# Application Layer Concepts + +> **Audience:** Teams building applications on top of Episteme. +> **Not covered here:** Database internals (see [architecture.md](../../architecture.md)) or implementation roadmap (see [roadmap.md](../../roadmap.md)). + +--- + +## The Boundary Principle + +Episteme is a **database engine**. It stores assertions, resolves conflicts via lenses, and serves queries. Everything else is the **application layer**. + +### Episteme Owns + +| Domain | Responsibilities | +|--------|------------------| +| **Storage** | WAL, KV store, indexes, content-addressing via BLAKE3 | +| **Types** | Assertion, Vote, Epoch, LifecycleStage, MaterializedView | +| **Resolution** | Lenses (Recency, Consensus, Authority, Skeptic, Layered, Constraints) | +| **Query** | Filtering, audit trail, time-travel (`as_of`), decay at resolution time | +| **Integrity** | Ed25519 signature verification, checksums, epoch supersession cascades | +| **API** | HTTP endpoints: `POST /assert`, `POST /vote`, `POST /epoch`, `GET /query` | + +### Application Layer Owns + +| Domain | Responsibilities | +|--------|------------------| +| **Data Acquisition** | Crawlers, scrapers, API consumers (PubMed, Reddit, FAERS, etc.) | +| **Data Transformation** | NLP extraction, claim identification, confidence assignment | +| **Classification** | Source-class tier assignment, study design classification | +| **Enrichment** | DOI resolution, journal metadata, engagement metrics | +| **Intelligence** | Cluster detection, anomaly detection, signal surfacing | +| **Presentation** | Dashboards, summaries, consumer UX, LLM-powered synthesis | +| **Orchestration** | Agent swarms, reviewers, curators | +| **Client Libraries** | SDKs that wrap the HTTP API (Go, Python, etc.) | +| **Infrastructure** | Key management, budget enforcement, job scheduling | + +--- + +## The Test + +For any feature, ask: **"Does this require changes to Episteme's storage, indexing, resolution, or API?"** + +- **If yes** → Database feature. It goes in Episteme. +- **If no**, it just calls the API → Application layer. It goes in your app. +- **If both** → Split it. Episteme provides the primitive; your app provides the intelligence. + +### Examples + +| Feature | DB Primitive | App Intelligence | +|---------|--------------|------------------| +| Source-class decay | Decay formula applied during lens resolution | Which tier a source belongs to | +| Cluster escalation | Accept/store/query escalation assertions | Detect clusters, compute thresholds | +| Disagreement dashboard | Skeptic Lens + conflict_score | UI rendering, LLM summaries | +| Time-travel | `as_of` query parameter | "What changed since you last looked" UX | +| Visual anchoring | Store + query visual_hash | Image hashing, screenshot comparison | +| Pharma data | Ingest via `POST /assert` | Crawl PubMed, extract claims, classify | + +--- + +## Core Application Components + +These are the building blocks that most Episteme-powered applications need. + +### 1. Ingestion Pipeline + +Transforms raw source material into signed assertions. + +``` +[Raw Source] → [Crawler/API] → [NLP Extraction] → [Classification] → [Enrichment] → [Signing] → [POST /assert] +``` + +**Responsibilities:** +- Fetch documents from source systems (PubMed API, Reddit API, web scraping) +- Extract claims as subject/predicate/object triples +- Assign confidence based on extraction quality +- Classify source tier (0-6) +- Enrich with structured metadata +- Sign with agent key +- Submit to Episteme + +**See:** [Consumer Health Ingestion](./consumer-health.md#ingestion-pipeline) + +### 2. Source-Class Classifier + +Determines the authority tier of each source. + +| Tier | Source Type | Examples | +|------|-------------|----------| +| 0 | Regulatory action | FDA label change, EMA withdrawal | +| 1 | Peer-reviewed RCT, meta-analysis | NEJM, Lancet, JAMA | +| 2 | Observational study, real-world evidence | Insurance claims, EHR studies | +| 3 | Pharmacovigilance | FAERS reports, EudraVigilance | +| 4 | Clinician anecdote, case report | Conference presentations, case series | +| 5 | Patient community | Reddit, forums, patient registries | +| 6 | Media, influencer, commercial | TikTok, news articles, pharma marketing | + +**Implementation:** Rule-based classifier or ML model that maps source metadata (URL pattern, DOI prefix, platform) to tier. + +**Domain-specific:** The tier map for pharma differs from finance differs from legal. + +### 3. Background Gardener + +Monitors the knowledge graph for signals that warrant attention. + +**Responsibilities:** +- Query assertion counts by subject/predicate/tier +- Detect unusual clustering (e.g., 1,847 Tier-5 assertions in 6 months) +- Generate escalation assertions when thresholds are crossed +- Trigger TrustRank decay on schedule +- Update agent reputations based on outcomes + +**Episteme primitives it uses:** +- `GET /query` with aggregation +- `POST /assert` for escalation assertions +- `POST /admin/decay-trust-ranks` for scheduled decay + +### 4. Presentation Layer + +Renders Episteme query results for end users. + +**Options:** +- **Dashboard:** React/Vue app that visualizes conflict scores, tier positions, timelines +- **API Gateway:** REST/GraphQL layer that adds business logic before returning data +- **Chat Interface:** LLM-powered conversational access to the knowledge graph +- **Reports:** Scheduled exports (PDF, email digests) + +**Episteme primitives it uses:** +- `GET /query` with various lenses +- Layered Consensus for per-tier breakdown +- Skeptic Lens for disagreement surfacing +- `as_of` for time-travel views +- `since` for change tracking + +### 5. Agent Integration + +Connects AI agents to Episteme for reading and writing knowledge. + +**ADK-Go Tool Example:** +```go +// Tool: Query the knowledge graph +func QueryKnowledge(ctx context.Context, subject, predicate string, lens string) (string, error) { + resp, err := episteme.Query(ctx, &QueryParams{ + Subject: subject, + Predicate: predicate, + Lens: lens, + }) + if err != nil { + return "", err + } + return formatForAgent(resp), nil +} + +// Tool: Assert a new fact +func AssertFact(ctx context.Context, subject, predicate, object string, confidence float32) error { + return episteme.Assert(ctx, &AssertionRequest{ + Subject: subject, + Predicate: predicate, + Object: ObjectText(object), + Confidence: confidence, + Lifecycle: "Proposed", + }) +} +``` + +**See:** [ADK-Go Integration Guide](../../.claude/guides/integrations/adk-go-episteme.md) + +--- + +## Vertical-Specific Guides + +| Vertical | Guide | Key Components | +|----------|-------|----------------| +| **Consumer Health** | [consumer-health.md](./consumer-health.md) | Pharma crawlers, tier classification, disagreement dashboard | +| **Financial Due Diligence** | (planned) | SEC filings, analyst extraction, invalidation cascades | +| **Agile Agent Team** | (planned) | Constraints lens, lifecycle workflow, audit trail | + +--- + +## Quick Reference: What Goes Where + +| If you need to... | Episteme provides... | You build... | +|-------------------|---------------------|--------------| +| Store conflicting facts | Assertion type, append-only DAG | Nothing — just POST assertions | +| Resolve conflicts | Lenses (Recency, Consensus, Skeptic, Layered) | Lens selection logic | +| Query historical state | `as_of` parameter | Time-travel UI | +| Track changes | `since` parameter + MV changelog | Notification system | +| Weight by source authority | `source_class` field + source-aware decay | Tier classifier | +| Detect emerging signals | Skeptic Lens + conflict_score | Gardener (threshold logic) | +| Show per-tier consensus | Layered Consensus Lens | Dashboard UI | +| Extract claims from papers | Nothing — pre-assertion transform | NLP pipeline | +| Sign assertions | Signature verification | Agent wallet / key management | +| Generate summaries | Structured query responses | LLM summarizer | + +--- + +## See Also + +- [Architecture](../../architecture.md) — Database internals +- [Roadmap](../../roadmap.md) — What's implemented vs planned +- [API Reference](../../ai-lookup/services/) — Endpoint documentation +- [Use Cases](../../use-cases/) — Full scenario walkthroughs diff --git a/docs/data-structures.md b/docs/data-structures.md new file mode 100644 index 0000000..1f7654c --- /dev/null +++ b/docs/data-structures.md @@ -0,0 +1,496 @@ +# StemeDB Data Structures + +> **Last Updated:** 2026-01-31 +> **Source:** `crates/stemedb-core/src/types.rs` + +This document describes the core data structures in StemeDB (Episteme). These types form the foundation of the "Git for Truth" knowledge graph. + +--- + +## Design Principles + +1. **Append-Only**: Data is never mutated. New assertions create new records. +2. **Content-Addressed**: Every assertion's ID is a BLAKE3 hash of its content. +3. **Zero-Copy**: Uses `rkyv` for serialization - data can be read directly from disk without parsing. +4. **Provenance-First**: Every fact carries its source, signers, and confidence. + +--- + +## Primitive Types + +```rust +pub type Hash = [u8; 32]; // BLAKE3 256-bit hash +pub type PHash = [u8; 8]; // Perceptual hash for images (8 bytes) +pub type EntityId = String; // Subject or object identifier +pub type RelationId = String; // Predicate identifier +pub type EpochId = Hash; // Paradigm/era identifier +pub type QueryId = Hash; // Query audit record identifier +``` + +--- + +## The Assertion (Atomic Unit of Knowledge) + +The `Assertion` is the fundamental unit. It represents a single claim about the world. + +```rust +pub struct Assertion { + // ═══════════════════════════════════════════════════════════ + // 1. THE FACT (What is being claimed) + // ═══════════════════════════════════════════════════════════ + + /// The entity this assertion is about (e.g., "Semaglutide", "Tesla_Inc") + pub subject: EntityId, + + /// The relationship or property (e.g., "has_side_effect", "annual_revenue") + pub predicate: RelationId, + + /// The claimed value + pub object: ObjectValue, + + // ═══════════════════════════════════════════════════════════ + // 2. THE LINEAGE (Why we believe it) + // ═══════════════════════════════════════════════════════════ + + /// If this modifies/forks another assertion, its hash + pub parent_hash: Option, + + /// Hash of the source evidence (PDF, URL, database export) + pub source_hash: Hash, + + /// Authority tier of the source (enables indexing and decay rates) + pub source_class: SourceClass, + + /// Perceptual hash of a visual anchor (e.g., screenshot of table) + pub visual_hash: Option, + + /// Which paradigm/era this belongs to (for paradigm shifts) + pub epoch: Option, + + /// Lifecycle stage (Proposed → Approved → Deprecated) + pub lifecycle: LifecycleStage, + + // ═══════════════════════════════════════════════════════════ + // 3. META-COGNITION (Who said it, how sure are they) + // ═══════════════════════════════════════════════════════════ + + /// Cryptographic signatures from agents vouching for this + pub signatures: Vec, + + /// Subjective confidence score (0.0 to 1.0) + pub confidence: f32, + + /// Unix timestamp when created + pub timestamp: u64, + + /// Semantic embedding vector for similarity search + pub vector: Option>, +} +``` + +### ObjectValue + +The value in a subject-predicate-object triple: + +```rust +pub enum ObjectValue { + Text(String), // "muscle loss" + Number(f64), // 96.7 + Boolean(bool), // true + Reference(EntityId), // Points to another entity (graph edge) +} +``` + +### LifecycleStage + +Assertions progress through stages (as new assertions, not mutations): + +``` +Proposed → UnderReview → Approved + ↘ Rejected + ↘ Deprecated +``` + +```rust +pub enum LifecycleStage { + Proposed, // Initial idea, not for production use + UnderReview, // Gathering votes and feedback + Approved, // Accepted as current truth + Deprecated, // Was true, now superseded + Rejected, // Explicitly declined +} +``` + +### SourceClass + +Authority tier classification for sources. Enables indexing by tier and tier-based decay rates: + +| Tier | Class | Example | Default Decay | +|------|-------|---------|---------------| +| 0 | Regulatory | FDA, EMA, WHO | Never | +| 1 | Clinical | Phase III trials, peer-reviewed RCTs | 2 years | +| 2 | Observational | Real-world evidence, cohort studies | 1 year | +| 3 | Expert | Medical professional opinions, guidelines | 6 months | +| 4 | Community | Curated forums, patient advocacy groups | 3 months | +| 5 | Anecdotal | Reddit posts, individual testimonials | 1 month | + +```rust +pub enum SourceClass { + Regulatory, // Tier 0: Highest authority, never decays + Clinical, // Tier 1: Peer-reviewed research + Observational, // Tier 2: Real-world evidence + Expert, // Tier 3: Professional opinions (default) + Community, // Tier 4: Curated community knowledge + Anecdotal, // Tier 5: Individual reports, fast decay +} + +impl SourceClass { + pub fn tier(&self) -> u8; // Returns 0-5 + pub fn default_decay_days(&self) -> Option; + pub fn authority_weight(&self) -> f32; // 1.0 for Regulatory, 0.1 for Anecdotal +} +``` + +**Key Benefits:** +- **Indexing**: `SC:{source_class}` index enables "show me only regulatory sources" +- **Decay rates**: Anecdotal claims decay faster than clinical evidence +- **Trust weighting**: Lenses can weight sources by authority tier in conflict resolution + +### SignatureEntry + +Cryptographic proof that an agent vouches for an assertion: + +```rust +pub struct SignatureEntry { + pub agent_id: [u8; 32], // Ed25519 public key + pub signature: [u8; 64], // Ed25519 signature over assertion content + pub timestamp: u64, // When the agent signed +} +``` + +--- + +## The Vote (High-Velocity Consensus) + +Votes are separated from assertions to enable thousands of agents to vote simultaneously without lock contention (the "Ballot Box" pattern). + +```rust +pub struct Vote { + /// Hash of the assertion being voted on + pub assertion_hash: Hash, + + /// Ed25519 public key of the voter + pub agent_id: [u8; 32], + + /// Weight of the vote (0.0 = reject, 1.0 = full endorsement) + pub weight: f32, + + /// Signature over the assertion_hash + pub signature: [u8; 64], + + /// When the vote was cast + pub timestamp: u64, +} +``` + +**Key Insight**: Votes are append-only. An agent can change their vote by submitting a new one with a later timestamp. + +--- + +## The Epoch (Paradigm Shifts) + +Epochs represent distinct periods of truth. When knowledge paradigms shift, old epochs can be superseded. + +```rust +pub struct Epoch { + pub id: EpochId, + pub name: String, // "Pre-2024", "Newtonian" + pub supersedes: Option, // What this replaces + pub supersession_type: Option, + pub start_timestamp: u64, + pub end_timestamp: Option, +} + +pub enum SupersessionType { + Invalidation, // Old epoch was factually wrong (e.g., "Earth is flat") + Temporal, // Old epoch was correct but outdated (e.g., "President is Obama") + Refinement, // Old epoch was a simplification (e.g., Newtonian → Relativity) +} +``` + +--- + +## Query Results + +### MaterializedView (O(1) Winner Lookup) + +Pre-computed resolution stored at `MV:{subject}:{predicate}`: + +```rust +pub struct MaterializedView { + /// The winning assertion from lens resolution + pub winner: Assertion, + + /// Which lens produced this (e.g., "VoteAwareConsensus") + pub lens_name: String, + + /// Confidence in the resolution (0.0 to 1.0) + pub resolution_confidence: f32, + + /// How many candidates were considered + pub candidates_count: usize, + + /// When this view was computed + pub materialized_at: u64, +} +``` + +### ConflictAnalysis (Trust but Verify) + +For the SkepticLens - surfaces all competing claims instead of picking a winner: + +```rust +pub struct ConflictAnalysis { + /// Overall status: Unanimous, Agreed, or Contested + pub status: ResolutionStatus, + + /// Conflict score (0.0 = unanimous, 1.0 = maximum chaos) + /// Calculated using normalized Shannon entropy + pub conflict_score: f32, + + /// All distinct claims, ranked by weight_share descending + pub claims: Vec, + + /// Total candidates considered + pub candidates_count: usize, +} + +pub enum ResolutionStatus { + Unanimous, // All agree (entropy < 0.1) + Agreed, // Strong majority (entropy < 0.4) + Contested, // Significant disagreement (entropy >= 0.4) +} +``` + +### ClaimSummary + +A single competing claim within a ConflictAnalysis: + +```rust +pub struct ClaimSummary { + /// The claimed value + pub value: ObjectValue, + + /// This claim's share of total support (0.0 to 1.0) + pub weight_share: f32, + + /// Number of assertions making this claim + pub assertion_count: u32, + + /// Hash of the highest-confidence assertion (for drill-down) + pub representative_hash: Hash, + + /// Source provenance + pub source: SourceSummary, + + /// Agents who signed assertions for this claim + pub supporting_agents: Vec, +} +``` + +### SourceSummary & AgentSummary + +Provenance types for "show me the proof" UX: + +```rust +pub struct SourceSummary { + pub source_hash: Hash, // Hash of source document + pub visual_hash: Option, // Visual anchor (screenshot) +} + +pub struct AgentSummary { + pub agent_id: [u8; 32], // Agent's public key + pub trust_score: f32, // Trust score at query time +} +``` + +--- + +## Query Audit Trail + +Every query is logged for "Why did you think that?" debugging: + +```rust +pub struct QueryAudit { + pub query_id: QueryId, + pub agent_id: Option<[u8; 32]>, // Who queried (from X-Agent-Id header) + pub timestamp: u64, + pub params: QueryParams, + pub result_hash: Option, // Winning assertion hash + pub result_confidence: f32, + pub contributing_assertions: Vec, +} + +pub struct QueryParams { + pub subject: Option, + pub predicate: Option, + pub lifecycle: Option, + pub epoch: Option, + pub lens: Option, +} + +pub struct ContributingAssertion { + pub assertion_hash: Hash, + pub weight: f32, // How much this influenced the result + pub source_hash: Hash, + pub lifecycle: LifecycleStage, +} +``` + +--- + +## Storage Layout + +Key patterns in the KV store: + +| Key Pattern | Value | Purpose | +|-------------|-------|---------| +| `H:{hash}` | Serialized Assertion | Primary assertion storage | +| `S:{subject}` | `Vec` | Subject index | +| `SP:{subject}:{predicate}` | `Vec` | Compound index (O(1) lookup) | +| `MV:{subject}:{predicate}` | MaterializedView | Pre-computed winner | +| `V:{assertion_hash}:{vote_hash}` | Vote | Individual votes | +| `VC:{assertion_hash}` | u64 | Vote count cache | +| `VW:{assertion_hash}` | f32 | Aggregate vote weight cache | +| `TR:{agent_id}` | TrustRank | Agent reputation | +| `TP:{pack_id}` | TrustPack | Curated agent lists | +| `AUD:{query_id}` | QueryAudit | Query audit record | +| `E:{epoch_id}` | Epoch | Epoch definitions | + +--- + +## The Trust Pack (Curator Economy) + +Trust Packs are the "App Store for Trust" - curated lists of trusted agents that filter consensus through domain expertise. + +```rust +pub struct TrustPack { + /// Content-addressed pack ID (BLAKE3 hash) + pub id: PackId, + + /// Human-readable name (e.g., "Mayo_Clinic_Experts") + pub name: String, + + /// Ed25519 public key of the pack maintainer + pub maintainer: [u8; 32], + + /// Agent public keys in this pack + /// Future: Replace with RoaringBitmap for O(1) membership + pub agents: Vec<[u8; 32]>, + + /// Unix timestamp when pack was created + pub created_at: u64, + + /// Unix timestamp of last modification + pub updated_at: u64, +} +``` + +**Key Methods:** +- `add_agent(agent_id)` - Idempotent agent addition +- `remove_agent(agent_id)` - Safe removal +- `contains_agent(agent_id) -> bool` - Membership check + +**Use Case:** Users subscribe to packs like "Skeptical Cardio Pack" to filter GLP-1 side effect claims through vetted cardiologists. + +--- + +## Serialization + +All types use `rkyv` for zero-copy deserialization: + +```rust +use stemedb_core::serde::{serialize, deserialize}; + +// Serialize +let bytes: Vec = serialize(&assertion)?; + +// Deserialize (zero-copy when possible) +let assertion: Assertion = deserialize(&bytes)?; +``` + +**Critical Rule**: Never use raw `AllocSerializer` in production code. Always use `stemedb_core::serde::{serialize, deserialize}`. + +--- + +## Relationship Diagram + +``` + ┌─────────────────────────────────────────────┐ + │ ASSERTION │ + │ ┌─────────┐ ┌───────────┐ ┌─────────────┐ │ + │ │ subject │ │ predicate │ │ object │ │ + │ └─────────┘ └───────────┘ └─────────────┘ │ + │ │ + │ ┌─────────────────┐ ┌──────────────────┐ │ + │ │ source_hash │ │ signatures[] │ │ + │ └────────┬────────┘ └────────┬─────────┘ │ + │ │ │ │ + └───────────┼────────────────────┼────────────┘ + │ │ + ┌───────────▼───────┐ ┌────────▼────────┐ + │ SOURCE DOCUMENT │ │ AGENTS │ + │ (PDF, URL...) │ │ (Ed25519 keys) │ + └───────────────────┘ └────────┬────────┘ + │ + ┌────────▼────────┐ + │ TRUST RANK │ + │ (reputation) │ + └─────────────────┘ + + + ┌─────────────────┐ ┌─────────────────┐ + │ VOTE │◄────────│ ASSERTION │ + │ (Ballot Box) │ votes │ (target) │ + │ weight: 0.0-1.0│ on │ │ + └─────────────────┘ └─────────────────┘ + + + ┌─────────────────┐ ┌─────────────────┐ + │ EPOCH B │◄────────│ EPOCH A │ + │ supersedes: A │ older │ │ + │ type: Temporal │ epoch │ │ + └─────────────────┘ └─────────────────┘ +``` + +--- + +## API Representation + +All binary data (hashes, signatures, agent IDs) is hex-encoded in JSON APIs: + +```json +{ + "subject": "Semaglutide", + "predicate": "muscle_effect", + "object": { "type": "Text", "value": "Significant loss" }, + "source_hash": "a1b2c3d4e5f6...", + "signatures": [ + { + "agent_id": "deadbeef...", + "signature": "cafebabe...", + "timestamp": 1706745600 + } + ], + "confidence": 0.85, + "timestamp": 1706745600 +} +``` + +--- + +## See Also + +- [Architecture Overview](../architecture.md) +- [Lens Documentation](../ai-lookup/services/lens.md) +- [API Endpoints Guide](../.claude/guides/backend/api-endpoints.md) diff --git a/docs/presentations/data/agile-agent-team.yaml b/docs/presentations/data/agile-agent-team.yaml index be6d537..7115b63 100644 --- a/docs/presentations/data/agile-agent-team.yaml +++ b/docs/presentations/data/agile-agent-team.yaml @@ -2,577 +2,248 @@ meta: id: agile-agent-team title: "Agile AI Agent Team" subtitle: "Knowledge Coordination with Episteme" - version: "1.0.0" + version: "4.0.0" -actors: - research_agent: - id: RA - label: "Research Agent" - description: "Ingests external sources, stores with uncertainty" - color: "#3B82F6" +actors: {} - lead_orchestrator: - id: LO - label: "Lead Orchestrator" - description: "Coordinates team, routes work based on knowledge" - color: "#8B5CF6" - - implementation_agent: - id: IA - label: "Implementation Agent" - description: "Writes code against current patterns" - color: "#10B981" - - deploy_agent: - id: DA - label: "Deploy Agent" - description: "Deploys configurations to production" - color: "#F59E0B" - - episteme: - id: E - label: "Episteme" - description: "Probabilistic knowledge graph" - color: "#FBBF24" - - human: - id: H - label: "Human Supervisor" - description: "Reviews decisions, corrects errors" - color: "#EC4899" - - gardener: - id: G - label: "Gardener" - description: "Background worker for TrustRank propagation" - color: "#14B8A6" - - production: - id: P - label: "Production" - description: "Live system" - color: "#EF4444" - -sequences: +slides: # ============================================ - # SEQUENCE 1: THE CATASTROPHE + # TITLE # ============================================ - - id: catastrophe + - type: title + id: title + + # ============================================ + # HOOK + # ============================================ + - type: hook + id: hook + line: "Your agents have amnesia." + subline: "Every correction you make is forgotten by the next session." + + # ============================================ + # THE DRIFT - Pattern 1: Logging + # ============================================ + - type: code + id: drift-logging + title: "Day 1: You correct the agent" + code: | + // Agent used console.log + // You: "We use winston, not console.log" + + import { logger } from './logger'; + + logger.info('User authenticated', { userId }); + + - type: code + id: drift-logging-2 + title: "Day 30: New session" + code: | + // Agent writes new code... + + console.log('User authenticated'); + console.log('userId:', userId); + + // The correction from Day 1? Gone. + + # ============================================ + # THE DRIFT - Pattern 2: HTTP Client + # ============================================ + - type: code + id: drift-http + title: "Day 45: You correct again" + code: | + // Agent used axios + // You: "We standardized on fetch" + + const response = await fetch('/api/users', { + headers: { 'Authorization': `Bearer ${token}` } + }); + + - type: code + id: drift-http-2 + title: "Day 60: Another new session" + code: | + // Agent writes new code... + + import axios from 'axios'; + + const response = await axios.get('/api/users', { + headers: { 'Authorization': `Bearer ${token}` } + }); + + // Forgot again. Different session, different choices. + + # ============================================ + # THE SPIRAL + # ============================================ + - type: code + id: spiral + title: "6 months later: 10 ways to do 1 thing" + code: | + // Logging + console.log() // 47 files + winston.info() // 23 files + pino.info() // 12 files + debug() // 8 files + + // HTTP + fetch() // 31 files + axios.get() // 28 files + got() // 6 files + + // Auth + RS256 // 4 services + ES256 // 3 services + HS256 // 2 services (why??) + + - type: hook + id: spiral-question + line: "Which one is correct?" + subline: "Nobody knows. The decision was never recorded." + + # ============================================ + # THE CATASTROPHE + # ============================================ + - type: code + id: catastrophe title: "The Catastrophe" - subtitle: "When Proposals Look Like Decisions" - description: | - A 47-minute production outage because an AI agent couldn't - distinguish a proposal from an approved decision. + code: | + // Auth service A expects RS256 + // Auth service B was deployed with ES256 + // An agent queried "what's our JWT algorithm?" + // Got the most recent answer: ES256 (from an RFC proposal) - steps: - - id: cat-1 - from: research_agent - to: episteme - action: assert - label: "Store RFC finding" - data: - subject: "auth/jwt" - predicate: "signing_algorithm" - object: "ES256" - lifecycle: "proposed" - confidence: 0.75 - source: "security-rfc-2024.md" - note: "RFC proposes ES256. Stored as PROPOSED." + HTTP 401 Unauthorized + { + error: "invalid_signature", + expected: "RS256", + received: "ES256" + } - - id: cat-2 - from: lead_orchestrator - to: episteme - action: query - label: "What's the JWT algorithm?" - data: - subject: "auth/jwt" - predicate: "signing_algorithm" - lens: "recency" - danger: true - note: "No lifecycle filter. This is the bug." - callout: "lifecycle: ???" + // 3:00 AM. Pager fires. 47-minute outage. - - id: cat-3 - from: episteme - to: lead_orchestrator - action: response - label: "ES256 (conf: 0.87)" - data: - value: "ES256" - confidence: 0.87 - lifecycle: "proposed" - danger: true - note: "Returns the proposal. Most recent wins." + - type: code + id: catastrophe-why + title: "The Root Cause" + code: | + // The RFC was stored without lifecycle state + // The query returned the most recent entry + // No way to distinguish "proposed" from "approved" + // The agent treated an idea as truth - - id: cat-4 - from: lead_orchestrator - to: implementation_agent - action: delegate - label: "Use ES256 for JWT" - data: - algorithm: "ES256" - confidence: 0.87 - danger: true - note: "Orchestrator passes 'truth' downstream." - - - id: cat-5 - from: implementation_agent - to: deploy_agent - action: handoff - label: "Config ready" - data: - jwt_algorithm: "ES256" - danger: true - note: "Code written against ES256." - - - id: cat-6 - from: deploy_agent - to: production - action: deploy - label: "Deploy JWT config" - data: - config: - algorithm: "ES256" - danger: true - note: "Deployed with confidence. Tests passed." - - - id: cat-7 - from: production - to: production - action: error - label: "401 Unauthorized" - data: - error: "JWT signature validation failed" - expected: "RS256" - received: "ES256" - danger: true - note: "Auth service expects RS256. Every token fails." - callout: "3:00 AM - Pager fires" + // And now you have to audit 9 services + // to figure out which JWT algorithm is actually correct. # ============================================ - # SEQUENCE 2: THE CORRECT PATH + # THE FIX - Episteme # ============================================ - - id: correct_path - title: "The Correct Path" - subtitle: "With Lifecycle Filtering" - description: | - The same scenario, but with Episteme's lifecycle filtering. - Proposals stay proposals. Approved stays approved. + - type: hook + id: fix-intro + line: "What if corrections persisted?" + subline: "Across sessions. Across agents. Forever." - steps: - - id: cor-1 - from: research_agent - to: episteme - action: assert - label: "Store RFC finding" - data: - subject: "auth/jwt" - predicate: "signing_algorithm" - object: "ES256" - lifecycle: "proposed" - confidence: 0.75 - note: "Same RFC. Still stored as PROPOSED." + - type: code + id: fix-store + title: "Store decisions with context" + code: | + episteme.assert({ + subject: "project/logging", + predicate: "library", + value: "winston", - - id: cor-2 - from: lead_orchestrator - to: episteme - action: query - label: "What's the APPROVED JWT algorithm?" - data: - subject: "auth/jwt" - predicate: "signing_algorithm" - lens: "authority" - lifecycle: "approved" - success: true - note: "Lifecycle filter: approved only." - callout: "lifecycle: approved" + lifecycle: "approved", // not proposed, not deprecated + confidence: 1.0, // this is a decision, not a guess + source: "adr-0012" // traceable to a decision record + }); - - id: cor-3 - from: episteme - to: lead_orchestrator - action: response - label: "RS256 (conf: 0.92)" - data: - value: "RS256" - confidence: 0.92 - lifecycle: "approved" - source: "production-config.yaml" - success: true - note: "Returns the approved decision. Proposal excluded." + - type: code + id: fix-query + title: "Query with lifecycle filter" + code: | + // Before writing code, agent checks constraints - - id: cor-4 - from: lead_orchestrator - to: implementation_agent - action: delegate - label: "Use RS256 for JWT" - data: - algorithm: "RS256" - confidence: 0.92 - success: true - note: "Correct algorithm propagates." + const constraints = await episteme.query({ + subject: "project/logging", + lifecycle: "approved" + }); - - id: cor-5 - from: implementation_agent - to: episteme - action: query - label: "Pre-flight constraint check" - data: - context: "auth_jwt" - lens: "constraints" - success: true - note: "Check for forbidden patterns before coding." + // Returns: { library: "winston", confidence: 1.0 } - - id: cor-6 - from: episteme - to: implementation_agent - action: response - label: "No violations" - data: - constraints: [] - clear_to_proceed: true - success: true - note: "No negative constraints for RS256." + // Agent uses winston. Every time. Every session. - - id: cor-7 - from: implementation_agent - to: deploy_agent - action: handoff - label: "Config ready" - data: - jwt_algorithm: "RS256" - success: true - note: "Code written against RS256." + - type: code + id: fix-diff + title: "The difference" + code: | + // Without Episteme: + query({ subject: "auth/jwt", predicate: "algorithm" }) + // Returns: ES256 (most recent entry - a proposal) - - id: cor-8 - from: deploy_agent - to: production - action: deploy - label: "Deploy JWT config" - data: - config: - algorithm: "RS256" - success: true - note: "Deployed. Matches production expectation." - - - id: cor-9 - from: production - to: production - action: success - label: "200 OK" - data: - status: "healthy" - tokens_validated: true - success: true - note: "Auth works. No pager. Sleep continues." + // With Episteme: + query({ subject: "auth/jwt", predicate: "algorithm", lifecycle: "approved" }) + // Returns: RS256 (the actual decision) # ============================================ - # SEQUENCE 3: THE CORRECTION LOOP + # TIME TRAVEL # ============================================ - - id: correction_loop - title: "The Correction Loop" - subtitle: "Tracing, Fixing, Learning" - description: | - Post-incident: Human traces the bug, corrects the record, - and the Gardener ensures agents learn from the mistake. + - type: code + id: time-travel + title: "Debug what you believed, not what you know now" + code: | + // Post-incident: what did we believe at 9pm? - steps: - - id: fix-1 - from: human - to: episteme - action: query - label: "Trace deploy agent queries" - data: - type: "audit" - agent_id: "deploy_agent" - time_range: "-6h" - subject: "auth/*" - note: "SRE investigates: what did the agent believe?" + episteme.query({ + subject: "auth/jwt", + predicate: "algorithm", + as_of: "2024-01-15T21:00:00Z" + }); - - id: fix-2 - from: episteme - to: human - action: response - label: "Query audit trail" - data: - query_id: "q_7f3a2b" - timestamp: "2024-01-15T21:03:47Z" - subject: "auth/jwt" - predicate: "signing_algorithm" - lens: "recency" - lifecycle_filter: null - result: "ES256" - contributing: - - hash: "rfc_2024_001" - lifecycle: "proposed" - weight: 0.9 - danger: true - note: "Found it: no lifecycle filter. Proposal returned." - callout: "lifecycle_filter: null" + // Returns: ES256 (the belief at incident time) - - id: fix-3 - from: human - to: episteme - action: supersede - label: "Mark assertion incorrect" - data: - hash: "rfc_2024_001" - reason: "Proposal treated as approved decision" - type: "RequiresReview" - note: "Supersede the problematic assertion." + episteme.diff({ + subject: "auth/jwt", + from: "2024-01-15T14:00:00Z", + to: "2024-01-15T21:00:00Z" + }); - - id: fix-4 - from: episteme - to: gardener - action: trigger - label: "Correction event" - data: - superseded_hash: "rfc_2024_001" - superseding_agent: "human_supervisor" - affected_queries: ["q_7f3a2b"] - note: "Gardener wakes up." - - - id: fix-5 - from: gardener - to: episteme - action: update - label: "TrustRank back-propagation" - data: - agent_id: "lead_orchestrator" - topic: "auth/jwt" - delta: -0.15 - reason: "Query returned proposal as decision" - warning: true - note: "Lead Orchestrator's reputation on auth topics drops." - - - id: fix-6 - from: gardener - to: episteme - action: update - label: "Store negative constraint" - data: - subject: "auth/jwt" - predicate: "query_pattern" - must_use: "lifecycle=approved" - forbidden: "lifecycle=null" - reason: "Proposals must not be treated as decisions" - success: true - note: "Future queries will see this constraint." + // Shows: RFC proposal added at 2:32pm + // Root cause identified. # ============================================ - # SEQUENCE 4: PERSISTENT LEARNING + # CORRECTION # ============================================ - - id: persistent_learning - title: "Persistent Learning" - subtitle: "Fixing the Optimization Conflict" - description: | - 1 month later. New session. Empty context window. - But the lesson persists. + - type: code + id: correction + title: "Fix the record, not just the code" + code: | + // Mark the bad assertion + episteme.supersede({ + target: "ax7f3k9...", + reason: "RFC was proposal, not approved decision", + corrected_by: "sre-oncall" + }); - steps: - - id: learn-1 - from: human - to: episteme - action: assert - label: "Correct the agent" - data: - subject: "Project_X_Http_Client" - predicate: "must_use_library" - object: "axios" - meta: - forbidden_alternative: "requests" - reason: "requests library deprecated for this project" - confidence: 1.0 - lifecycle: "approved" - note: "Human stores correction with forbidden alternative." - callout: "Day 1" + // Add a constraint so it never happens again + episteme.assert({ + subject: "auth/jwt", + predicate: "algorithm", + value: "RS256", + lifecycle: "approved", + supersedes: "ax7f3k9..." + }); - - id: learn-2 - from: episteme - to: gardener - action: trigger - label: "Negative constraint stored" - data: - type: "correction" - agent_corrected: "implementation_agent" - note: "Gardener sees the correction event." - - - id: learn-3 - from: gardener - to: episteme - action: update - label: "TrustRank penalty" - data: - agent_id: "implementation_agent" - topic: "http_libraries" - delta: -0.20 - warning: true - note: "Implementation Agent's confidence on HTTP libs drops." - callout: "Learns from mistake" - - - id: learn-4 - from: implementation_agent - to: implementation_agent - action: start - label: "New session begins" - data: - context_window: "empty" - system_prompt: "default" - note: "30 days later. Fresh context. No memory of correction." - callout: "Day 30 - New Session" - - - id: learn-5 - from: implementation_agent - to: episteme - action: query - label: "Pre-flight constraint check" - data: - context: "python_http" - lens: "constraints" - success: true - note: "Before writing code, check constraints." - callout: "Automatic pre-flight" - - - id: learn-6 - from: episteme - to: implementation_agent - action: response - label: "Constraint found" - data: - constraints: - - subject: "Project_X_Http_Client" - must_use: "axios" - forbidden: "requests" - reason: "requests library deprecated for this project" - confidence: 1.0 - success: true - note: "The correction from Day 1 is still there." - callout: "Survived context window!" - - - id: learn-7 - from: implementation_agent - to: implementation_agent - action: generate - label: "Write code with axios" - data: - import: "axios" - avoided: "requests" - success: true - note: "Agent uses axios. Constraint honored." - - - id: learn-8 - from: episteme - to: episteme - action: resurrect - label: "Resurrection" - data: - constraint_hash: "axios_constraint" - last_verified: "now" - confidence: 1.0 - success: true - note: "Constraint used successfully. Stays fresh forever." - callout: "Resurrection" + // Future sessions will see this. Forever. # ============================================ - # SEQUENCE 5: TIME TRAVEL DEBUGGING + # VISION # ============================================ - - id: time_travel - title: "Time Travel Debugging" - subtitle: "What Did We Believe Then?" - description: | - 3:00 AM incident investigation. The SRE needs to know - what the system believed 6 hours ago, not now. - - steps: - - id: tt-1 - from: human - to: episteme - action: query - label: "What's the current JWT algorithm?" - data: - subject: "auth/jwt" - predicate: "signing_algorithm" - lifecycle: "approved" - note: "Current state shows RS256 (post-fix)." - - - id: tt-2 - from: episteme - to: human - action: response - label: "RS256 (current)" - data: - value: "RS256" - confidence: 0.95 - note: "This is useless for debugging. We need history." - - - id: tt-3 - from: human - to: episteme - action: query - label: "What did we believe at 9pm?" - data: - subject: "auth/jwt" - predicate: "signing_algorithm" - as_of: "2024-01-15T21:00:00Z" - note: "Time-travel query." - callout: "as_of: 9pm" - - - id: tt-4 - from: episteme - to: human - action: response - label: "ES256 (at 9pm)" - data: - value: "ES256" - confidence: 0.87 - lifecycle: "proposed" - as_of: "2024-01-15T21:00:00Z" - danger: true - note: "At 9pm, the system believed ES256 was correct." - callout: "Found the state at incident time" - - - id: tt-5 - from: human - to: episteme - action: query - label: "What changed in last 24h?" - data: - type: "diff" - subject: "auth/jwt" - from: "-24h" - note: "Diff view for change analysis." - - - id: tt-6 - from: episteme - to: human - action: response - label: "Diff result" - data: - added: - - hash: "rfc_2024_001" - value: "ES256" - lifecycle: "proposed" - added_at: "2024-01-15T14:30:00Z" - unchanged: - - hash: "prod_config_v2" - value: "RS256" - lifecycle: "approved" - success: true - note: "Clear view: RFC added at 2:30pm caused the issue." - -annotations: - danger: - color: "#EF4444" - label: "Problem" - icon: "alert-triangle" - warning: - color: "#F59E0B" - label: "Warning" - icon: "alert-circle" - success: - color: "#10B981" - label: "Success" - icon: "check-circle" - info: - color: "#3B82F6" - label: "Info" - icon: "info" + - type: vision + id: vision + title: "Episteme" + points: + - "Claims, not facts. Uncertainty is first-class." + - "Lifecycle awareness. Proposals ≠ decisions." + - "Corrections that persist across sessions." + - "Time travel for incident investigation." + tagline: "Git for Truth" diff --git a/docs/presentations/data/consumer-health-intelligence.yaml b/docs/presentations/data/consumer-health-intelligence.yaml new file mode 100644 index 0000000..8dd9d37 --- /dev/null +++ b/docs/presentations/data/consumer-health-intelligence.yaml @@ -0,0 +1,391 @@ +meta: + id: consumer-health-intelligence + title: "Consumer Health Intelligence" + subtitle: "The Living Truth Layer" + version: "1.0.0" + +actors: {} + +slides: + # ============================================ + # TITLE + # ============================================ + - type: title + id: title + + # ============================================ + # HOOK + # ============================================ + - type: hook + id: hook + line: "Your sources contradict each other." + subline: "And you have no way to weigh them." + + # ============================================ + # THE DRIFT - Seven sources, one hour + # ============================================ + - type: code + id: drift-doctor + title: "Source 1: Your doctor" + code: | + "Well-tolerated. Nausea is common but transient." + + // Confidence: high (MD, treating physician) + // Basis: prescribing guidelines, clinical experience + // What's missing: doesn't see Reddit, doesn't see FAERS + + - type: code + id: drift-fda + title: "Source 2: The FDA label" + code: | + WARNING: Thyroid C-cell tumors (boxed warning) + + Adverse reactions: + - Nausea (44%) + - Diarrhea (30%) + - Vomiting (24%) + + // No mention of gastroparesis (yet). + // Label last updated: 2021. + + - type: code + id: drift-reddit + title: "Source 3: Reddit (1.2M members)" + code: | + r/Ozempic - sorted by top, past month: + + "Ozempic face is real. I look 10 years older." [2.1k upvotes] + "Month 3: can't eat, stomach won't empty" [1.8k upvotes] + "Hair is falling out in clumps" [1.4k upvotes] + "Lost 40 lbs, feel amazing, life changed" [947 upvotes] + + // 4 posts. 4 different realities. + + - type: code + id: drift-tiktok + title: "Source 4: TikTok (4M views)" + code: | + @healthinfluencer: + "Ozempic gave me stomach paralysis. + I was in the ER for 3 days." + + 4.2M views | 340K likes | 12K comments + + // One person's experience. + // Presented as universal truth. + // Engagement = visibility, not validity. + + - type: code + id: drift-nejm + title: "Source 5: NEJM meta-analysis" + code: | + // Pooled analysis, n = 14,847 + // Design: randomized controlled trials + + Result: "No statistically significant increase + in gastroparesis incidence vs placebo" + + // p = 0.23, CI crosses 1.0 + // The gold standard says: no signal. + + - type: code + id: drift-faers + title: "Source 6: FDA Adverse Event Reports" + code: | + FAERS query: semaglutide + gastroparesis + + Total reports: 8,547 + Serious: 3,201 + Hospitalizations: 1,894 + Trend: increasing (2022-2024) + + // Self-reported + unverified. + // But 8,547 reports is a signal. + + - type: hook + id: drift-question + line: "Seven sources. Seven answers." + subline: "You make your decision based on whichever one you saw last." + + # ============================================ + # THE SPIRAL + # ============================================ + - type: code + id: spiral + title: "The same problem, everywhere" + code: | + // Gastroparesis: + Doctor: "Rare" + FDA: (not on label) + Reddit: "It happened to me" (x 4,200) + TikTok: "It's an epidemic" (12M views) + NEJM: "No significant signal" + FAERS: 8,547 reports + + // Hair loss: + Clinical trials: not studied + Reddit: 1,847 posts + Clinical evidence: zero + + // Muscle loss: + Phase III: "~40% of weight lost is lean mass" + Reddit: "My legs are wasting away" + Trainers: "Just lift weights" + + - type: hook + id: spiral-insight + line: "This is the vaccine problem." + subline: "Not misinformation. The absence of a system that can hold all claims and show you the shape of the evidence." + + # ============================================ + # THE CATASTROPHE + # ============================================ + - type: code + id: catastrophe + title: "The Catastrophe" + code: | + // June 2023: She starts Semaglutide. + // Her research: doctor + Google + a few Reddit posts. + // Gastroparesis wasn't on the FDA label. + // + // January 2024: FDA updates the label. + // Intestinal obstruction warning added. + // + // Reddit had flagged this a year earlier. + // FAERS reports were accumulating for two years. + // + // Nobody told her. Google doesn't send updates. + // Her doctor's office doesn't track label changes. + // The truth changed. Her information didn't. + + - type: code + id: catastrophe-pattern + title: "The pattern repeats" + code: | + // COVID vaccines, 2021: + // April: "No myocarditis signal" + // June: VAERS reports accumulating + // July: CDC acknowledges elevated risk in young males + // + // Millions of decisions made between April and July + // based on information that was about to change. + // + // Not because anyone lied. + // Because no system could show: + // "Here is what we know, at each level, + // and here is what changed since you last looked." + + # ============================================ + # THE FIX + # ============================================ + - type: hook + id: fix-intro + line: "What if every source had a weight?" + subline: "And the disagreement was the answer." + + - type: code + id: fix-tiers + title: "Source-class hierarchy" + code: | + // Not all sources are equal. Make it structural. + + Tier 0: Regulatory action weight: 1.0 decay: never + Tier 1: RCTs, meta-analyses weight: 0.9 decay: 2 years + Tier 2: Observational studies weight: 0.7 decay: 1 year + Tier 3: Pharmacovigilance weight: 0.5 decay: 18 months + Tier 4: Clinician case reports weight: 0.4 decay: 6 months + Tier 5: Patient community weight: 0.2 decay: 3 months + Tier 6: Media, influencers weight: 0.1 decay: 30 days + + // A million TikTok posts cannot outvote one FDA action. + // But they can signal that something is happening. + + - type: code + id: fix-assert + title: "Store claims with provenance" + code: | + // Clinical evidence enters with full metadata + episteme.assert({ + subject: "semaglutide/adverse-effects/gastroparesis", + predicate: "risk_level", + value: "No statistically significant increase", + source_class: "tier-1", + source: { + type: "meta-analysis", + journal: "NEJM", + sample_size: 14847 + }, + confidence: 0.92 + }); + + // Patient report enters the same graph + episteme.assert({ + subject: "semaglutide/adverse-effects/gastroparesis", + predicate: "risk_level", + value: "Experienced severe gastroparesis after 3 months", + source_class: "tier-5", + source: { platform: "reddit", upvotes: 847 }, + confidence: 0.3 + }); + + // Both coexist. Neither overwrites. But they are not equal. + + - type: code + id: fix-query + title: "Query returns layers, not a single answer" + code: | + episteme.query({ + subject: "semaglutide/adverse-effects/gastroparesis", + lens: "layered-consensus" + }); + + // Returns: + { + regulatory: "Added to label Jan 2024", + clinical_evidence: "No signal in Phase III (conflict: 0.34)", + pharmacovigilance: "8,547 FAERS reports, trend: increasing", + patient_community: "Widely reported, cluster size: 4,200", + + overall_conflict: 0.72, + summary: "Trials show low incidence. Post-marketing and + patient reports show higher rates. FDA added + to label January 2024." + } + + // Not "yes" or "no". The shape of the evidence. + + # ============================================ + # CLUSTER ESCALATION + # ============================================ + - type: code + id: escalation + title: "Anecdotal signal detection" + code: | + // The Gardener monitors Tier 5 clusters. + // When density crosses threshold: + + episteme.assert({ + subject: "semaglutide/adverse-effects/hair-loss", + predicate: "escalation_signal", + value: "Anecdotal cluster detected", + source_class: "meta", + meta: { + tier_5_count: 1847, + growth_rate: "312/month", + tier_1_count: 0, // no clinical evidence exists + clinical_gap: true + }, + lifecycle: "under-review" + }); + + // Does NOT claim hair loss is real. + // Claims: "people are reporting this, and nobody has studied it." + // The gap is the signal. + + # ============================================ + # GUIDANCE CHANGES + # ============================================ + - type: code + id: guidance-change + title: "What changed since you last looked" + code: | + // FDA updates the label. Epoch shifts. + episteme.epoch.supersede({ + old_epoch: "semaglutide-label-pre-2024", + new_epoch: "semaglutide-label-2024-01", + reason: "Intestinal obstruction warning added" + }); + + // Consumer returns 3 months later: + episteme.query({ + subject: "semaglutide/adverse-effects", + lens: "layered-consensus", + since: "2023-10-01" // their last visit + }); + + // Returns: + { + changes: [{ + date: "2024-01-12", + type: "regulatory", + change: "Intestinal obstruction added to warnings" + }], + prior_assertions_affected: 12 + } + + // Not just today's answer. What changed. + + # ============================================ + # TIME TRAVEL + # ============================================ + - type: code + id: time-travel + title: "What was known when you decided?" + code: | + // "I started Semaglutide in June 2023. + // What were the known risks at that time?" + + episteme.query({ + subject: "semaglutide/adverse-effects", + lens: "layered-consensus", + as_of: "2023-06-15" + }); + + // Returns the June 2023 snapshot: + { + regulatory: "Boxed warning: thyroid. No GI obstruction.", + clinical: "Nausea common, no gastroparesis signal", + patient: "Growing reports (cluster size: 340)", + escalation: "not yet triggered (threshold: 500)" + } + + // Your decision was reasonable given available evidence. + // The record proves it. + + # ============================================ + # DISAGREEMENT DASHBOARD + # ============================================ + - type: code + id: disagreement + title: "The disagreement dashboard" + code: | + episteme.query({ + subject: "semaglutide", + lens: "skeptic", + scope: "adverse-effects" + }); + + // Returns: + resolved: [ + { topic: "nausea", conflict: 0.08, "all tiers agree" } + ] + + active_disagreement: [ + { topic: "gastroparesis", conflict: 0.72, + clinical: "Low incidence", + faers: "8,547 reports", + patients: "Widely reported" } + ] + + emerging_signal: [ + { topic: "hair loss", + clinical_evidence: "none", + patient_reports: 1847, + status: "under-review" } + ] + + // Settled. Contested. Emerging. + // Honest answers, not false certainty. + + # ============================================ + # VISION + # ============================================ + - type: vision + id: vision + title: "Episteme" + points: + - "Source-class hierarchy. Not all claims are equal." + - "Anecdotal signals surfaced without false authority." + - "Guidance changes propagated, not buried." + - "Time travel to the evidence at any moment." + tagline: "Git for Truth" diff --git a/docs/presentations/data/sec-analysis.yaml b/docs/presentations/data/sec-analysis.yaml new file mode 100644 index 0000000..58b37df --- /dev/null +++ b/docs/presentations/data/sec-analysis.yaml @@ -0,0 +1,311 @@ +meta: + id: sec-analysis + title: "SEC Document Analysis" + subtitle: "Filing Intelligence with Episteme" + version: "1.0.0" + +actors: {} + +slides: + # ============================================ + # TITLE + # ============================================ + - type: title + id: title + + # ============================================ + # HOOK + # ============================================ + - type: hook + id: hook + line: "Your filings contradict each other." + subline: "And every agent reading them gets a different answer." + + # ============================================ + # THE DRIFT - Revenue + # ============================================ + - type: code + id: drift-revenue + title: "10-K: Annual revenue" + code: | + // Agent extracts from 10-K filing + // CIK: 0001234567, Filed: 2024-02-28 + + { + "subject": "ACME/revenue/annual", + "source": "10-K/2023", + "value": "$847M" + } + + - type: code + id: drift-revenue-2 + title: "10-Q: Quarterly revenue tells a different story" + code: | + // Agent extracts from Q4 10-Q filing + // Same company, same fiscal year + + { + "subject": "ACME/revenue/Q4", + "source": "10-Q/2023-Q4", + "value": "$218M" + } + + // Q1 + Q2 + Q3 + Q4 = $872M annualized + // 10-K says $847M + // Delta: $25M. Which is right? + + # ============================================ + # THE DRIFT - Amendments + # ============================================ + - type: code + id: drift-amendment + title: "Original 10-K: No impairment" + code: | + // Filed: 2024-02-28 + // Form: 10-K + + { + "subject": "ACME/goodwill/impairment", + "source": "10-K/2023", + "value": "$0" + } + + // Clean bill of health. + + - type: code + id: drift-amendment-2 + title: "10-K/A: $340M impairment appears" + code: | + // Filed: 2024-06-15 (amended filing) + // Form: 10-K/A + + { + "subject": "ACME/goodwill/impairment", + "source": "10-K-A/2023", + "value": "$340M" + } + + // The amendment supersedes the original. + // But which sections? All of them? Just Note 7? + // The rest of the 10-K -- still valid? + + # ============================================ + # THE SPIRAL + # ============================================ + - type: code + id: spiral + title: "Same data, extracted 3 times, 3 answers" + code: | + // Q3 Revenue appears in: + "10-Q/2023-Q3" -> $213M // quarterly filing + "10-K/2023" -> $209M // annual summary table + "DEF 14A/2024" -> $211M // proxy exec comp section + + // Two analysts read the same proxy statement + // Analyst A: CEO comp = $14.2M (includes options) + // Analyst B: CEO comp = $8.7M (base + bonus only) + + // Both are "correct" -- different definitions + + - type: hook + id: spiral-question + line: "Which extraction is correct?" + subline: "Depends on the filing, the section, and what you're measuring." + + # ============================================ + # THE CATASTROPHE + # ============================================ + - type: code + id: catastrophe + title: "The Catastrophe" + code: | + // Agent builds a DCF model + // Revenue: pulled from 10-K/A -> $847M (amended) + // Cost of revenue: pulled from 10-K -> $612M (original) + // + // But the amendment changed cost allocations too. + // Actual cost of revenue post-amendment: $658M + // + // Gross margin: 27.7% (agent's model) + // Actual: 22.3% + // + // DCF valuation: off by $180M + // + // The model mixed amended and pre-amendment data + // because there was no way to track the amendment chain. + + - type: code + id: catastrophe-why + title: "The Root Cause" + code: | + // Filings were stored as flat key-value pairs + // No amendment chain linking 10-K to 10-K/A + // No section-level tracking + // No way to know which data points were superseded + // + // The agent had no concept of "this number was restated" + // It just grabbed the first match for each field + // + // Garbage in, $180M garbage out. + + # ============================================ + # THE FIX - Episteme + # ============================================ + - type: hook + id: fix-intro + line: "What if filings carried their own lineage?" + subline: "Every extraction linked to its source, section, and amendment chain." + + - type: code + id: fix-store + title: "Store extractions with filing metadata" + code: | + episteme.assert({ + subject: "ACME/revenue/annual/2023", + predicate: "value", + value: "$847M", + + source: { + cik: "0001234567", + form: "10-K", + filed: "2024-02-28", + section: "Part II, Item 8", + accession: "0001234567-24-000042" + }, + + lifecycle: "current", + confidence: 0.95 + }); + + - type: code + id: fix-amendment + title: "Amendments supersede cleanly" + code: | + // When the 10-K/A arrives: + episteme.assert({ + subject: "ACME/goodwill/impairment/2023", + predicate: "value", + value: "$340M", + + source: { + form: "10-K/A", + filed: "2024-06-15", + amends: "0001234567-24-000042", // links to original + sections_amended: ["Note 7", "Part II Item 8"] + }, + + lifecycle: "current", + supersedes: "ax7f3k9..." // the $0 assertion + }); + + // The original $0 assertion is now lifecycle: "superseded" + // Sections NOT in sections_amended remain valid + + - type: code + id: fix-query + title: "Query with lifecycle: only current data" + code: | + // Agent building a DCF model queries: + const revenue = await episteme.query({ + subject: "ACME/revenue/annual/2023", + lifecycle: "current" + }); + // Returns $847M from 10-K/A (amended value) + + const cost = await episteme.query({ + subject: "ACME/cost-of-revenue/annual/2023", + lifecycle: "current" + }); + // Returns $658M from 10-K/A (amended value) + + // Both values from the same amendment. + // No mixing. No $180M error. + + # ============================================ + # TIME TRAVEL + # ============================================ + - type: code + id: time-travel + title: "What did we believe before the restatement?" + code: | + // Audit question: what was our position on March 1? + // (before the 10-K/A was filed on June 15) + + episteme.query({ + subject: "ACME/goodwill/impairment/2023", + as_of: "2024-03-01T00:00:00Z" + }); + + // Returns: $0 (the original 10-K assertion) + // At that point, that WAS the truth. + + episteme.diff({ + subject: "ACME/goodwill/impairment/2023", + from: "2024-03-01", + to: "2024-07-01" + }); + + // Shows: 10-K/A filed June 15, impairment changed $0 -> $340M + // Full audit trail. No guessing. + + # ============================================ + # MULTI-ANALYST + # ============================================ + - type: code + id: multi-analyst + title: "Competing extractions coexist" + code: | + // Analyst A extracts CEO comp from proxy (DEF 14A) + episteme.assert({ + subject: "ACME/exec-comp/CEO/2023", + value: "$14.2M", + source: { form: "DEF 14A", section: "Summary Compensation" }, + confidence: 0.9, + author: "analyst-A" + }); + + // Analyst B extracts from the same proxy + episteme.assert({ + subject: "ACME/exec-comp/CEO/2023", + value: "$8.7M", + source: { form: "DEF 14A", section: "Summary Compensation" }, + confidence: 0.85, + author: "analyst-B" + }); + + // Both assertions coexist. No overwrite. + + - type: code + id: multi-analyst-resolve + title: "Lens resolves at query time" + code: | + // Default lens: highest confidence wins + episteme.query({ + subject: "ACME/exec-comp/CEO/2023", + lens: "authority" + }); + // Returns: $14.2M (analyst-A, confidence 0.9) + + // But you can ask: show me all claims + episteme.query({ + subject: "ACME/exec-comp/CEO/2023", + lens: "all" + }); + // Returns both: $14.2M and $8.7M + // With full provenance on each + + // The disagreement IS the signal. + // Someone needs to reconcile definitions. + + # ============================================ + # VISION + # ============================================ + - type: vision + id: vision + title: "Episteme" + points: + - "Amendment chains, not flat overwrites." + - "Section-level provenance for every extraction." + - "Competing analyst reads coexist until resolved." + - "Time travel for audit and restatement analysis." + tagline: "Git for Truth" diff --git a/docs/presentations/generated/agile-agent-team-catastrophe.mmd b/docs/presentations/generated/agile-agent-team-catastrophe.mmd index 1eeac7c..dc396fb 100644 --- a/docs/presentations/generated/agile-agent-team-catastrophe.mmd +++ b/docs/presentations/generated/agile-agent-team-catastrophe.mmd @@ -1,10 +1,9 @@ sequenceDiagram - %% The Catastrophe: When Proposals Look Like Decisions + %% The Catastrophe participant RA as Research Agent participant E as Episteme participant LO as Lead Orchestrator - participant IA as Implementation Agent participant DA as Deploy Agent participant P as Production @@ -17,13 +16,7 @@ sequenceDiagram E-->>LO: ES256 (conf: 0.87) Note right of LO: ⚠️ Returns the proposal. Most recent wins. - LO->>IA: Use ES256 for JWT - Note right of IA: ⚠️ Orchestrator passes 'truth' downstream. - - IA->>DA: Config ready - Note right of DA: ⚠️ Code written against ES256. - - DA->>P: Deploy JWT config + DA->>P: Deploy ES256 config Note right of P: ⚠️ Deployed with confidence. Tests passed. P->>P: 401 Unauthorized diff --git a/docs/presentations/generated/agile-agent-team-correct_path.mmd b/docs/presentations/generated/agile-agent-team-correct_path.mmd index 696f419..3d5f8fa 100644 --- a/docs/presentations/generated/agile-agent-team-correct_path.mmd +++ b/docs/presentations/generated/agile-agent-team-correct_path.mmd @@ -1,35 +1,22 @@ sequenceDiagram - %% The Correct Path: With Lifecycle Filtering + %% The Correct Path participant RA as Research Agent participant E as Episteme participant LO as Lead Orchestrator - participant IA as Implementation Agent participant DA as Deploy Agent participant P as Production RA->>E: Store RFC finding Note right of E: Same RFC. Still stored as PROPOSED. - LO->>E: What's the APPROVED JWT algorithm? + LO->>E: What's the APPROVED algorithm? Note right of E: ✓ Lifecycle filter: approved only. E-->>LO: RS256 (conf: 0.92) Note right of LO: ✓ Returns the approved decision. Proposal excluded. - LO->>IA: Use RS256 for JWT - Note right of IA: ✓ Correct algorithm propagates. - - IA->>E: Pre-flight constraint check - Note right of E: ✓ Check for forbidden patterns before coding. - - E-->>IA: No violations - Note right of IA: ✓ No negative constraints for RS256. - - IA->>DA: Config ready - Note right of DA: ✓ Code written against RS256. - - DA->>P: Deploy JWT config + DA->>P: Deploy RS256 config Note right of P: ✓ Deployed. Matches production expectation. P->>P: 200 OK diff --git a/docs/presentations/generated/agile-agent-team-correction_loop.mmd b/docs/presentations/generated/agile-agent-team-correction_loop.mmd index a9a96cb..51261be 100644 --- a/docs/presentations/generated/agile-agent-team-correction_loop.mmd +++ b/docs/presentations/generated/agile-agent-team-correction_loop.mmd @@ -1,24 +1,18 @@ sequenceDiagram - %% The Correction Loop: Tracing, Fixing, Learning + %% The Correction Loop participant H as Human Supervisor participant E as Episteme participant G as Gardener - H->>E: Trace deploy agent queries - Note right of E: SRE investigates: what did the agent believe? + H->>E: What did the agent query? + Note right of E: SRE investigates the incident. E-->>H: Query audit trail - Note right of H: ⚠️ Found it: no lifecycle filter. Proposal returned. + Note right of H: ⚠️ Found it: no lifecycle filter used. H->>E: Mark assertion incorrect - Note right of E: Supersede the problematic assertion. - - E->>G: Correction event - Note right of G: Gardener wakes up. - - G->>E: TrustRank back-propagation - Note right of E: Lead Orchestrator's reputation on auth topics drops. + Note right of E: Correct the record. G->>E: Store negative constraint Note right of E: ✓ Future queries will see this constraint. diff --git a/docs/presentations/generated/agile-agent-team-persistent_learning.mmd b/docs/presentations/generated/agile-agent-team-persistent_learning.mmd index e8cdd3b..7fdddf5 100644 --- a/docs/presentations/generated/agile-agent-team-persistent_learning.mmd +++ b/docs/presentations/generated/agile-agent-team-persistent_learning.mmd @@ -1,31 +1,21 @@ sequenceDiagram - %% Persistent Learning: Fixing the Optimization Conflict + %% Persistent Learning participant H as Human Supervisor participant E as Episteme - participant G as Gardener participant IA as Implementation Agent H->>E: Correct the agent - Note right of E: Human stores correction with forbidden alternative. - - E->>G: Negative constraint stored - Note right of G: Gardener sees the correction event. - - G->>E: TrustRank penalty - Note right of E: Implementation Agent's confidence on HTTP libs drops. + Note right of E: Human stores: use axios, not requests. IA->>IA: New session begins - Note over IA: 30 days later. Fresh context. No memory of correction. + Note over IA: 30 days later. Fresh context window. IA->>E: Pre-flight constraint check Note right of E: ✓ Before writing code, check constraints. - E-->>IA: Constraint found - Note right of IA: ✓ The correction from Day 1 is still there. + E-->>IA: Constraint found: use axios + Note right of IA: ✓ The correction from Day 1 persists. - IA->>IA: Write code with axios + IA->>IA: Write correct code Note over IA: ✓ Agent uses axios. Constraint honored. - - E->>E: Resurrection - Note over E: ✓ Constraint used successfully. Stays fresh forever. diff --git a/docs/presentations/generated/agile-agent-team-time_travel.mmd b/docs/presentations/generated/agile-agent-team-time_travel.mmd index cddaf73..4a3a141 100644 --- a/docs/presentations/generated/agile-agent-team-time_travel.mmd +++ b/docs/presentations/generated/agile-agent-team-time_travel.mmd @@ -1,23 +1,17 @@ sequenceDiagram - %% Time Travel Debugging: What Did We Believe Then? + %% Time Travel Debugging participant H as Human Supervisor participant E as Episteme - H->>E: What's the current JWT algorithm? - Note right of E: Current state shows RS256 (post-fix). - - E-->>H: RS256 (current) - Note right of H: This is useless for debugging. We need history. + H->>E: Current state? + Note right of E: Shows RS256 (post-fix). Useless for debugging. H->>E: What did we believe at 9pm? Note right of E: Time-travel query. E-->>H: ES256 (at 9pm) - Note right of H: ⚠️ At 9pm, the system believed ES256 was correct. + Note right of H: ⚠️ Found it. This was the state at incident time. - H->>E: What changed in last 24h? - Note right of E: Diff view for change analysis. - - E-->>H: Diff result - Note right of H: ✓ Clear view: RFC added at 2:30pm caused the issue. + E-->>H: Diff: RFC added at 2:30pm + Note right of H: ✓ Clear timeline of what changed and when. diff --git a/docs/presentations/generated/agile-agent-team.json b/docs/presentations/generated/agile-agent-team.json index 140e163..492a2c3 100644 --- a/docs/presentations/generated/agile-agent-team.json +++ b/docs/presentations/generated/agile-agent-team.json @@ -3,1293 +3,115 @@ "id": "agile-agent-team", "title": "Agile AI Agent Team", "subtitle": "Knowledge Coordination with Episteme", - "version": "1.0.0" - }, - "actors": { - "research_agent": { - "id": "RA", - "label": "Research Agent", - "description": "Ingests external sources, stores with uncertainty", - "color": "#3B82F6" - }, - "lead_orchestrator": { - "id": "LO", - "label": "Lead Orchestrator", - "description": "Coordinates team, routes work based on knowledge", - "color": "#8B5CF6" - }, - "implementation_agent": { - "id": "IA", - "label": "Implementation Agent", - "description": "Writes code against current patterns", - "color": "#10B981" - }, - "deploy_agent": { - "id": "DA", - "label": "Deploy Agent", - "description": "Deploys configurations to production", - "color": "#F59E0B" - }, - "episteme": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - }, - "human": { - "id": "H", - "label": "Human Supervisor", - "description": "Reviews decisions, corrects errors", - "color": "#EC4899" - }, - "gardener": { - "id": "G", - "label": "Gardener", - "description": "Background worker for TrustRank propagation", - "color": "#14B8A6" - }, - "production": { - "id": "P", - "label": "Production", - "description": "Live system", - "color": "#EF4444" - } - }, - "annotations": { - "danger": { - "color": "#EF4444", - "label": "Problem", - "icon": "alert-triangle" - }, - "warning": { - "color": "#F59E0B", - "label": "Warning", - "icon": "alert-circle" - }, - "success": { - "color": "#10B981", - "label": "Success", - "icon": "check-circle" - }, - "info": { - "color": "#3B82F6", - "label": "Info", - "icon": "info" - } + "version": "4.0.0" }, + "actors": {}, "slides": [ { "type": "title", - "title": "Agile AI Agent Team", - "subtitle": "Knowledge Coordination with Episteme" + "id": "title" }, { - "type": "section-title", + "type": "hook", + "id": "hook", + "line": "Your agents have amnesia.", + "subline": "Every correction you make is forgotten by the next session." + }, + { + "type": "code", + "id": "drift-logging", + "title": "Day 1: You correct the agent", + "code": "// Agent used console.log\n// You: \"We use winston, not console.log\"\n\nimport { logger } from './logger';\n\nlogger.info('User authenticated', { userId });\n" + }, + { + "type": "code", + "id": "drift-logging-2", + "title": "Day 30: New session", + "code": "// Agent writes new code...\n\nconsole.log('User authenticated');\nconsole.log('userId:', userId);\n\n// The correction from Day 1? Gone.\n" + }, + { + "type": "code", + "id": "drift-http", + "title": "Day 45: You correct again", + "code": "// Agent used axios\n// You: \"We standardized on fetch\"\n\nconst response = await fetch('/api/users', {\n headers: { 'Authorization': `Bearer ${token}` }\n});\n" + }, + { + "type": "code", + "id": "drift-http-2", + "title": "Day 60: Another new session", + "code": "// Agent writes new code...\n\nimport axios from 'axios';\n\nconst response = await axios.get('/api/users', {\n headers: { 'Authorization': `Bearer ${token}` }\n});\n\n// Forgot again. Different session, different choices.\n" + }, + { + "type": "code", + "id": "spiral", + "title": "6 months later: 10 ways to do 1 thing", + "code": "// Logging\nconsole.log() // 47 files\nwinston.info() // 23 files\npino.info() // 12 files\ndebug() // 8 files\n\n// HTTP\nfetch() // 31 files\naxios.get() // 28 files\ngot() // 6 files\n\n// Auth\nRS256 // 4 services\nES256 // 3 services\nHS256 // 2 services (why??)\n" + }, + { + "type": "hook", + "id": "spiral-question", + "line": "Which one is correct?", + "subline": "Nobody knows. The decision was never recorded." + }, + { + "type": "code", + "id": "catastrophe", "title": "The Catastrophe", - "subtitle": "When Proposals Look Like Decisions", - "description": "A 47-minute production outage because an AI agent couldn't\ndistinguish a proposal from an approved decision.\n" + "code": "// Auth service A expects RS256\n// Auth service B was deployed with ES256\n// An agent queried \"what's our JWT algorithm?\"\n// Got the most recent answer: ES256 (from an RFC proposal)\n\nHTTP 401 Unauthorized\n{\n error: \"invalid_signature\",\n expected: \"RS256\",\n received: \"ES256\"\n}\n\n// 3:00 AM. Pager fires. 47-minute outage.\n" }, { - "type": "sequence", - "sequenceId": "catastrophe", - "title": "The Catastrophe", - "actors": { - "research_agent": { - "id": "RA", - "label": "Research Agent", - "description": "Ingests external sources, stores with uncertainty", - "color": "#3B82F6" - }, - "episteme": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - }, - "lead_orchestrator": { - "id": "LO", - "label": "Lead Orchestrator", - "description": "Coordinates team, routes work based on knowledge", - "color": "#8B5CF6" - }, - "implementation_agent": { - "id": "IA", - "label": "Implementation Agent", - "description": "Writes code against current patterns", - "color": "#10B981" - }, - "deploy_agent": { - "id": "DA", - "label": "Deploy Agent", - "description": "Deploys configurations to production", - "color": "#F59E0B" - }, - "production": { - "id": "P", - "label": "Production", - "description": "Live system", - "color": "#EF4444" - } - }, - "steps": [ - { - "id": "cat-1", - "from": "research_agent", - "to": "episteme", - "action": "assert", - "label": "Store RFC finding", - "data": { - "subject": "auth/jwt", - "predicate": "signing_algorithm", - "object": "ES256", - "lifecycle": "proposed", - "confidence": 0.75, - "source": "security-rfc-2024.md" - }, - "note": "RFC proposes ES256. Stored as PROPOSED.", - "index": 0, - "fromActor": { - "id": "RA", - "label": "Research Agent", - "description": "Ingests external sources, stores with uncertainty", - "color": "#3B82F6" - }, - "toActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - } - }, - { - "id": "cat-2", - "from": "lead_orchestrator", - "to": "episteme", - "action": "query", - "label": "What's the JWT algorithm?", - "data": { - "subject": "auth/jwt", - "predicate": "signing_algorithm", - "lens": "recency" - }, - "danger": true, - "note": "No lifecycle filter. This is the bug.", - "callout": "lifecycle: ???", - "index": 1, - "fromActor": { - "id": "LO", - "label": "Lead Orchestrator", - "description": "Coordinates team, routes work based on knowledge", - "color": "#8B5CF6" - }, - "toActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - } - }, - { - "id": "cat-3", - "from": "episteme", - "to": "lead_orchestrator", - "action": "response", - "label": "ES256 (conf: 0.87)", - "data": { - "value": "ES256", - "confidence": 0.87, - "lifecycle": "proposed" - }, - "danger": true, - "note": "Returns the proposal. Most recent wins.", - "index": 2, - "fromActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - }, - "toActor": { - "id": "LO", - "label": "Lead Orchestrator", - "description": "Coordinates team, routes work based on knowledge", - "color": "#8B5CF6" - } - }, - { - "id": "cat-4", - "from": "lead_orchestrator", - "to": "implementation_agent", - "action": "delegate", - "label": "Use ES256 for JWT", - "data": { - "algorithm": "ES256", - "confidence": 0.87 - }, - "danger": true, - "note": "Orchestrator passes 'truth' downstream.", - "index": 3, - "fromActor": { - "id": "LO", - "label": "Lead Orchestrator", - "description": "Coordinates team, routes work based on knowledge", - "color": "#8B5CF6" - }, - "toActor": { - "id": "IA", - "label": "Implementation Agent", - "description": "Writes code against current patterns", - "color": "#10B981" - } - }, - { - "id": "cat-5", - "from": "implementation_agent", - "to": "deploy_agent", - "action": "handoff", - "label": "Config ready", - "data": { - "jwt_algorithm": "ES256" - }, - "danger": true, - "note": "Code written against ES256.", - "index": 4, - "fromActor": { - "id": "IA", - "label": "Implementation Agent", - "description": "Writes code against current patterns", - "color": "#10B981" - }, - "toActor": { - "id": "DA", - "label": "Deploy Agent", - "description": "Deploys configurations to production", - "color": "#F59E0B" - } - }, - { - "id": "cat-6", - "from": "deploy_agent", - "to": "production", - "action": "deploy", - "label": "Deploy JWT config", - "data": { - "config": { - "algorithm": "ES256" - } - }, - "danger": true, - "note": "Deployed with confidence. Tests passed.", - "index": 5, - "fromActor": { - "id": "DA", - "label": "Deploy Agent", - "description": "Deploys configurations to production", - "color": "#F59E0B" - }, - "toActor": { - "id": "P", - "label": "Production", - "description": "Live system", - "color": "#EF4444" - } - }, - { - "id": "cat-7", - "from": "production", - "to": "production", - "action": "error", - "label": "401 Unauthorized", - "data": { - "error": "JWT signature validation failed", - "expected": "RS256", - "received": "ES256" - }, - "danger": true, - "note": "Auth service expects RS256. Every token fails.", - "callout": "3:00 AM - Pager fires", - "index": 6, - "fromActor": { - "id": "P", - "label": "Production", - "description": "Live system", - "color": "#EF4444" - }, - "toActor": { - "id": "P", - "label": "Production", - "description": "Live system", - "color": "#EF4444" - } - } - ] + "type": "code", + "id": "catastrophe-why", + "title": "The Root Cause", + "code": "// The RFC was stored without lifecycle state\n// The query returned the most recent entry\n// No way to distinguish \"proposed\" from \"approved\"\n// The agent treated an idea as truth\n\n// And now you have to audit 9 services\n// to figure out which JWT algorithm is actually correct.\n" }, { - "type": "section-title", - "title": "The Correct Path", - "subtitle": "With Lifecycle Filtering", - "description": "The same scenario, but with Episteme's lifecycle filtering.\nProposals stay proposals. Approved stays approved.\n" + "type": "hook", + "id": "fix-intro", + "line": "What if corrections persisted?", + "subline": "Across sessions. Across agents. Forever." }, { - "type": "sequence", - "sequenceId": "correct_path", - "title": "The Correct Path", - "actors": { - "research_agent": { - "id": "RA", - "label": "Research Agent", - "description": "Ingests external sources, stores with uncertainty", - "color": "#3B82F6" - }, - "episteme": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - }, - "lead_orchestrator": { - "id": "LO", - "label": "Lead Orchestrator", - "description": "Coordinates team, routes work based on knowledge", - "color": "#8B5CF6" - }, - "implementation_agent": { - "id": "IA", - "label": "Implementation Agent", - "description": "Writes code against current patterns", - "color": "#10B981" - }, - "deploy_agent": { - "id": "DA", - "label": "Deploy Agent", - "description": "Deploys configurations to production", - "color": "#F59E0B" - }, - "production": { - "id": "P", - "label": "Production", - "description": "Live system", - "color": "#EF4444" - } - }, - "steps": [ - { - "id": "cor-1", - "from": "research_agent", - "to": "episteme", - "action": "assert", - "label": "Store RFC finding", - "data": { - "subject": "auth/jwt", - "predicate": "signing_algorithm", - "object": "ES256", - "lifecycle": "proposed", - "confidence": 0.75 - }, - "note": "Same RFC. Still stored as PROPOSED.", - "index": 0, - "fromActor": { - "id": "RA", - "label": "Research Agent", - "description": "Ingests external sources, stores with uncertainty", - "color": "#3B82F6" - }, - "toActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - } - }, - { - "id": "cor-2", - "from": "lead_orchestrator", - "to": "episteme", - "action": "query", - "label": "What's the APPROVED JWT algorithm?", - "data": { - "subject": "auth/jwt", - "predicate": "signing_algorithm", - "lens": "authority", - "lifecycle": "approved" - }, - "success": true, - "note": "Lifecycle filter: approved only.", - "callout": "lifecycle: approved", - "index": 1, - "fromActor": { - "id": "LO", - "label": "Lead Orchestrator", - "description": "Coordinates team, routes work based on knowledge", - "color": "#8B5CF6" - }, - "toActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - } - }, - { - "id": "cor-3", - "from": "episteme", - "to": "lead_orchestrator", - "action": "response", - "label": "RS256 (conf: 0.92)", - "data": { - "value": "RS256", - "confidence": 0.92, - "lifecycle": "approved", - "source": "production-config.yaml" - }, - "success": true, - "note": "Returns the approved decision. Proposal excluded.", - "index": 2, - "fromActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - }, - "toActor": { - "id": "LO", - "label": "Lead Orchestrator", - "description": "Coordinates team, routes work based on knowledge", - "color": "#8B5CF6" - } - }, - { - "id": "cor-4", - "from": "lead_orchestrator", - "to": "implementation_agent", - "action": "delegate", - "label": "Use RS256 for JWT", - "data": { - "algorithm": "RS256", - "confidence": 0.92 - }, - "success": true, - "note": "Correct algorithm propagates.", - "index": 3, - "fromActor": { - "id": "LO", - "label": "Lead Orchestrator", - "description": "Coordinates team, routes work based on knowledge", - "color": "#8B5CF6" - }, - "toActor": { - "id": "IA", - "label": "Implementation Agent", - "description": "Writes code against current patterns", - "color": "#10B981" - } - }, - { - "id": "cor-5", - "from": "implementation_agent", - "to": "episteme", - "action": "query", - "label": "Pre-flight constraint check", - "data": { - "context": "auth_jwt", - "lens": "constraints" - }, - "success": true, - "note": "Check for forbidden patterns before coding.", - "index": 4, - "fromActor": { - "id": "IA", - "label": "Implementation Agent", - "description": "Writes code against current patterns", - "color": "#10B981" - }, - "toActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - } - }, - { - "id": "cor-6", - "from": "episteme", - "to": "implementation_agent", - "action": "response", - "label": "No violations", - "data": { - "constraints": [], - "clear_to_proceed": true - }, - "success": true, - "note": "No negative constraints for RS256.", - "index": 5, - "fromActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - }, - "toActor": { - "id": "IA", - "label": "Implementation Agent", - "description": "Writes code against current patterns", - "color": "#10B981" - } - }, - { - "id": "cor-7", - "from": "implementation_agent", - "to": "deploy_agent", - "action": "handoff", - "label": "Config ready", - "data": { - "jwt_algorithm": "RS256" - }, - "success": true, - "note": "Code written against RS256.", - "index": 6, - "fromActor": { - "id": "IA", - "label": "Implementation Agent", - "description": "Writes code against current patterns", - "color": "#10B981" - }, - "toActor": { - "id": "DA", - "label": "Deploy Agent", - "description": "Deploys configurations to production", - "color": "#F59E0B" - } - }, - { - "id": "cor-8", - "from": "deploy_agent", - "to": "production", - "action": "deploy", - "label": "Deploy JWT config", - "data": { - "config": { - "algorithm": "RS256" - } - }, - "success": true, - "note": "Deployed. Matches production expectation.", - "index": 7, - "fromActor": { - "id": "DA", - "label": "Deploy Agent", - "description": "Deploys configurations to production", - "color": "#F59E0B" - }, - "toActor": { - "id": "P", - "label": "Production", - "description": "Live system", - "color": "#EF4444" - } - }, - { - "id": "cor-9", - "from": "production", - "to": "production", - "action": "success", - "label": "200 OK", - "data": { - "status": "healthy", - "tokens_validated": true - }, - "success": true, - "note": "Auth works. No pager. Sleep continues.", - "index": 8, - "fromActor": { - "id": "P", - "label": "Production", - "description": "Live system", - "color": "#EF4444" - }, - "toActor": { - "id": "P", - "label": "Production", - "description": "Live system", - "color": "#EF4444" - } - } - ] + "type": "code", + "id": "fix-store", + "title": "Store decisions with context", + "code": "episteme.assert({\n subject: \"project/logging\",\n predicate: \"library\",\n value: \"winston\",\n\n lifecycle: \"approved\", // not proposed, not deprecated\n confidence: 1.0, // this is a decision, not a guess\n source: \"adr-0012\" // traceable to a decision record\n});\n" }, { - "type": "section-title", - "title": "The Correction Loop", - "subtitle": "Tracing, Fixing, Learning", - "description": "Post-incident: Human traces the bug, corrects the record,\nand the Gardener ensures agents learn from the mistake.\n" + "type": "code", + "id": "fix-query", + "title": "Query with lifecycle filter", + "code": "// Before writing code, agent checks constraints\n\nconst constraints = await episteme.query({\n subject: \"project/logging\",\n lifecycle: \"approved\"\n});\n\n// Returns: { library: \"winston\", confidence: 1.0 }\n\n// Agent uses winston. Every time. Every session.\n" }, { - "type": "sequence", - "sequenceId": "correction_loop", - "title": "The Correction Loop", - "actors": { - "human": { - "id": "H", - "label": "Human Supervisor", - "description": "Reviews decisions, corrects errors", - "color": "#EC4899" - }, - "episteme": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - }, - "gardener": { - "id": "G", - "label": "Gardener", - "description": "Background worker for TrustRank propagation", - "color": "#14B8A6" - } - }, - "steps": [ - { - "id": "fix-1", - "from": "human", - "to": "episteme", - "action": "query", - "label": "Trace deploy agent queries", - "data": { - "type": "audit", - "agent_id": "deploy_agent", - "time_range": "-6h", - "subject": "auth/*" - }, - "note": "SRE investigates: what did the agent believe?", - "index": 0, - "fromActor": { - "id": "H", - "label": "Human Supervisor", - "description": "Reviews decisions, corrects errors", - "color": "#EC4899" - }, - "toActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - } - }, - { - "id": "fix-2", - "from": "episteme", - "to": "human", - "action": "response", - "label": "Query audit trail", - "data": { - "query_id": "q_7f3a2b", - "timestamp": "2024-01-15T21:03:47Z", - "subject": "auth/jwt", - "predicate": "signing_algorithm", - "lens": "recency", - "lifecycle_filter": null, - "result": "ES256", - "contributing": [ - { - "hash": "rfc_2024_001", - "lifecycle": "proposed", - "weight": 0.9 - } - ] - }, - "danger": true, - "note": "Found it: no lifecycle filter. Proposal returned.", - "callout": "lifecycle_filter: null", - "index": 1, - "fromActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - }, - "toActor": { - "id": "H", - "label": "Human Supervisor", - "description": "Reviews decisions, corrects errors", - "color": "#EC4899" - } - }, - { - "id": "fix-3", - "from": "human", - "to": "episteme", - "action": "supersede", - "label": "Mark assertion incorrect", - "data": { - "hash": "rfc_2024_001", - "reason": "Proposal treated as approved decision", - "type": "RequiresReview" - }, - "note": "Supersede the problematic assertion.", - "index": 2, - "fromActor": { - "id": "H", - "label": "Human Supervisor", - "description": "Reviews decisions, corrects errors", - "color": "#EC4899" - }, - "toActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - } - }, - { - "id": "fix-4", - "from": "episteme", - "to": "gardener", - "action": "trigger", - "label": "Correction event", - "data": { - "superseded_hash": "rfc_2024_001", - "superseding_agent": "human_supervisor", - "affected_queries": [ - "q_7f3a2b" - ] - }, - "note": "Gardener wakes up.", - "index": 3, - "fromActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - }, - "toActor": { - "id": "G", - "label": "Gardener", - "description": "Background worker for TrustRank propagation", - "color": "#14B8A6" - } - }, - { - "id": "fix-5", - "from": "gardener", - "to": "episteme", - "action": "update", - "label": "TrustRank back-propagation", - "data": { - "agent_id": "lead_orchestrator", - "topic": "auth/jwt", - "delta": -0.15, - "reason": "Query returned proposal as decision" - }, - "warning": true, - "note": "Lead Orchestrator's reputation on auth topics drops.", - "index": 4, - "fromActor": { - "id": "G", - "label": "Gardener", - "description": "Background worker for TrustRank propagation", - "color": "#14B8A6" - }, - "toActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - } - }, - { - "id": "fix-6", - "from": "gardener", - "to": "episteme", - "action": "update", - "label": "Store negative constraint", - "data": { - "subject": "auth/jwt", - "predicate": "query_pattern", - "must_use": "lifecycle=approved", - "forbidden": "lifecycle=null", - "reason": "Proposals must not be treated as decisions" - }, - "success": true, - "note": "Future queries will see this constraint.", - "index": 5, - "fromActor": { - "id": "G", - "label": "Gardener", - "description": "Background worker for TrustRank propagation", - "color": "#14B8A6" - }, - "toActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - } - } - ] + "type": "code", + "id": "fix-diff", + "title": "The difference", + "code": "// Without Episteme:\nquery({ subject: \"auth/jwt\", predicate: \"algorithm\" })\n// Returns: ES256 (most recent entry - a proposal)\n\n// With Episteme:\nquery({ subject: \"auth/jwt\", predicate: \"algorithm\", lifecycle: \"approved\" })\n// Returns: RS256 (the actual decision)\n" }, { - "type": "section-title", - "title": "Persistent Learning", - "subtitle": "Fixing the Optimization Conflict", - "description": "1 month later. New session. Empty context window.\nBut the lesson persists.\n" + "type": "code", + "id": "time-travel", + "title": "Debug what you believed, not what you know now", + "code": "// Post-incident: what did we believe at 9pm?\n\nepisteme.query({\n subject: \"auth/jwt\",\n predicate: \"algorithm\",\n as_of: \"2024-01-15T21:00:00Z\"\n});\n\n// Returns: ES256 (the belief at incident time)\n\nepisteme.diff({\n subject: \"auth/jwt\",\n from: \"2024-01-15T14:00:00Z\",\n to: \"2024-01-15T21:00:00Z\"\n});\n\n// Shows: RFC proposal added at 2:32pm\n// Root cause identified.\n" }, { - "type": "sequence", - "sequenceId": "persistent_learning", - "title": "Persistent Learning", - "actors": { - "human": { - "id": "H", - "label": "Human Supervisor", - "description": "Reviews decisions, corrects errors", - "color": "#EC4899" - }, - "episteme": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - }, - "gardener": { - "id": "G", - "label": "Gardener", - "description": "Background worker for TrustRank propagation", - "color": "#14B8A6" - }, - "implementation_agent": { - "id": "IA", - "label": "Implementation Agent", - "description": "Writes code against current patterns", - "color": "#10B981" - } - }, - "steps": [ - { - "id": "learn-1", - "from": "human", - "to": "episteme", - "action": "assert", - "label": "Correct the agent", - "data": { - "subject": "Project_X_Http_Client", - "predicate": "must_use_library", - "object": "axios", - "meta": { - "forbidden_alternative": "requests", - "reason": "requests library deprecated for this project" - }, - "confidence": 1, - "lifecycle": "approved" - }, - "note": "Human stores correction with forbidden alternative.", - "callout": "Day 1", - "index": 0, - "fromActor": { - "id": "H", - "label": "Human Supervisor", - "description": "Reviews decisions, corrects errors", - "color": "#EC4899" - }, - "toActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - } - }, - { - "id": "learn-2", - "from": "episteme", - "to": "gardener", - "action": "trigger", - "label": "Negative constraint stored", - "data": { - "type": "correction", - "agent_corrected": "implementation_agent" - }, - "note": "Gardener sees the correction event.", - "index": 1, - "fromActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - }, - "toActor": { - "id": "G", - "label": "Gardener", - "description": "Background worker for TrustRank propagation", - "color": "#14B8A6" - } - }, - { - "id": "learn-3", - "from": "gardener", - "to": "episteme", - "action": "update", - "label": "TrustRank penalty", - "data": { - "agent_id": "implementation_agent", - "topic": "http_libraries", - "delta": -0.2 - }, - "warning": true, - "note": "Implementation Agent's confidence on HTTP libs drops.", - "callout": "Learns from mistake", - "index": 2, - "fromActor": { - "id": "G", - "label": "Gardener", - "description": "Background worker for TrustRank propagation", - "color": "#14B8A6" - }, - "toActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - } - }, - { - "id": "learn-4", - "from": "implementation_agent", - "to": "implementation_agent", - "action": "start", - "label": "New session begins", - "data": { - "context_window": "empty", - "system_prompt": "default" - }, - "note": "30 days later. Fresh context. No memory of correction.", - "callout": "Day 30 - New Session", - "index": 3, - "fromActor": { - "id": "IA", - "label": "Implementation Agent", - "description": "Writes code against current patterns", - "color": "#10B981" - }, - "toActor": { - "id": "IA", - "label": "Implementation Agent", - "description": "Writes code against current patterns", - "color": "#10B981" - } - }, - { - "id": "learn-5", - "from": "implementation_agent", - "to": "episteme", - "action": "query", - "label": "Pre-flight constraint check", - "data": { - "context": "python_http", - "lens": "constraints" - }, - "success": true, - "note": "Before writing code, check constraints.", - "callout": "Automatic pre-flight", - "index": 4, - "fromActor": { - "id": "IA", - "label": "Implementation Agent", - "description": "Writes code against current patterns", - "color": "#10B981" - }, - "toActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - } - }, - { - "id": "learn-6", - "from": "episteme", - "to": "implementation_agent", - "action": "response", - "label": "Constraint found", - "data": { - "constraints": [ - { - "subject": "Project_X_Http_Client", - "must_use": "axios", - "forbidden": "requests", - "reason": "requests library deprecated for this project", - "confidence": 1 - } - ] - }, - "success": true, - "note": "The correction from Day 1 is still there.", - "callout": "Survived context window!", - "index": 5, - "fromActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - }, - "toActor": { - "id": "IA", - "label": "Implementation Agent", - "description": "Writes code against current patterns", - "color": "#10B981" - } - }, - { - "id": "learn-7", - "from": "implementation_agent", - "to": "implementation_agent", - "action": "generate", - "label": "Write code with axios", - "data": { - "import": "axios", - "avoided": "requests" - }, - "success": true, - "note": "Agent uses axios. Constraint honored.", - "index": 6, - "fromActor": { - "id": "IA", - "label": "Implementation Agent", - "description": "Writes code against current patterns", - "color": "#10B981" - }, - "toActor": { - "id": "IA", - "label": "Implementation Agent", - "description": "Writes code against current patterns", - "color": "#10B981" - } - }, - { - "id": "learn-8", - "from": "episteme", - "to": "episteme", - "action": "resurrect", - "label": "Resurrection", - "data": { - "constraint_hash": "axios_constraint", - "last_verified": "now", - "confidence": 1 - }, - "success": true, - "note": "Constraint used successfully. Stays fresh forever.", - "callout": "Resurrection", - "index": 7, - "fromActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - }, - "toActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - } - } - ] + "type": "code", + "id": "correction", + "title": "Fix the record, not just the code", + "code": "// Mark the bad assertion\nepisteme.supersede({\n target: \"ax7f3k9...\",\n reason: \"RFC was proposal, not approved decision\",\n corrected_by: \"sre-oncall\"\n});\n\n// Add a constraint so it never happens again\nepisteme.assert({\n subject: \"auth/jwt\",\n predicate: \"algorithm\",\n value: \"RS256\",\n lifecycle: \"approved\",\n supersedes: \"ax7f3k9...\"\n});\n\n// Future sessions will see this. Forever.\n" }, { - "type": "section-title", - "title": "Time Travel Debugging", - "subtitle": "What Did We Believe Then?", - "description": "3:00 AM incident investigation. The SRE needs to know\nwhat the system believed 6 hours ago, not now.\n" - }, - { - "type": "sequence", - "sequenceId": "time_travel", - "title": "Time Travel Debugging", - "actors": { - "human": { - "id": "H", - "label": "Human Supervisor", - "description": "Reviews decisions, corrects errors", - "color": "#EC4899" - }, - "episteme": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - } - }, - "steps": [ - { - "id": "tt-1", - "from": "human", - "to": "episteme", - "action": "query", - "label": "What's the current JWT algorithm?", - "data": { - "subject": "auth/jwt", - "predicate": "signing_algorithm", - "lifecycle": "approved" - }, - "note": "Current state shows RS256 (post-fix).", - "index": 0, - "fromActor": { - "id": "H", - "label": "Human Supervisor", - "description": "Reviews decisions, corrects errors", - "color": "#EC4899" - }, - "toActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - } - }, - { - "id": "tt-2", - "from": "episteme", - "to": "human", - "action": "response", - "label": "RS256 (current)", - "data": { - "value": "RS256", - "confidence": 0.95 - }, - "note": "This is useless for debugging. We need history.", - "index": 1, - "fromActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - }, - "toActor": { - "id": "H", - "label": "Human Supervisor", - "description": "Reviews decisions, corrects errors", - "color": "#EC4899" - } - }, - { - "id": "tt-3", - "from": "human", - "to": "episteme", - "action": "query", - "label": "What did we believe at 9pm?", - "data": { - "subject": "auth/jwt", - "predicate": "signing_algorithm", - "as_of": "2024-01-15T21:00:00Z" - }, - "note": "Time-travel query.", - "callout": "as_of: 9pm", - "index": 2, - "fromActor": { - "id": "H", - "label": "Human Supervisor", - "description": "Reviews decisions, corrects errors", - "color": "#EC4899" - }, - "toActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - } - }, - { - "id": "tt-4", - "from": "episteme", - "to": "human", - "action": "response", - "label": "ES256 (at 9pm)", - "data": { - "value": "ES256", - "confidence": 0.87, - "lifecycle": "proposed", - "as_of": "2024-01-15T21:00:00Z" - }, - "danger": true, - "note": "At 9pm, the system believed ES256 was correct.", - "callout": "Found the state at incident time", - "index": 3, - "fromActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - }, - "toActor": { - "id": "H", - "label": "Human Supervisor", - "description": "Reviews decisions, corrects errors", - "color": "#EC4899" - } - }, - { - "id": "tt-5", - "from": "human", - "to": "episteme", - "action": "query", - "label": "What changed in last 24h?", - "data": { - "type": "diff", - "subject": "auth/jwt", - "from": "-24h" - }, - "note": "Diff view for change analysis.", - "index": 4, - "fromActor": { - "id": "H", - "label": "Human Supervisor", - "description": "Reviews decisions, corrects errors", - "color": "#EC4899" - }, - "toActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - } - }, - { - "id": "tt-6", - "from": "episteme", - "to": "human", - "action": "response", - "label": "Diff result", - "data": { - "added": [ - { - "hash": "rfc_2024_001", - "value": "ES256", - "lifecycle": "proposed", - "added_at": "2024-01-15T14:30:00Z" - } - ], - "unchanged": [ - { - "hash": "prod_config_v2", - "value": "RS256", - "lifecycle": "approved" - } - ] - }, - "success": true, - "note": "Clear view: RFC added at 2:30pm caused the issue.", - "index": 5, - "fromActor": { - "id": "E", - "label": "Episteme", - "description": "Probabilistic knowledge graph", - "color": "#FBBF24" - }, - "toActor": { - "id": "H", - "label": "Human Supervisor", - "description": "Reviews decisions, corrects errors", - "color": "#EC4899" - } - } - ] + "type": "vision", + "id": "vision", + "title": "Episteme", + "points": [ + "Claims, not facts. Uncertainty is first-class.", + "Lifecycle awareness. Proposals ≠ decisions.", + "Corrections that persist across sessions.", + "Time travel for incident investigation." + ], + "tagline": "Git for Truth" } ] } \ No newline at end of file diff --git a/docs/presentations/generated/agile-agent-team.mmd b/docs/presentations/generated/agile-agent-team.mmd index 430d5f3..028e78a 100644 --- a/docs/presentations/generated/agile-agent-team.mmd +++ b/docs/presentations/generated/agile-agent-team.mmd @@ -1,10 +1,9 @@ sequenceDiagram - %% The Catastrophe: When Proposals Look Like Decisions + %% The Catastrophe participant RA as Research Agent participant E as Episteme participant LO as Lead Orchestrator - participant IA as Implementation Agent participant DA as Deploy Agent participant P as Production @@ -17,13 +16,7 @@ sequenceDiagram E-->>LO: ES256 (conf: 0.87) Note right of LO: ⚠️ Returns the proposal. Most recent wins. - LO->>IA: Use ES256 for JWT - Note right of IA: ⚠️ Orchestrator passes 'truth' downstream. - - IA->>DA: Config ready - Note right of DA: ⚠️ Code written against ES256. - - DA->>P: Deploy JWT config + DA->>P: Deploy ES256 config Note right of P: ⚠️ Deployed with confidence. Tests passed. P->>P: 401 Unauthorized @@ -33,37 +26,24 @@ sequenceDiagram --- sequenceDiagram - %% The Correct Path: With Lifecycle Filtering + %% The Correct Path participant RA as Research Agent participant E as Episteme participant LO as Lead Orchestrator - participant IA as Implementation Agent participant DA as Deploy Agent participant P as Production RA->>E: Store RFC finding Note right of E: Same RFC. Still stored as PROPOSED. - LO->>E: What's the APPROVED JWT algorithm? + LO->>E: What's the APPROVED algorithm? Note right of E: ✓ Lifecycle filter: approved only. E-->>LO: RS256 (conf: 0.92) Note right of LO: ✓ Returns the approved decision. Proposal excluded. - LO->>IA: Use RS256 for JWT - Note right of IA: ✓ Correct algorithm propagates. - - IA->>E: Pre-flight constraint check - Note right of E: ✓ Check for forbidden patterns before coding. - - E-->>IA: No violations - Note right of IA: ✓ No negative constraints for RS256. - - IA->>DA: Config ready - Note right of DA: ✓ Code written against RS256. - - DA->>P: Deploy JWT config + DA->>P: Deploy RS256 config Note right of P: ✓ Deployed. Matches production expectation. P->>P: 200 OK @@ -73,26 +53,20 @@ sequenceDiagram --- sequenceDiagram - %% The Correction Loop: Tracing, Fixing, Learning + %% The Correction Loop participant H as Human Supervisor participant E as Episteme participant G as Gardener - H->>E: Trace deploy agent queries - Note right of E: SRE investigates: what did the agent believe? + H->>E: What did the agent query? + Note right of E: SRE investigates the incident. E-->>H: Query audit trail - Note right of H: ⚠️ Found it: no lifecycle filter. Proposal returned. + Note right of H: ⚠️ Found it: no lifecycle filter used. H->>E: Mark assertion incorrect - Note right of E: Supersede the problematic assertion. - - E->>G: Correction event - Note right of G: Gardener wakes up. - - G->>E: TrustRank back-propagation - Note right of E: Lead Orchestrator's reputation on auth topics drops. + Note right of E: Correct the record. G->>E: Store negative constraint Note right of E: ✓ Future queries will see this constraint. @@ -101,60 +75,44 @@ sequenceDiagram --- sequenceDiagram - %% Persistent Learning: Fixing the Optimization Conflict + %% Persistent Learning participant H as Human Supervisor participant E as Episteme - participant G as Gardener participant IA as Implementation Agent H->>E: Correct the agent - Note right of E: Human stores correction with forbidden alternative. - - E->>G: Negative constraint stored - Note right of G: Gardener sees the correction event. - - G->>E: TrustRank penalty - Note right of E: Implementation Agent's confidence on HTTP libs drops. + Note right of E: Human stores: use axios, not requests. IA->>IA: New session begins - Note over IA: 30 days later. Fresh context. No memory of correction. + Note over IA: 30 days later. Fresh context window. IA->>E: Pre-flight constraint check Note right of E: ✓ Before writing code, check constraints. - E-->>IA: Constraint found - Note right of IA: ✓ The correction from Day 1 is still there. + E-->>IA: Constraint found: use axios + Note right of IA: ✓ The correction from Day 1 persists. - IA->>IA: Write code with axios + IA->>IA: Write correct code Note over IA: ✓ Agent uses axios. Constraint honored. - E->>E: Resurrection - Note over E: ✓ Constraint used successfully. Stays fresh forever. - --- sequenceDiagram - %% Time Travel Debugging: What Did We Believe Then? + %% Time Travel Debugging participant H as Human Supervisor participant E as Episteme - H->>E: What's the current JWT algorithm? - Note right of E: Current state shows RS256 (post-fix). - - E-->>H: RS256 (current) - Note right of H: This is useless for debugging. We need history. + H->>E: Current state? + Note right of E: Shows RS256 (post-fix). Useless for debugging. H->>E: What did we believe at 9pm? Note right of E: Time-travel query. E-->>H: ES256 (at 9pm) - Note right of H: ⚠️ At 9pm, the system believed ES256 was correct. + Note right of H: ⚠️ Found it. This was the state at incident time. - H->>E: What changed in last 24h? - Note right of E: Diff view for change analysis. - - E-->>H: Diff result - Note right of H: ✓ Clear view: RFC added at 2:30pm caused the issue. + E-->>H: Diff: RFC added at 2:30pm + Note right of H: ✓ Clear timeline of what changed and when. diff --git a/docs/presentations/generated/consumer-health-intelligence.json b/docs/presentations/generated/consumer-health-intelligence.json new file mode 100644 index 0000000..87587f9 --- /dev/null +++ b/docs/presentations/generated/consumer-health-intelligence.json @@ -0,0 +1,147 @@ +{ + "meta": { + "id": "consumer-health-intelligence", + "title": "Consumer Health Intelligence", + "subtitle": "The Living Truth Layer", + "version": "1.0.0" + }, + "actors": {}, + "slides": [ + { + "type": "title", + "id": "title" + }, + { + "type": "hook", + "id": "hook", + "line": "Your sources contradict each other.", + "subline": "And you have no way to weigh them." + }, + { + "type": "code", + "id": "drift-doctor", + "title": "Source 1: Your doctor", + "code": "\"Well-tolerated. Nausea is common but transient.\"\n\n// Confidence: high (MD, treating physician)\n// Basis: prescribing guidelines, clinical experience\n// What's missing: doesn't see Reddit, doesn't see FAERS\n" + }, + { + "type": "code", + "id": "drift-fda", + "title": "Source 2: The FDA label", + "code": "WARNING: Thyroid C-cell tumors (boxed warning)\n\nAdverse reactions:\n - Nausea (44%)\n - Diarrhea (30%)\n - Vomiting (24%)\n\n// No mention of gastroparesis (yet).\n// Label last updated: 2021.\n" + }, + { + "type": "code", + "id": "drift-reddit", + "title": "Source 3: Reddit (1.2M members)", + "code": "r/Ozempic - sorted by top, past month:\n\n\"Ozempic face is real. I look 10 years older.\" [2.1k upvotes]\n\"Month 3: can't eat, stomach won't empty\" [1.8k upvotes]\n\"Hair is falling out in clumps\" [1.4k upvotes]\n\"Lost 40 lbs, feel amazing, life changed\" [947 upvotes]\n\n// 4 posts. 4 different realities.\n" + }, + { + "type": "code", + "id": "drift-tiktok", + "title": "Source 4: TikTok (4M views)", + "code": "@healthinfluencer:\n\"Ozempic gave me stomach paralysis.\n I was in the ER for 3 days.\"\n\n4.2M views | 340K likes | 12K comments\n\n// One person's experience.\n// Presented as universal truth.\n// Engagement = visibility, not validity.\n" + }, + { + "type": "code", + "id": "drift-nejm", + "title": "Source 5: NEJM meta-analysis", + "code": "// Pooled analysis, n = 14,847\n// Design: randomized controlled trials\n\nResult: \"No statistically significant increase\n in gastroparesis incidence vs placebo\"\n\n// p = 0.23, CI crosses 1.0\n// The gold standard says: no signal.\n" + }, + { + "type": "code", + "id": "drift-faers", + "title": "Source 6: FDA Adverse Event Reports", + "code": "FAERS query: semaglutide + gastroparesis\n\nTotal reports: 8,547\nSerious: 3,201\nHospitalizations: 1,894\nTrend: increasing (2022-2024)\n\n// Self-reported + unverified.\n// But 8,547 reports is a signal.\n" + }, + { + "type": "hook", + "id": "drift-question", + "line": "Seven sources. Seven answers.", + "subline": "You make your decision based on whichever one you saw last." + }, + { + "type": "code", + "id": "spiral", + "title": "The same problem, everywhere", + "code": "// Gastroparesis:\nDoctor: \"Rare\"\nFDA: (not on label)\nReddit: \"It happened to me\" (x 4,200)\nTikTok: \"It's an epidemic\" (12M views)\nNEJM: \"No significant signal\"\nFAERS: 8,547 reports\n\n// Hair loss:\nClinical trials: not studied\nReddit: 1,847 posts\nClinical evidence: zero\n\n// Muscle loss:\nPhase III: \"~40% of weight lost is lean mass\"\nReddit: \"My legs are wasting away\"\nTrainers: \"Just lift weights\"\n" + }, + { + "type": "hook", + "id": "spiral-insight", + "line": "This is the vaccine problem.", + "subline": "Not misinformation. The absence of a system that can hold all claims and show you the shape of the evidence." + }, + { + "type": "code", + "id": "catastrophe", + "title": "The Catastrophe", + "code": "// June 2023: She starts Semaglutide.\n// Her research: doctor + Google + a few Reddit posts.\n// Gastroparesis wasn't on the FDA label.\n//\n// January 2024: FDA updates the label.\n// Intestinal obstruction warning added.\n//\n// Reddit had flagged this a year earlier.\n// FAERS reports were accumulating for two years.\n//\n// Nobody told her. Google doesn't send updates.\n// Her doctor's office doesn't track label changes.\n// The truth changed. Her information didn't.\n" + }, + { + "type": "code", + "id": "catastrophe-pattern", + "title": "The pattern repeats", + "code": "// COVID vaccines, 2021:\n// April: \"No myocarditis signal\"\n// June: VAERS reports accumulating\n// July: CDC acknowledges elevated risk in young males\n//\n// Millions of decisions made between April and July\n// based on information that was about to change.\n//\n// Not because anyone lied.\n// Because no system could show:\n// \"Here is what we know, at each level,\n// and here is what changed since you last looked.\"\n" + }, + { + "type": "hook", + "id": "fix-intro", + "line": "What if every source had a weight?", + "subline": "And the disagreement was the answer." + }, + { + "type": "code", + "id": "fix-tiers", + "title": "Source-class hierarchy", + "code": "// Not all sources are equal. Make it structural.\n\nTier 0: Regulatory action weight: 1.0 decay: never\nTier 1: RCTs, meta-analyses weight: 0.9 decay: 2 years\nTier 2: Observational studies weight: 0.7 decay: 1 year\nTier 3: Pharmacovigilance weight: 0.5 decay: 18 months\nTier 4: Clinician case reports weight: 0.4 decay: 6 months\nTier 5: Patient community weight: 0.2 decay: 3 months\nTier 6: Media, influencers weight: 0.1 decay: 30 days\n\n// A million TikTok posts cannot outvote one FDA action.\n// But they can signal that something is happening.\n" + }, + { + "type": "code", + "id": "fix-assert", + "title": "Store claims with provenance", + "code": "// Clinical evidence enters with full metadata\nepisteme.assert({\n subject: \"semaglutide/adverse-effects/gastroparesis\",\n predicate: \"risk_level\",\n value: \"No statistically significant increase\",\n source_class: \"tier-1\",\n source: {\n type: \"meta-analysis\",\n journal: \"NEJM\",\n sample_size: 14847\n },\n confidence: 0.92\n});\n\n// Patient report enters the same graph\nepisteme.assert({\n subject: \"semaglutide/adverse-effects/gastroparesis\",\n predicate: \"risk_level\",\n value: \"Experienced severe gastroparesis after 3 months\",\n source_class: \"tier-5\",\n source: { platform: \"reddit\", upvotes: 847 },\n confidence: 0.3\n});\n\n// Both coexist. Neither overwrites. But they are not equal.\n" + }, + { + "type": "code", + "id": "fix-query", + "title": "Query returns layers, not a single answer", + "code": "episteme.query({\n subject: \"semaglutide/adverse-effects/gastroparesis\",\n lens: \"layered-consensus\"\n});\n\n// Returns:\n{\n regulatory: \"Added to label Jan 2024\",\n clinical_evidence: \"No signal in Phase III (conflict: 0.34)\",\n pharmacovigilance: \"8,547 FAERS reports, trend: increasing\",\n patient_community: \"Widely reported, cluster size: 4,200\",\n\n overall_conflict: 0.72,\n summary: \"Trials show low incidence. Post-marketing and\n patient reports show higher rates. FDA added\n to label January 2024.\"\n}\n\n// Not \"yes\" or \"no\". The shape of the evidence.\n" + }, + { + "type": "code", + "id": "escalation", + "title": "Anecdotal signal detection", + "code": "// The Gardener monitors Tier 5 clusters.\n// When density crosses threshold:\n\nepisteme.assert({\n subject: \"semaglutide/adverse-effects/hair-loss\",\n predicate: \"escalation_signal\",\n value: \"Anecdotal cluster detected\",\n source_class: \"meta\",\n meta: {\n tier_5_count: 1847,\n growth_rate: \"312/month\",\n tier_1_count: 0, // no clinical evidence exists\n clinical_gap: true\n },\n lifecycle: \"under-review\"\n});\n\n// Does NOT claim hair loss is real.\n// Claims: \"people are reporting this, and nobody has studied it.\"\n// The gap is the signal.\n" + }, + { + "type": "code", + "id": "guidance-change", + "title": "What changed since you last looked", + "code": "// FDA updates the label. Epoch shifts.\nepisteme.epoch.supersede({\n old_epoch: \"semaglutide-label-pre-2024\",\n new_epoch: \"semaglutide-label-2024-01\",\n reason: \"Intestinal obstruction warning added\"\n});\n\n// Consumer returns 3 months later:\nepisteme.query({\n subject: \"semaglutide/adverse-effects\",\n lens: \"layered-consensus\",\n since: \"2023-10-01\" // their last visit\n});\n\n// Returns:\n{\n changes: [{\n date: \"2024-01-12\",\n type: \"regulatory\",\n change: \"Intestinal obstruction added to warnings\"\n }],\n prior_assertions_affected: 12\n}\n\n// Not just today's answer. What changed.\n" + }, + { + "type": "code", + "id": "time-travel", + "title": "What was known when you decided?", + "code": "// \"I started Semaglutide in June 2023.\n// What were the known risks at that time?\"\n\nepisteme.query({\n subject: \"semaglutide/adverse-effects\",\n lens: \"layered-consensus\",\n as_of: \"2023-06-15\"\n});\n\n// Returns the June 2023 snapshot:\n{\n regulatory: \"Boxed warning: thyroid. No GI obstruction.\",\n clinical: \"Nausea common, no gastroparesis signal\",\n patient: \"Growing reports (cluster size: 340)\",\n escalation: \"not yet triggered (threshold: 500)\"\n}\n\n// Your decision was reasonable given available evidence.\n// The record proves it.\n" + }, + { + "type": "code", + "id": "disagreement", + "title": "The disagreement dashboard", + "code": "episteme.query({\n subject: \"semaglutide\",\n lens: \"skeptic\",\n scope: \"adverse-effects\"\n});\n\n// Returns:\nresolved: [\n { topic: \"nausea\", conflict: 0.08, \"all tiers agree\" }\n]\n\nactive_disagreement: [\n { topic: \"gastroparesis\", conflict: 0.72,\n clinical: \"Low incidence\",\n faers: \"8,547 reports\",\n patients: \"Widely reported\" }\n]\n\nemerging_signal: [\n { topic: \"hair loss\",\n clinical_evidence: \"none\",\n patient_reports: 1847,\n status: \"under-review\" }\n]\n\n// Settled. Contested. Emerging.\n// Honest answers, not false certainty.\n" + }, + { + "type": "vision", + "id": "vision", + "title": "Episteme", + "points": [ + "Source-class hierarchy. Not all claims are equal.", + "Anecdotal signals surfaced without false authority.", + "Guidance changes propagated, not buried.", + "Time travel to the evidence at any moment." + ], + "tagline": "Git for Truth" + } + ] +} \ No newline at end of file diff --git a/docs/presentations/generated/sec-analysis.json b/docs/presentations/generated/sec-analysis.json new file mode 100644 index 0000000..6dbfeb0 --- /dev/null +++ b/docs/presentations/generated/sec-analysis.json @@ -0,0 +1,123 @@ +{ + "meta": { + "id": "sec-analysis", + "title": "SEC Document Analysis", + "subtitle": "Filing Intelligence with Episteme", + "version": "1.0.0" + }, + "actors": {}, + "slides": [ + { + "type": "title", + "id": "title" + }, + { + "type": "hook", + "id": "hook", + "line": "Your filings contradict each other.", + "subline": "And every agent reading them gets a different answer." + }, + { + "type": "code", + "id": "drift-revenue", + "title": "10-K: Annual revenue", + "code": "// Agent extracts from 10-K filing\n// CIK: 0001234567, Filed: 2024-02-28\n\n{\n \"subject\": \"ACME/revenue/annual\",\n \"source\": \"10-K/2023\",\n \"value\": \"$847M\"\n}\n" + }, + { + "type": "code", + "id": "drift-revenue-2", + "title": "10-Q: Quarterly revenue tells a different story", + "code": "// Agent extracts from Q4 10-Q filing\n// Same company, same fiscal year\n\n{\n \"subject\": \"ACME/revenue/Q4\",\n \"source\": \"10-Q/2023-Q4\",\n \"value\": \"$218M\"\n}\n\n// Q1 + Q2 + Q3 + Q4 = $872M annualized\n// 10-K says $847M\n// Delta: $25M. Which is right?\n" + }, + { + "type": "code", + "id": "drift-amendment", + "title": "Original 10-K: No impairment", + "code": "// Filed: 2024-02-28\n// Form: 10-K\n\n{\n \"subject\": \"ACME/goodwill/impairment\",\n \"source\": \"10-K/2023\",\n \"value\": \"$0\"\n}\n\n// Clean bill of health.\n" + }, + { + "type": "code", + "id": "drift-amendment-2", + "title": "10-K/A: $340M impairment appears", + "code": "// Filed: 2024-06-15 (amended filing)\n// Form: 10-K/A\n\n{\n \"subject\": \"ACME/goodwill/impairment\",\n \"source\": \"10-K-A/2023\",\n \"value\": \"$340M\"\n}\n\n// The amendment supersedes the original.\n// But which sections? All of them? Just Note 7?\n// The rest of the 10-K -- still valid?\n" + }, + { + "type": "code", + "id": "spiral", + "title": "Same data, extracted 3 times, 3 answers", + "code": "// Q3 Revenue appears in:\n\"10-Q/2023-Q3\" -> $213M // quarterly filing\n\"10-K/2023\" -> $209M // annual summary table\n\"DEF 14A/2024\" -> $211M // proxy exec comp section\n\n// Two analysts read the same proxy statement\n// Analyst A: CEO comp = $14.2M (includes options)\n// Analyst B: CEO comp = $8.7M (base + bonus only)\n\n// Both are \"correct\" -- different definitions\n" + }, + { + "type": "hook", + "id": "spiral-question", + "line": "Which extraction is correct?", + "subline": "Depends on the filing, the section, and what you're measuring." + }, + { + "type": "code", + "id": "catastrophe", + "title": "The Catastrophe", + "code": "// Agent builds a DCF model\n// Revenue: pulled from 10-K/A -> $847M (amended)\n// Cost of revenue: pulled from 10-K -> $612M (original)\n//\n// But the amendment changed cost allocations too.\n// Actual cost of revenue post-amendment: $658M\n//\n// Gross margin: 27.7% (agent's model)\n// Actual: 22.3%\n//\n// DCF valuation: off by $180M\n//\n// The model mixed amended and pre-amendment data\n// because there was no way to track the amendment chain.\n" + }, + { + "type": "code", + "id": "catastrophe-why", + "title": "The Root Cause", + "code": "// Filings were stored as flat key-value pairs\n// No amendment chain linking 10-K to 10-K/A\n// No section-level tracking\n// No way to know which data points were superseded\n//\n// The agent had no concept of \"this number was restated\"\n// It just grabbed the first match for each field\n//\n// Garbage in, $180M garbage out.\n" + }, + { + "type": "hook", + "id": "fix-intro", + "line": "What if filings carried their own lineage?", + "subline": "Every extraction linked to its source, section, and amendment chain." + }, + { + "type": "code", + "id": "fix-store", + "title": "Store extractions with filing metadata", + "code": "episteme.assert({\n subject: \"ACME/revenue/annual/2023\",\n predicate: \"value\",\n value: \"$847M\",\n\n source: {\n cik: \"0001234567\",\n form: \"10-K\",\n filed: \"2024-02-28\",\n section: \"Part II, Item 8\",\n accession: \"0001234567-24-000042\"\n },\n\n lifecycle: \"current\",\n confidence: 0.95\n});\n" + }, + { + "type": "code", + "id": "fix-amendment", + "title": "Amendments supersede cleanly", + "code": "// When the 10-K/A arrives:\nepisteme.assert({\n subject: \"ACME/goodwill/impairment/2023\",\n predicate: \"value\",\n value: \"$340M\",\n\n source: {\n form: \"10-K/A\",\n filed: \"2024-06-15\",\n amends: \"0001234567-24-000042\", // links to original\n sections_amended: [\"Note 7\", \"Part II Item 8\"]\n },\n\n lifecycle: \"current\",\n supersedes: \"ax7f3k9...\" // the $0 assertion\n});\n\n// The original $0 assertion is now lifecycle: \"superseded\"\n// Sections NOT in sections_amended remain valid\n" + }, + { + "type": "code", + "id": "fix-query", + "title": "Query with lifecycle: only current data", + "code": "// Agent building a DCF model queries:\nconst revenue = await episteme.query({\n subject: \"ACME/revenue/annual/2023\",\n lifecycle: \"current\"\n});\n// Returns $847M from 10-K/A (amended value)\n\nconst cost = await episteme.query({\n subject: \"ACME/cost-of-revenue/annual/2023\",\n lifecycle: \"current\"\n});\n// Returns $658M from 10-K/A (amended value)\n\n// Both values from the same amendment.\n// No mixing. No $180M error.\n" + }, + { + "type": "code", + "id": "time-travel", + "title": "What did we believe before the restatement?", + "code": "// Audit question: what was our position on March 1?\n// (before the 10-K/A was filed on June 15)\n\nepisteme.query({\n subject: \"ACME/goodwill/impairment/2023\",\n as_of: \"2024-03-01T00:00:00Z\"\n});\n\n// Returns: $0 (the original 10-K assertion)\n// At that point, that WAS the truth.\n\nepisteme.diff({\n subject: \"ACME/goodwill/impairment/2023\",\n from: \"2024-03-01\",\n to: \"2024-07-01\"\n});\n\n// Shows: 10-K/A filed June 15, impairment changed $0 -> $340M\n// Full audit trail. No guessing.\n" + }, + { + "type": "code", + "id": "multi-analyst", + "title": "Competing extractions coexist", + "code": "// Analyst A extracts CEO comp from proxy (DEF 14A)\nepisteme.assert({\n subject: \"ACME/exec-comp/CEO/2023\",\n value: \"$14.2M\",\n source: { form: \"DEF 14A\", section: \"Summary Compensation\" },\n confidence: 0.9,\n author: \"analyst-A\"\n});\n\n// Analyst B extracts from the same proxy\nepisteme.assert({\n subject: \"ACME/exec-comp/CEO/2023\",\n value: \"$8.7M\",\n source: { form: \"DEF 14A\", section: \"Summary Compensation\" },\n confidence: 0.85,\n author: \"analyst-B\"\n});\n\n// Both assertions coexist. No overwrite.\n" + }, + { + "type": "code", + "id": "multi-analyst-resolve", + "title": "Lens resolves at query time", + "code": "// Default lens: highest confidence wins\nepisteme.query({\n subject: \"ACME/exec-comp/CEO/2023\",\n lens: \"authority\"\n});\n// Returns: $14.2M (analyst-A, confidence 0.9)\n\n// But you can ask: show me all claims\nepisteme.query({\n subject: \"ACME/exec-comp/CEO/2023\",\n lens: \"all\"\n});\n// Returns both: $14.2M and $8.7M\n// With full provenance on each\n\n// The disagreement IS the signal.\n// Someone needs to reconcile definitions.\n" + }, + { + "type": "vision", + "id": "vision", + "title": "Episteme", + "points": [ + "Amendment chains, not flat overwrites.", + "Section-level provenance for every extraction.", + "Competing analyst reads coexist until resolved.", + "Time travel for audit and restatement analysis." + ], + "tagline": "Git for Truth" + } + ] +} \ No newline at end of file diff --git a/docs/presentations/generated/stemedb.json b/docs/presentations/generated/stemedb.json new file mode 100644 index 0000000..a9d4c70 --- /dev/null +++ b/docs/presentations/generated/stemedb.json @@ -0,0 +1,396 @@ +{ + "combined": true, + "meta": { + "id": "stemedb", + "title": "stemedb" + }, + "decks": [ + { + "meta": { + "id": "consumer-health-intelligence", + "title": "Consumer Health Intelligence", + "subtitle": "The Living Truth Layer", + "version": "1.0.0" + }, + "actors": {}, + "slides": [ + { + "type": "title", + "id": "title" + }, + { + "type": "hook", + "id": "hook", + "line": "Your sources contradict each other.", + "subline": "And you have no way to weigh them." + }, + { + "type": "code", + "id": "drift-doctor", + "title": "Source 1: Your doctor", + "code": "\"Well-tolerated. Nausea is common but transient.\"\n\n// Confidence: high (MD, treating physician)\n// Basis: prescribing guidelines, clinical experience\n// What's missing: doesn't see Reddit, doesn't see FAERS\n" + }, + { + "type": "code", + "id": "drift-fda", + "title": "Source 2: The FDA label", + "code": "WARNING: Thyroid C-cell tumors (boxed warning)\n\nAdverse reactions:\n - Nausea (44%)\n - Diarrhea (30%)\n - Vomiting (24%)\n\n// No mention of gastroparesis (yet).\n// Label last updated: 2021.\n" + }, + { + "type": "code", + "id": "drift-reddit", + "title": "Source 3: Reddit (1.2M members)", + "code": "r/Ozempic - sorted by top, past month:\n\n\"Ozempic face is real. I look 10 years older.\" [2.1k upvotes]\n\"Month 3: can't eat, stomach won't empty\" [1.8k upvotes]\n\"Hair is falling out in clumps\" [1.4k upvotes]\n\"Lost 40 lbs, feel amazing, life changed\" [947 upvotes]\n\n// 4 posts. 4 different realities.\n" + }, + { + "type": "code", + "id": "drift-tiktok", + "title": "Source 4: TikTok (4M views)", + "code": "@healthinfluencer:\n\"Ozempic gave me stomach paralysis.\n I was in the ER for 3 days.\"\n\n4.2M views | 340K likes | 12K comments\n\n// One person's experience.\n// Presented as universal truth.\n// Engagement = visibility, not validity.\n" + }, + { + "type": "code", + "id": "drift-nejm", + "title": "Source 5: NEJM meta-analysis", + "code": "// Pooled analysis, n = 14,847\n// Design: randomized controlled trials\n\nResult: \"No statistically significant increase\n in gastroparesis incidence vs placebo\"\n\n// p = 0.23, CI crosses 1.0\n// The gold standard says: no signal.\n" + }, + { + "type": "code", + "id": "drift-faers", + "title": "Source 6: FDA Adverse Event Reports", + "code": "FAERS query: semaglutide + gastroparesis\n\nTotal reports: 8,547\nSerious: 3,201\nHospitalizations: 1,894\nTrend: increasing (2022-2024)\n\n// Self-reported + unverified.\n// But 8,547 reports is a signal.\n" + }, + { + "type": "hook", + "id": "drift-question", + "line": "Seven sources. Seven answers.", + "subline": "You make your decision based on whichever one you saw last." + }, + { + "type": "code", + "id": "spiral", + "title": "The same problem, everywhere", + "code": "// Gastroparesis:\nDoctor: \"Rare\"\nFDA: (not on label)\nReddit: \"It happened to me\" (x 4,200)\nTikTok: \"It's an epidemic\" (12M views)\nNEJM: \"No significant signal\"\nFAERS: 8,547 reports\n\n// Hair loss:\nClinical trials: not studied\nReddit: 1,847 posts\nClinical evidence: zero\n\n// Muscle loss:\nPhase III: \"~40% of weight lost is lean mass\"\nReddit: \"My legs are wasting away\"\nTrainers: \"Just lift weights\"\n" + }, + { + "type": "hook", + "id": "spiral-insight", + "line": "This is the vaccine problem.", + "subline": "Not misinformation. The absence of a system that can hold all claims and show you the shape of the evidence." + }, + { + "type": "code", + "id": "catastrophe", + "title": "The Catastrophe", + "code": "// June 2023: She starts Semaglutide.\n// Her research: doctor + Google + a few Reddit posts.\n// Gastroparesis wasn't on the FDA label.\n//\n// January 2024: FDA updates the label.\n// Intestinal obstruction warning added.\n//\n// Reddit had flagged this a year earlier.\n// FAERS reports were accumulating for two years.\n//\n// Nobody told her. Google doesn't send updates.\n// Her doctor's office doesn't track label changes.\n// The truth changed. Her information didn't.\n" + }, + { + "type": "code", + "id": "catastrophe-pattern", + "title": "The pattern repeats", + "code": "// COVID vaccines, 2021:\n// April: \"No myocarditis signal\"\n// June: VAERS reports accumulating\n// July: CDC acknowledges elevated risk in young males\n//\n// Millions of decisions made between April and July\n// based on information that was about to change.\n//\n// Not because anyone lied.\n// Because no system could show:\n// \"Here is what we know, at each level,\n// and here is what changed since you last looked.\"\n" + }, + { + "type": "hook", + "id": "fix-intro", + "line": "What if every source had a weight?", + "subline": "And the disagreement was the answer." + }, + { + "type": "code", + "id": "fix-tiers", + "title": "Source-class hierarchy", + "code": "// Not all sources are equal. Make it structural.\n\nTier 0: Regulatory action weight: 1.0 decay: never\nTier 1: RCTs, meta-analyses weight: 0.9 decay: 2 years\nTier 2: Observational studies weight: 0.7 decay: 1 year\nTier 3: Pharmacovigilance weight: 0.5 decay: 18 months\nTier 4: Clinician case reports weight: 0.4 decay: 6 months\nTier 5: Patient community weight: 0.2 decay: 3 months\nTier 6: Media, influencers weight: 0.1 decay: 30 days\n\n// A million TikTok posts cannot outvote one FDA action.\n// But they can signal that something is happening.\n" + }, + { + "type": "code", + "id": "fix-assert", + "title": "Store claims with provenance", + "code": "// Clinical evidence enters with full metadata\nepisteme.assert({\n subject: \"semaglutide/adverse-effects/gastroparesis\",\n predicate: \"risk_level\",\n value: \"No statistically significant increase\",\n source_class: \"tier-1\",\n source: {\n type: \"meta-analysis\",\n journal: \"NEJM\",\n sample_size: 14847\n },\n confidence: 0.92\n});\n\n// Patient report enters the same graph\nepisteme.assert({\n subject: \"semaglutide/adverse-effects/gastroparesis\",\n predicate: \"risk_level\",\n value: \"Experienced severe gastroparesis after 3 months\",\n source_class: \"tier-5\",\n source: { platform: \"reddit\", upvotes: 847 },\n confidence: 0.3\n});\n\n// Both coexist. Neither overwrites. But they are not equal.\n" + }, + { + "type": "code", + "id": "fix-query", + "title": "Query returns layers, not a single answer", + "code": "episteme.query({\n subject: \"semaglutide/adverse-effects/gastroparesis\",\n lens: \"layered-consensus\"\n});\n\n// Returns:\n{\n regulatory: \"Added to label Jan 2024\",\n clinical_evidence: \"No signal in Phase III (conflict: 0.34)\",\n pharmacovigilance: \"8,547 FAERS reports, trend: increasing\",\n patient_community: \"Widely reported, cluster size: 4,200\",\n\n overall_conflict: 0.72,\n summary: \"Trials show low incidence. Post-marketing and\n patient reports show higher rates. FDA added\n to label January 2024.\"\n}\n\n// Not \"yes\" or \"no\". The shape of the evidence.\n" + }, + { + "type": "code", + "id": "escalation", + "title": "Anecdotal signal detection", + "code": "// The Gardener monitors Tier 5 clusters.\n// When density crosses threshold:\n\nepisteme.assert({\n subject: \"semaglutide/adverse-effects/hair-loss\",\n predicate: \"escalation_signal\",\n value: \"Anecdotal cluster detected\",\n source_class: \"meta\",\n meta: {\n tier_5_count: 1847,\n growth_rate: \"312/month\",\n tier_1_count: 0, // no clinical evidence exists\n clinical_gap: true\n },\n lifecycle: \"under-review\"\n});\n\n// Does NOT claim hair loss is real.\n// Claims: \"people are reporting this, and nobody has studied it.\"\n// The gap is the signal.\n" + }, + { + "type": "code", + "id": "guidance-change", + "title": "What changed since you last looked", + "code": "// FDA updates the label. Epoch shifts.\nepisteme.epoch.supersede({\n old_epoch: \"semaglutide-label-pre-2024\",\n new_epoch: \"semaglutide-label-2024-01\",\n reason: \"Intestinal obstruction warning added\"\n});\n\n// Consumer returns 3 months later:\nepisteme.query({\n subject: \"semaglutide/adverse-effects\",\n lens: \"layered-consensus\",\n since: \"2023-10-01\" // their last visit\n});\n\n// Returns:\n{\n changes: [{\n date: \"2024-01-12\",\n type: \"regulatory\",\n change: \"Intestinal obstruction added to warnings\"\n }],\n prior_assertions_affected: 12\n}\n\n// Not just today's answer. What changed.\n" + }, + { + "type": "code", + "id": "time-travel", + "title": "What was known when you decided?", + "code": "// \"I started Semaglutide in June 2023.\n// What were the known risks at that time?\"\n\nepisteme.query({\n subject: \"semaglutide/adverse-effects\",\n lens: \"layered-consensus\",\n as_of: \"2023-06-15\"\n});\n\n// Returns the June 2023 snapshot:\n{\n regulatory: \"Boxed warning: thyroid. No GI obstruction.\",\n clinical: \"Nausea common, no gastroparesis signal\",\n patient: \"Growing reports (cluster size: 340)\",\n escalation: \"not yet triggered (threshold: 500)\"\n}\n\n// Your decision was reasonable given available evidence.\n// The record proves it.\n" + }, + { + "type": "code", + "id": "disagreement", + "title": "The disagreement dashboard", + "code": "episteme.query({\n subject: \"semaglutide\",\n lens: \"skeptic\",\n scope: \"adverse-effects\"\n});\n\n// Returns:\nresolved: [\n { topic: \"nausea\", conflict: 0.08, \"all tiers agree\" }\n]\n\nactive_disagreement: [\n { topic: \"gastroparesis\", conflict: 0.72,\n clinical: \"Low incidence\",\n faers: \"8,547 reports\",\n patients: \"Widely reported\" }\n]\n\nemerging_signal: [\n { topic: \"hair loss\",\n clinical_evidence: \"none\",\n patient_reports: 1847,\n status: \"under-review\" }\n]\n\n// Settled. Contested. Emerging.\n// Honest answers, not false certainty.\n" + }, + { + "type": "vision", + "id": "vision", + "title": "Episteme", + "points": [ + "Source-class hierarchy. Not all claims are equal.", + "Anecdotal signals surfaced without false authority.", + "Guidance changes propagated, not buried.", + "Time travel to the evidence at any moment." + ], + "tagline": "Git for Truth" + } + ] + }, + { + "meta": { + "id": "agile-agent-team", + "title": "Agile AI Agent Team", + "subtitle": "Knowledge Coordination with Episteme", + "version": "4.0.0" + }, + "actors": {}, + "slides": [ + { + "type": "title", + "id": "title" + }, + { + "type": "hook", + "id": "hook", + "line": "Your agents have amnesia.", + "subline": "Every correction you make is forgotten by the next session." + }, + { + "type": "code", + "id": "drift-logging", + "title": "Day 1: You correct the agent", + "code": "// Agent used console.log\n// You: \"We use winston, not console.log\"\n\nimport { logger } from './logger';\n\nlogger.info('User authenticated', { userId });\n" + }, + { + "type": "code", + "id": "drift-logging-2", + "title": "Day 30: New session", + "code": "// Agent writes new code...\n\nconsole.log('User authenticated');\nconsole.log('userId:', userId);\n\n// The correction from Day 1? Gone.\n" + }, + { + "type": "code", + "id": "drift-http", + "title": "Day 45: You correct again", + "code": "// Agent used axios\n// You: \"We standardized on fetch\"\n\nconst response = await fetch('/api/users', {\n headers: { 'Authorization': `Bearer ${token}` }\n});\n" + }, + { + "type": "code", + "id": "drift-http-2", + "title": "Day 60: Another new session", + "code": "// Agent writes new code...\n\nimport axios from 'axios';\n\nconst response = await axios.get('/api/users', {\n headers: { 'Authorization': `Bearer ${token}` }\n});\n\n// Forgot again. Different session, different choices.\n" + }, + { + "type": "code", + "id": "spiral", + "title": "6 months later: 10 ways to do 1 thing", + "code": "// Logging\nconsole.log() // 47 files\nwinston.info() // 23 files\npino.info() // 12 files\ndebug() // 8 files\n\n// HTTP\nfetch() // 31 files\naxios.get() // 28 files\ngot() // 6 files\n\n// Auth\nRS256 // 4 services\nES256 // 3 services\nHS256 // 2 services (why??)\n" + }, + { + "type": "hook", + "id": "spiral-question", + "line": "Which one is correct?", + "subline": "Nobody knows. The decision was never recorded." + }, + { + "type": "code", + "id": "catastrophe", + "title": "The Catastrophe", + "code": "// Auth service A expects RS256\n// Auth service B was deployed with ES256\n// An agent queried \"what's our JWT algorithm?\"\n// Got the most recent answer: ES256 (from an RFC proposal)\n\nHTTP 401 Unauthorized\n{\n error: \"invalid_signature\",\n expected: \"RS256\",\n received: \"ES256\"\n}\n\n// 3:00 AM. Pager fires. 47-minute outage.\n" + }, + { + "type": "code", + "id": "catastrophe-why", + "title": "The Root Cause", + "code": "// The RFC was stored without lifecycle state\n// The query returned the most recent entry\n// No way to distinguish \"proposed\" from \"approved\"\n// The agent treated an idea as truth\n\n// And now you have to audit 9 services\n// to figure out which JWT algorithm is actually correct.\n" + }, + { + "type": "hook", + "id": "fix-intro", + "line": "What if corrections persisted?", + "subline": "Across sessions. Across agents. Forever." + }, + { + "type": "code", + "id": "fix-store", + "title": "Store decisions with context", + "code": "episteme.assert({\n subject: \"project/logging\",\n predicate: \"library\",\n value: \"winston\",\n\n lifecycle: \"approved\", // not proposed, not deprecated\n confidence: 1.0, // this is a decision, not a guess\n source: \"adr-0012\" // traceable to a decision record\n});\n" + }, + { + "type": "code", + "id": "fix-query", + "title": "Query with lifecycle filter", + "code": "// Before writing code, agent checks constraints\n\nconst constraints = await episteme.query({\n subject: \"project/logging\",\n lifecycle: \"approved\"\n});\n\n// Returns: { library: \"winston\", confidence: 1.0 }\n\n// Agent uses winston. Every time. Every session.\n" + }, + { + "type": "code", + "id": "fix-diff", + "title": "The difference", + "code": "// Without Episteme:\nquery({ subject: \"auth/jwt\", predicate: \"algorithm\" })\n// Returns: ES256 (most recent entry - a proposal)\n\n// With Episteme:\nquery({ subject: \"auth/jwt\", predicate: \"algorithm\", lifecycle: \"approved\" })\n// Returns: RS256 (the actual decision)\n" + }, + { + "type": "code", + "id": "time-travel", + "title": "Debug what you believed, not what you know now", + "code": "// Post-incident: what did we believe at 9pm?\n\nepisteme.query({\n subject: \"auth/jwt\",\n predicate: \"algorithm\",\n as_of: \"2024-01-15T21:00:00Z\"\n});\n\n// Returns: ES256 (the belief at incident time)\n\nepisteme.diff({\n subject: \"auth/jwt\",\n from: \"2024-01-15T14:00:00Z\",\n to: \"2024-01-15T21:00:00Z\"\n});\n\n// Shows: RFC proposal added at 2:32pm\n// Root cause identified.\n" + }, + { + "type": "code", + "id": "correction", + "title": "Fix the record, not just the code", + "code": "// Mark the bad assertion\nepisteme.supersede({\n target: \"ax7f3k9...\",\n reason: \"RFC was proposal, not approved decision\",\n corrected_by: \"sre-oncall\"\n});\n\n// Add a constraint so it never happens again\nepisteme.assert({\n subject: \"auth/jwt\",\n predicate: \"algorithm\",\n value: \"RS256\",\n lifecycle: \"approved\",\n supersedes: \"ax7f3k9...\"\n});\n\n// Future sessions will see this. Forever.\n" + }, + { + "type": "vision", + "id": "vision", + "title": "Episteme", + "points": [ + "Claims, not facts. Uncertainty is first-class.", + "Lifecycle awareness. Proposals ≠ decisions.", + "Corrections that persist across sessions.", + "Time travel for incident investigation." + ], + "tagline": "Git for Truth" + } + ] + }, + { + "meta": { + "id": "sec-analysis", + "title": "SEC Document Analysis", + "subtitle": "Filing Intelligence with Episteme", + "version": "1.0.0" + }, + "actors": {}, + "slides": [ + { + "type": "title", + "id": "title" + }, + { + "type": "hook", + "id": "hook", + "line": "Your filings contradict each other.", + "subline": "And every agent reading them gets a different answer." + }, + { + "type": "code", + "id": "drift-revenue", + "title": "10-K: Annual revenue", + "code": "// Agent extracts from 10-K filing\n// CIK: 0001234567, Filed: 2024-02-28\n\n{\n \"subject\": \"ACME/revenue/annual\",\n \"source\": \"10-K/2023\",\n \"value\": \"$847M\"\n}\n" + }, + { + "type": "code", + "id": "drift-revenue-2", + "title": "10-Q: Quarterly revenue tells a different story", + "code": "// Agent extracts from Q4 10-Q filing\n// Same company, same fiscal year\n\n{\n \"subject\": \"ACME/revenue/Q4\",\n \"source\": \"10-Q/2023-Q4\",\n \"value\": \"$218M\"\n}\n\n// Q1 + Q2 + Q3 + Q4 = $872M annualized\n// 10-K says $847M\n// Delta: $25M. Which is right?\n" + }, + { + "type": "code", + "id": "drift-amendment", + "title": "Original 10-K: No impairment", + "code": "// Filed: 2024-02-28\n// Form: 10-K\n\n{\n \"subject\": \"ACME/goodwill/impairment\",\n \"source\": \"10-K/2023\",\n \"value\": \"$0\"\n}\n\n// Clean bill of health.\n" + }, + { + "type": "code", + "id": "drift-amendment-2", + "title": "10-K/A: $340M impairment appears", + "code": "// Filed: 2024-06-15 (amended filing)\n// Form: 10-K/A\n\n{\n \"subject\": \"ACME/goodwill/impairment\",\n \"source\": \"10-K-A/2023\",\n \"value\": \"$340M\"\n}\n\n// The amendment supersedes the original.\n// But which sections? All of them? Just Note 7?\n// The rest of the 10-K -- still valid?\n" + }, + { + "type": "code", + "id": "spiral", + "title": "Same data, extracted 3 times, 3 answers", + "code": "// Q3 Revenue appears in:\n\"10-Q/2023-Q3\" -> $213M // quarterly filing\n\"10-K/2023\" -> $209M // annual summary table\n\"DEF 14A/2024\" -> $211M // proxy exec comp section\n\n// Two analysts read the same proxy statement\n// Analyst A: CEO comp = $14.2M (includes options)\n// Analyst B: CEO comp = $8.7M (base + bonus only)\n\n// Both are \"correct\" -- different definitions\n" + }, + { + "type": "hook", + "id": "spiral-question", + "line": "Which extraction is correct?", + "subline": "Depends on the filing, the section, and what you're measuring." + }, + { + "type": "code", + "id": "catastrophe", + "title": "The Catastrophe", + "code": "// Agent builds a DCF model\n// Revenue: pulled from 10-K/A -> $847M (amended)\n// Cost of revenue: pulled from 10-K -> $612M (original)\n//\n// But the amendment changed cost allocations too.\n// Actual cost of revenue post-amendment: $658M\n//\n// Gross margin: 27.7% (agent's model)\n// Actual: 22.3%\n//\n// DCF valuation: off by $180M\n//\n// The model mixed amended and pre-amendment data\n// because there was no way to track the amendment chain.\n" + }, + { + "type": "code", + "id": "catastrophe-why", + "title": "The Root Cause", + "code": "// Filings were stored as flat key-value pairs\n// No amendment chain linking 10-K to 10-K/A\n// No section-level tracking\n// No way to know which data points were superseded\n//\n// The agent had no concept of \"this number was restated\"\n// It just grabbed the first match for each field\n//\n// Garbage in, $180M garbage out.\n" + }, + { + "type": "hook", + "id": "fix-intro", + "line": "What if filings carried their own lineage?", + "subline": "Every extraction linked to its source, section, and amendment chain." + }, + { + "type": "code", + "id": "fix-store", + "title": "Store extractions with filing metadata", + "code": "episteme.assert({\n subject: \"ACME/revenue/annual/2023\",\n predicate: \"value\",\n value: \"$847M\",\n\n source: {\n cik: \"0001234567\",\n form: \"10-K\",\n filed: \"2024-02-28\",\n section: \"Part II, Item 8\",\n accession: \"0001234567-24-000042\"\n },\n\n lifecycle: \"current\",\n confidence: 0.95\n});\n" + }, + { + "type": "code", + "id": "fix-amendment", + "title": "Amendments supersede cleanly", + "code": "// When the 10-K/A arrives:\nepisteme.assert({\n subject: \"ACME/goodwill/impairment/2023\",\n predicate: \"value\",\n value: \"$340M\",\n\n source: {\n form: \"10-K/A\",\n filed: \"2024-06-15\",\n amends: \"0001234567-24-000042\", // links to original\n sections_amended: [\"Note 7\", \"Part II Item 8\"]\n },\n\n lifecycle: \"current\",\n supersedes: \"ax7f3k9...\" // the $0 assertion\n});\n\n// The original $0 assertion is now lifecycle: \"superseded\"\n// Sections NOT in sections_amended remain valid\n" + }, + { + "type": "code", + "id": "fix-query", + "title": "Query with lifecycle: only current data", + "code": "// Agent building a DCF model queries:\nconst revenue = await episteme.query({\n subject: \"ACME/revenue/annual/2023\",\n lifecycle: \"current\"\n});\n// Returns $847M from 10-K/A (amended value)\n\nconst cost = await episteme.query({\n subject: \"ACME/cost-of-revenue/annual/2023\",\n lifecycle: \"current\"\n});\n// Returns $658M from 10-K/A (amended value)\n\n// Both values from the same amendment.\n// No mixing. No $180M error.\n" + }, + { + "type": "code", + "id": "time-travel", + "title": "What did we believe before the restatement?", + "code": "// Audit question: what was our position on March 1?\n// (before the 10-K/A was filed on June 15)\n\nepisteme.query({\n subject: \"ACME/goodwill/impairment/2023\",\n as_of: \"2024-03-01T00:00:00Z\"\n});\n\n// Returns: $0 (the original 10-K assertion)\n// At that point, that WAS the truth.\n\nepisteme.diff({\n subject: \"ACME/goodwill/impairment/2023\",\n from: \"2024-03-01\",\n to: \"2024-07-01\"\n});\n\n// Shows: 10-K/A filed June 15, impairment changed $0 -> $340M\n// Full audit trail. No guessing.\n" + }, + { + "type": "code", + "id": "multi-analyst", + "title": "Competing extractions coexist", + "code": "// Analyst A extracts CEO comp from proxy (DEF 14A)\nepisteme.assert({\n subject: \"ACME/exec-comp/CEO/2023\",\n value: \"$14.2M\",\n source: { form: \"DEF 14A\", section: \"Summary Compensation\" },\n confidence: 0.9,\n author: \"analyst-A\"\n});\n\n// Analyst B extracts from the same proxy\nepisteme.assert({\n subject: \"ACME/exec-comp/CEO/2023\",\n value: \"$8.7M\",\n source: { form: \"DEF 14A\", section: \"Summary Compensation\" },\n confidence: 0.85,\n author: \"analyst-B\"\n});\n\n// Both assertions coexist. No overwrite.\n" + }, + { + "type": "code", + "id": "multi-analyst-resolve", + "title": "Lens resolves at query time", + "code": "// Default lens: highest confidence wins\nepisteme.query({\n subject: \"ACME/exec-comp/CEO/2023\",\n lens: \"authority\"\n});\n// Returns: $14.2M (analyst-A, confidence 0.9)\n\n// But you can ask: show me all claims\nepisteme.query({\n subject: \"ACME/exec-comp/CEO/2023\",\n lens: \"all\"\n});\n// Returns both: $14.2M and $8.7M\n// With full provenance on each\n\n// The disagreement IS the signal.\n// Someone needs to reconcile definitions.\n" + }, + { + "type": "vision", + "id": "vision", + "title": "Episteme", + "points": [ + "Amendment chains, not flat overwrites.", + "Section-level provenance for every extraction.", + "Competing analyst reads coexist until resolved.", + "Time travel for audit and restatement analysis." + ], + "tagline": "Git for Truth" + } + ] + } + ] +} \ No newline at end of file diff --git a/docs/presentations/package.json b/docs/presentations/package.json index 68b7e4a..d2991cb 100644 --- a/docs/presentations/package.json +++ b/docs/presentations/package.json @@ -3,9 +3,10 @@ "version": "1.0.0", "description": "Data-driven presentations for Episteme", "scripts": { - "generate": "npx tsx scripts/generate.ts data/agile-agent-team.yaml", + "generate": "npx tsx scripts/generate.ts", + "generate:all": "for f in data/*.yaml; do npx tsx scripts/generate.ts \"$f\"; done && npx tsx scripts/combine.ts consumer-health-intelligence agile-agent-team sec-analysis", "serve": "npx serve .", - "dev": "npm run generate && npm run serve" + "dev": "npm run generate:all && npm run serve" }, "devDependencies": { "@types/node": "^20.0.0", diff --git a/docs/presentations/reveal/decks.html b/docs/presentations/reveal/decks.html new file mode 100644 index 0000000..f3e956b --- /dev/null +++ b/docs/presentations/reveal/decks.html @@ -0,0 +1,124 @@ + + + + + + Episteme - Presentations + + + + + + + + + + + diff --git a/docs/presentations/reveal/index.html b/docs/presentations/reveal/index.html index 34b64a1..6471e56 100644 --- a/docs/presentations/reveal/index.html +++ b/docs/presentations/reveal/index.html @@ -3,7 +3,7 @@ - Episteme - Agile AI Agent Team + Episteme @@ -26,9 +26,12 @@ - + diff --git a/docs/presentations/reveal/renderer.js b/docs/presentations/reveal/renderer.js index d4cc935..1883d81 100644 --- a/docs/presentations/reveal/renderer.js +++ b/docs/presentations/reveal/renderer.js @@ -1,148 +1,306 @@ /** * Episteme Presentation Renderer * - * Reads JSON data and renders Reveal.js slides + * Data-driven slide rendering with multi-deck support. + * + * Modes: + * flat - single deck, slides left/right (default Reveal.js) + * combined - menu column (↓ browse, → enter), decks are vertical (↓↑ navigate, ← back) + * + * Slide types are registered in RENDERERS. To add a new type, add one function. */ (async function () { - // Load presentation data - const dataUrl = window.PRESENTATION_DATA_URL || '../generated/agile-agent-team.json'; + const dataUrl = window.PRESENTATION_DATA_URL || '/generated/stemedb.json'; let data; try { - const response = await fetch(dataUrl); - data = await response.json(); - } catch (error) { - console.error('Failed to load presentation data:', error); + const resp = await fetch(dataUrl); + data = await resp.json(); + } catch (err) { document.getElementById('slides').innerHTML = ` -
+

Error Loading Presentation

Could not load ${dataUrl}

-

Run: npx ts-node scripts/generate.ts data/agile-agent-team.yaml

-
- `; +

Run: npm run generate:all

+
`; Reveal.initialize(); return; } - const slidesContainer = document.getElementById('slides'); + const root = document.getElementById('slides'); + const isCombined = !!data.combined; - // Actor icon mapping (simple initials for now) - function getActorInitials(actor) { + // ── Utilities ────────────────────────────────────────────── + + function esc(text) { + const el = document.createElement('div'); + el.textContent = text; + return el.innerHTML; + } + + function actorInitials(actor) { + if (!actor?.label) return '??'; return actor.label.split(' ').map(w => w[0]).join('').toUpperCase().slice(0, 2); } - // Format JSON for display - function formatData(data) { - if (!data) return ''; - return JSON.stringify(data, null, 2) - .replace(/"([^"]+)":/g, '"$1":') - .replace(/: "([^"]+)"/g, ': "$1"') - .replace(/: (\d+\.?\d*)/g, ': $1') - .replace(/: (true|false)/g, ': $1') - .replace(/: (null)/g, ': $1'); + function fragmentList(items, cls) { + return `
    ${items.map(p => `
  • ${p}
  • `).join('')}
`; } - // Render slides - function renderSlides(slides) { - let sectionNumber = 0; + // ── Slide-Type Registry ──────────────────────────────────── + // + // Each renderer receives (slide, ctx) and returns { css?, attrs?, html }. + // ctx = { actors, sectionNum } + const RENDERERS = { + title() { + return { + css: 'title-slide', + html: '

stemedb

', + }; + }, + + hook(slide) { + return { + css: 'hook-slide', + html: `
+

${slide.line}

+ ${slide.subline ? `

${slide.subline}

` : ''} +
`, + }; + }, + + code(slide) { + return { + css: 'code-slide', + html: `
+

${slide.title}

+
${esc(slide.code.trim())}
+
`, + }; + }, + + problem(slide) { + return { + css: 'problem-slide', + html: `
+

${slide.title}

+ ${fragmentList(slide.points, 'problem-points')} +
`, + }; + }, + + insight(slide) { + return { + css: 'insight-slide', + html: `
+

${slide.title}

+ ${fragmentList(slide.points, 'insight-points')} +
`, + }; + }, + + vision(slide) { + return { + css: 'vision-slide', + html: `
+

${slide.title}

+ ${fragmentList(slide.points, 'vision-points')} + ${slide.tagline ? `

${slide.tagline}

` : ''} +
`, + }; + }, + + 'section-title'(slide, ctx) { + ctx.sectionNum++; + return { + html: `
+ Section ${ctx.sectionNum} +

${slide.title}

+

${slide.subtitle}

+

${slide.description.trim()}

+
`, + }; + }, + + contrast(slide) { + return { + css: 'contrast-slide', + html: `
+

${slide.title}

+
+
+

${slide.before.title}

+
    ${slide.before.points.map(p => `
  • ${p}
  • `).join('')}
+
+
+

${slide.after.title}

+
    ${slide.after.points.map(p => `
  • ${p}
  • `).join('')}
+
+
+
`, + }; + }, + + sequence(slide, ctx) { + return { + attrs: { 'data-auto-animate': '' }, + html: renderSequence(slide, ctx.actors), + }; + }, + }; + + // ── Section Factory ──────────────────────────────────────── + + function createSection(slide, ctx) { + const render = RENDERERS[slide.type]; + if (!render) return null; + + const { css, attrs, html } = render(slide, ctx); + const el = document.createElement('section'); + if (css) el.classList.add(css); + if (attrs) Object.entries(attrs).forEach(([k, v]) => el.setAttribute(k, v)); + el.innerHTML = html; + return el; + } + + // ── Build: Flat (single deck) ────────────────────────────── + + function buildFlat(slides, actors) { + const ctx = { actors: actors || {}, sectionNum: 0 }; for (const slide of slides) { - const section = document.createElement('section'); - - switch (slide.type) { - case 'title': - section.classList.add('title-slide'); - section.innerHTML = ` -
-

stemedb

-
- `; - break; - - case 'section-title': - sectionNumber++; - section.innerHTML = ` -
- Section ${sectionNumber} -

${slide.title}

-

${slide.subtitle}

-

${slide.description.trim()}

-
- `; - break; - - case 'sequence': - section.setAttribute('data-auto-animate', ''); - section.innerHTML = renderSequenceSlide(slide, data.actors); - break; - } - - slidesContainer.appendChild(section); + const el = createSection(slide, ctx); + if (el) root.appendChild(el); } } - // Render sequence slide - function renderSequenceSlide(slide, allActors) { - const actors = slide.actors; - const steps = slide.steps; + // ── Build: Combined (multi-deck) ────────────────────────── - // Actor columns - const actorHtml = Object.values(actors).map(actor => ` + function buildCombined(decks) { + // Column 0: vertical menu stack + const menu = document.createElement('section'); + + // Title (reuses the registered title renderer — single source of truth) + menu.appendChild(createSection({ type: 'title' }, { actors: {}, sectionNum: 0 })); + + // Deck entry cards + decks.forEach((deck, i) => { + const card = document.createElement('section'); + card.classList.add('menu-slide'); + card.innerHTML = `
+ ${String(i + 1).padStart(2, '0')} +

${deck.meta.title}

+ ${deck.meta.subtitle ? `` : ''} + +
`; + menu.appendChild(card); + }); + + root.appendChild(menu); + + // Columns 1-N: each deck as a horizontal section wrapping vertical slides + for (const deck of decks) { + const col = document.createElement('section'); + const ctx = { actors: deck.actors || {}, sectionNum: 0 }; + for (const slide of deck.slides) { + if (slide.type === 'title') continue; // menu is the landing + const el = createSection(slide, ctx); + if (el) col.appendChild(el); + } + root.appendChild(col); + } + } + + // ── Sequence Slide (complex layout, kept separate) ───────── + + function renderSequence(slide, allActors) { + const actors = slide.actors.map(id => + typeof id === 'string' + ? allActors[id] || { id, label: id, color: '#666666' } + : id + ); + + const lookup = {}; + actors.forEach(a => { + lookup[a.id] = a; + const key = Object.keys(allActors).find(k => allActors[k].id === a.id); + if (key) lookup[key] = a; + }); + + const actorsHtml = actors.map(a => `
-
- ${getActorInitials(actor)} -
- ${actor.label} -
- `).join(''); - - // Step cards as fragments - const stepsHtml = steps.map((step, index) => { - const statusClass = step.danger ? 'danger' : (step.success ? 'success' : (step.warning ? 'warning' : '')); - const fromActor = step.fromActor || actors[step.from] || { label: step.from }; - const toActor = step.toActor || actors[step.to] || { label: step.to }; +
${actorInitials(a)}
+ ${a.label} + `).join(''); + const stepsHtml = slide.steps.map((step, i) => { + const cls = step.danger ? 'danger' : step.success ? 'success' : step.warning ? 'warning' : ''; + const from = lookup[step.from] || allActors[step.from] || { label: step.from }; + const to = lookup[step.to] || allActors[step.to] || { label: step.to }; return ` -
-
${index + 1}
+
+
${i + 1}
- ${fromActor.label} - → - ${toActor.label} + ${from.label} + → + ${to.label}
${step.action}
${step.label}
${step.note ? `
${step.note}
` : ''} - ${step.data ? `
${formatData(step.data)}
` : ''} ${step.callout ? `
${step.callout}
` : ''}
-
- `; +
`; }).join(''); - return ` -
-
-

${slide.title}

-
-
- ${actorHtml} -
-
- ${stepsHtml} -
-
- `; + return `
+

${slide.title}

+
${actorsHtml}
+
${stepsHtml}
+
`; } - // Render slides - renderSlides(data.slides); + // ── Keyboard: Combined Mode ──────────────────────────────── + // + // Menu (h=0): ↓↑ browse cards, → enter deck + // Deck (h>0): ↓↑ navigate slides, ← back to menu + // → also advances (alias for ↓) so arrow-mashing works + + function combinedKeys() { + return { + // → : menu → enter deck; inside deck → next slide + 39: function () { + const { h, v } = Reveal.getIndices(); + if (h === 0) { + Reveal.slide(v > 0 ? v : 1, 0); + } else { + Reveal.down(); + } + }, + // ← : first slide of deck → back to its menu card; deeper → prev slide + 37: function () { + const { h, v } = Reveal.getIndices(); + if (h > 0 && v === 0) { + Reveal.slide(0, h); + } else if (h > 0) { + Reveal.up(); + } + }, + }; + } + + // ── Render & Initialize ──────────────────────────────────── + + if (isCombined) { + buildCombined(data.decks); + } else { + buildFlat(data.slides, data.actors || {}); + } - // Initialize Reveal.js Reveal.initialize({ hash: true, history: true, @@ -151,34 +309,10 @@ center: true, transition: 'fade', transitionSpeed: 'fast', - - // Keyboard shortcuts - keyboard: { - // Arrow keys for fragments within slide - 39: 'next', // right - 37: 'prev', // left - }, + keyboard: isCombined ? combinedKeys() : { 39: 'next', 37: 'prev' }, }); - // Make step cards visible as fragments appear - Reveal.on('fragmentshown', event => { - event.fragment.classList.add('visible'); - }); + Reveal.on('fragmentshown', e => e.fragment.classList.add('visible')); + Reveal.on('fragmenthidden', e => e.fragment.classList.remove('visible')); - Reveal.on('fragmenthidden', event => { - event.fragment.classList.remove('visible'); - }); - - // Show all fragments on slide enter if coming from later slide - Reveal.on('slidechanged', event => { - const currentSlide = event.currentSlide; - const fragments = currentSlide.querySelectorAll('.fragment'); - - // Reset visibility on slide change - fragments.forEach(frag => { - if (frag.classList.contains('visible')) { - frag.classList.add('visible'); - } - }); - }); })(); diff --git a/docs/presentations/reveal/theme.css b/docs/presentations/reveal/theme.css index 0ee73c6..713a26f 100644 --- a/docs/presentations/reveal/theme.css +++ b/docs/presentations/reveal/theme.css @@ -56,6 +56,11 @@ background: var(--bg-primary); } +/* Ensure all slides have opaque background - fixes ghost bleed */ +.reveal .slides section { + background: var(--bg-primary); +} + .reveal { font-family: var(--font-sans); font-size: 24px; @@ -114,10 +119,7 @@ background: var(--text-muted); } -/* Hide progress on title slide */ -.reveal .slides section.title-slide ~ .progress { - opacity: 0; -} +/* Progress bar styling is handled via Reveal.js config */ /* Controls - minimal */ .reveal .controls { @@ -133,8 +135,7 @@ opacity: 0.6; } -/* Hide controls on title slide */ -.reveal .slides section.title-slide ~ .controls, +/* Hide controls on title slide via data-state */ .reveal[data-state="title"] .controls { opacity: 0; } @@ -178,6 +179,60 @@ display: none; } +/* Menu slide - deck picker in combined mode */ +.reveal .slides section.menu-slide { + height: 100%; + display: flex !important; + align-items: center !important; + justify-content: center !important; +} + +.slide-menu-card { + display: flex; + flex-direction: column; + align-items: flex-start; + padding-left: 10%; + max-width: 800px; + width: 100%; +} + +.slide-menu-card .menu-card-number { + font-family: var(--font-mono); + font-size: 0.875rem; + font-weight: 500; + color: var(--accent-episteme); + letter-spacing: 0.1em; + margin-bottom: var(--space-md); +} + +.slide-menu-card h2 { + font-size: 3rem; + font-weight: 600; + letter-spacing: -0.02em; + margin-bottom: var(--space-sm); +} + +.slide-menu-card .menu-card-subtitle { + font-size: 1.25rem; + color: var(--text-secondary); + margin-bottom: var(--space-xl); +} + +.slide-menu-card .menu-card-hint { + font-size: 1rem; + color: var(--text-muted); +} + +.slide-menu-card .key-hint { + display: inline-block; + padding: 0.1em 0.5em; + background: var(--border-subtle); + border-radius: 4px; + font-family: var(--font-mono); + font-size: 0.875rem; + color: var(--text-secondary); +} + /* Section title slide */ .slide-section-title { display: flex; @@ -215,6 +270,323 @@ line-height: 1.6; } +/* Hook slide - Single powerful line */ +.reveal .slides section.hook-slide { + height: 100%; + display: flex !important; + align-items: center !important; + justify-content: center !important; +} + +.slide-hook { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + text-align: center; + padding: 0 10%; +} + +.slide-hook .hook-line { + font-size: 3rem; + font-weight: 400; + color: var(--text-primary); + line-height: 1.3; + letter-spacing: -0.02em; +} + +.slide-hook .hook-subline { + font-size: 1.5rem; + font-weight: 400; + color: var(--text-secondary); + margin-top: var(--space-lg); + line-height: 1.4; +} + +/* Problem slide */ +.reveal .slides section.problem-slide { + height: 100%; + display: flex !important; + align-items: center !important; + justify-content: center !important; +} + +.slide-problem { + display: flex; + flex-direction: column; + align-items: flex-start; + padding-left: 10%; + max-width: 800px; +} + +.slide-problem h2 { + font-size: 2.5rem; + font-weight: 600; + margin-bottom: var(--space-xl); + color: var(--text-primary); +} + +.slide-problem .problem-points { + list-style: none; + padding: 0; + margin: 0; +} + +.slide-problem .problem-points li { + font-size: 1.5rem; + color: var(--text-secondary); + margin-bottom: var(--space-lg); + padding-left: var(--space-lg); + position: relative; +} + +.slide-problem .problem-points li::before { + content: "—"; + position: absolute; + left: 0; + color: var(--text-muted); +} + +/* Insight slide */ +.reveal .slides section.insight-slide { + height: 100%; + display: flex !important; + align-items: center !important; + justify-content: center !important; +} + +.slide-insight { + display: flex; + flex-direction: column; + align-items: flex-start; + padding-left: 10%; + max-width: 800px; +} + +.slide-insight h2 { + font-size: 2.5rem; + font-weight: 600; + margin-bottom: var(--space-xl); + color: var(--accent-episteme); +} + +.slide-insight .insight-points { + list-style: none; + padding: 0; + margin: 0; +} + +.slide-insight .insight-points li { + font-size: 1.5rem; + color: var(--text-secondary); + margin-bottom: var(--space-lg); + padding-left: var(--space-lg); + position: relative; +} + +.slide-insight .insight-points li::before { + content: "→"; + position: absolute; + left: 0; + color: var(--accent-episteme); +} + +/* Contrast slide - side by side comparison */ +.reveal .slides section.contrast-slide { + height: 100%; + display: flex !important; + align-items: center !important; + justify-content: center !important; +} + +.slide-contrast { + display: flex; + flex-direction: column; + align-items: center; + width: 100%; + max-width: 1100px; +} + +.slide-contrast h2 { + font-size: 2.5rem; + font-weight: 600; + margin-bottom: var(--space-xl); + color: var(--text-primary); +} + +.contrast-container { + display: flex; + gap: var(--space-xl); + width: 100%; +} + +.contrast-side { + flex: 1; + padding: var(--space-lg); + border-radius: 12px; + border: 1px solid var(--border-subtle); +} + +.contrast-side.before { + background: rgba(239, 68, 68, 0.1); + border-color: var(--accent-danger); +} + +.contrast-side.after { + background: rgba(16, 185, 129, 0.1); + border-color: var(--accent-success); +} + +.contrast-side h3 { + font-size: 1.25rem; + font-weight: 600; + margin-bottom: var(--space-md); +} + +.contrast-side.before h3 { + color: var(--accent-danger); +} + +.contrast-side.after h3 { + color: var(--accent-success); +} + +.contrast-side .contrast-points { + list-style: none; + padding: 0; + margin: 0; +} + +.contrast-side .contrast-points li { + font-size: 1.125rem; + color: var(--text-secondary); + margin-bottom: var(--space-md); + padding-left: var(--space-lg); + position: relative; +} + +.contrast-side.before .contrast-points li::before { + content: "✗"; + position: absolute; + left: 0; + color: var(--accent-danger); +} + +.contrast-side.after .contrast-points li::before { + content: "✓"; + position: absolute; + left: 0; + color: var(--accent-success); +} + +.contrast-callout { + margin-top: var(--space-xl); + font-size: 1.5rem; + color: var(--accent-episteme); + text-align: center; +} + +/* Vision slide */ +.reveal .slides section.vision-slide { + height: 100%; + display: flex !important; + align-items: center !important; + justify-content: center !important; +} + +.slide-vision { + display: flex; + flex-direction: column; + align-items: center; + text-align: center; + max-width: 800px; +} + +.slide-vision h2 { + font-size: 2.5rem; + font-weight: 600; + margin-bottom: var(--space-xl); + color: var(--text-primary); +} + +.slide-vision .vision-points { + list-style: none; + padding: 0; + margin: 0; + text-align: left; +} + +.slide-vision .vision-points li { + font-size: 1.5rem; + color: var(--text-secondary); + margin-bottom: var(--space-lg); + padding-left: var(--space-lg); + position: relative; +} + +.slide-vision .vision-points li::before { + content: "✓"; + position: absolute; + left: 0; + color: var(--accent-success); +} + +.slide-vision .vision-tagline { + font-size: 3rem; + font-weight: 400; + color: var(--accent-episteme); + margin-top: var(--space-2xl); + letter-spacing: -0.02em; +} + +/* ============================================== + CODE SLIDE - Clean, minimal + ============================================== */ + +.reveal .slides section.code-slide { + height: 100%; + display: flex !important; + align-items: center !important; + justify-content: center !important; + padding: var(--space-xl); +} + +.slide-code { + width: 100%; + max-width: 800px; +} + +.slide-code h2 { + font-size: 1.25rem; + font-weight: 500; + margin-bottom: var(--space-lg); + color: var(--text-secondary); +} + +.code-block { + background: var(--bg-secondary); + border-radius: 8px; + border: 1px solid var(--border-subtle); + overflow: hidden; +} + +.code-block pre { + margin: 0; + padding: var(--space-lg); + overflow-x: auto; +} + +.code-block code { + font-family: var(--font-mono); + font-size: 0.875rem; + line-height: 1.7; + color: var(--text-primary); + background: transparent; + padding: 0; + white-space: pre; + display: block; +} + /* ============================================== SEQUENCE DIAGRAM SLIDE ============================================== */ diff --git a/docs/presentations/scripts/combine.ts b/docs/presentations/scripts/combine.ts new file mode 100644 index 0000000..da5f289 --- /dev/null +++ b/docs/presentations/scripts/combine.ts @@ -0,0 +1,53 @@ +#!/usr/bin/env npx tsx +/** + * Combine individual deck JSONs into a single multi-deck presentation. + * + * Usage: + * npx tsx scripts/combine.ts [deck-id ...] + * + * If deck IDs are provided, they define the order. + * Otherwise, all JSONs in generated/ are combined alphabetically. + */ + +import * as fs from 'fs'; +import * as path from 'path'; + +const generatedDir = path.resolve(__dirname, '..', 'generated'); + +const args = process.argv.slice(2); +let deckIds: string[]; + +if (args.length > 0) { + deckIds = args; +} else { + deckIds = fs.readdirSync(generatedDir) + .filter(f => f.endsWith('.json') && f !== 'stemedb.json') + .map(f => f.replace('.json', '')) + .sort(); +} + +if (deckIds.length === 0) { + console.error('No deck JSON files found in generated/'); + process.exit(1); +} + +const decks = []; +for (const id of deckIds) { + const filePath = path.join(generatedDir, `${id}.json`); + if (!fs.existsSync(filePath)) { + console.error(`Deck not found: ${filePath}`); + process.exit(1); + } + const content = fs.readFileSync(filePath, 'utf-8'); + decks.push(JSON.parse(content)); +} + +const combined = { + combined: true, + meta: { id: 'stemedb', title: 'stemedb' }, + decks, +}; + +const outputPath = path.join(generatedDir, 'stemedb.json'); +fs.writeFileSync(outputPath, JSON.stringify(combined, null, 2)); +console.log(`Generated: ${outputPath} (${decks.length} decks)`); diff --git a/docs/presentations/scripts/generate.ts b/docs/presentations/scripts/generate.ts index e71049d..c72e002 100644 --- a/docs/presentations/scripts/generate.ts +++ b/docs/presentations/scripts/generate.ts @@ -1,12 +1,12 @@ -#!/usr/bin/env npx ts-node +#!/usr/bin/env npx tsx /** * Presentation Generator * - * Reads YAML sequence data and generates: - * 1. Mermaid sequence diagrams (.mmd) + * Reads YAML slide data and generates: + * 1. Mermaid sequence diagrams (.mmd) for sequence slides * 2. JSON for Reveal.js slides * - * Usage: npx ts-node generate.ts ../data/agile-agent-team.yaml + * Usage: npx tsx scripts/generate.ts data/agile-agent-team.yaml */ import * as fs from 'fs'; @@ -20,17 +20,12 @@ interface Actor { color: string; } -interface StepData { - [key: string]: unknown; -} - interface Step { id: string; from: string; to: string; action: string; label: string; - data?: StepData; note?: string; callout?: string; danger?: boolean; @@ -38,14 +33,57 @@ interface Step { success?: boolean; } -interface Sequence { +interface TitleSlide { + type: 'title'; + id: string; +} + +interface HookSlide { + type: 'hook'; + id: string; + line: string; +} + +interface ProblemSlide { + type: 'problem'; + id: string; + title: string; + points: string[]; +} + +interface SectionTitleSlide { + type: 'section-title'; id: string; title: string; subtitle: string; description: string; +} + +interface SequenceSlide { + type: 'sequence'; + id: string; + title: string; + actors: string[]; steps: Step[]; } +interface InsightSlide { + type: 'insight'; + id: string; + title: string; + points: string[]; +} + +interface VisionSlide { + type: 'vision'; + id: string; + title: string; + points: string[]; + tagline?: string; +} + +type Slide = TitleSlide | HookSlide | ProblemSlide | SectionTitleSlide | SequenceSlide | InsightSlide | VisionSlide; + interface PresentationData { meta: { id: string; @@ -54,7 +92,7 @@ interface PresentationData { version: string; }; actors: Record; - sequences: Sequence[]; + slides: Slide[]; annotations: Record; } -// Generate Mermaid sequence diagram for a sequence -function generateMermaid(data: PresentationData, sequence: Sequence): string { +// Generate Mermaid sequence diagram for a sequence slide +function generateMermaid(data: PresentationData, sequence: SequenceSlide): string { const lines: string[] = []; lines.push('sequenceDiagram'); - lines.push(` %% ${sequence.title}: ${sequence.subtitle}`); + lines.push(` %% ${sequence.title}`); lines.push(''); // Collect unique actors used in this sequence @@ -124,59 +162,13 @@ function generateMermaid(data: PresentationData, sequence: Sequence): string { return lines.join('\n'); } -// Generate JSON for Reveal.js +// Generate JSON for Reveal.js - pass through slides with actor resolution function generateRevealJson(data: PresentationData): object { - const slides: object[] = []; - - // Title slide - slides.push({ - type: 'title', - title: data.meta.title, - subtitle: data.meta.subtitle, - }); - - // Generate slides for each sequence - for (const sequence of data.sequences) { - // Sequence title slide - slides.push({ - type: 'section-title', - title: sequence.title, - subtitle: sequence.subtitle, - description: sequence.description, - }); - - // Create step slides - group steps for animation - const stepSlide = { - type: 'sequence', - sequenceId: sequence.id, - title: sequence.title, - actors: {} as Record, - steps: sequence.steps.map((step, index) => ({ - ...step, - index, - fromActor: data.actors[step.from], - toActor: data.actors[step.to], - })), - }; - - // Collect actors for this sequence - for (const step of sequence.steps) { - if (data.actors[step.from]) { - stepSlide.actors[step.from] = data.actors[step.from]; - } - if (data.actors[step.to]) { - stepSlide.actors[step.to] = data.actors[step.to]; - } - } - - slides.push(stepSlide); - } - return { meta: data.meta, actors: data.actors, annotations: data.annotations, - slides, + slides: data.slides, }; } @@ -184,7 +176,7 @@ function generateRevealJson(data: PresentationData): object { function main() { const args = process.argv.slice(2); if (args.length < 1) { - console.error('Usage: npx ts-node generate.ts '); + console.error('Usage: npx tsx scripts/generate.ts '); process.exit(1); } @@ -193,34 +185,58 @@ function main() { const baseName = path.basename(inputPath, '.yaml'); // Read and parse YAML - const yamlContent = fs.readFileSync(inputPath, 'utf-8'); - const data = yaml.parse(yamlContent) as PresentationData; + let data: PresentationData; + try { + const yamlContent = fs.readFileSync(inputPath, 'utf-8'); + data = yaml.parse(yamlContent) as PresentationData; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + console.error(`Failed to read/parse ${inputPath}: ${message}`); + process.exit(1); + } + + // Validate required fields + if (!data.meta || !data.actors || !data.slides) { + console.error('Invalid presentation data: missing required fields (meta, actors, slides)'); + process.exit(1); + } // Output directory const outputDir = path.resolve(inputDir, '..', 'generated'); fs.mkdirSync(outputDir, { recursive: true }); - // Generate Mermaid for each sequence - for (const sequence of data.sequences) { - const mermaid = generateMermaid(data, sequence); - const mermaidPath = path.join(outputDir, `${baseName}-${sequence.id}.mmd`); - fs.writeFileSync(mermaidPath, mermaid); - console.log(`Generated: ${mermaidPath}`); + // Find all sequence slides + const sequenceSlides = data.slides.filter((s): s is SequenceSlide => s.type === 'sequence'); + + try { + // Generate Mermaid for each sequence + for (const sequence of sequenceSlides) { + const mermaid = generateMermaid(data, sequence); + const mermaidPath = path.join(outputDir, `${baseName}-${sequence.id}.mmd`); + fs.writeFileSync(mermaidPath, mermaid); + console.log(`Generated: ${mermaidPath}`); + } + + // Generate combined Mermaid + if (sequenceSlides.length > 0) { + const allMermaid = sequenceSlides + .map(seq => generateMermaid(data, seq)) + .join('\n\n---\n\n'); + const combinedMermaidPath = path.join(outputDir, `${baseName}.mmd`); + fs.writeFileSync(combinedMermaidPath, allMermaid); + console.log(`Generated: ${combinedMermaidPath}`); + } + + // Generate JSON for Reveal.js + const revealJson = generateRevealJson(data); + const jsonPath = path.join(outputDir, `${baseName}.json`); + fs.writeFileSync(jsonPath, JSON.stringify(revealJson, null, 2)); + console.log(`Generated: ${jsonPath}`); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + console.error(`Failed to write output files: ${message}`); + process.exit(1); } - - // Generate combined Mermaid - const allMermaid = data.sequences - .map(seq => generateMermaid(data, seq)) - .join('\n\n---\n\n'); - const combinedMermaidPath = path.join(outputDir, `${baseName}.mmd`); - fs.writeFileSync(combinedMermaidPath, allMermaid); - console.log(`Generated: ${combinedMermaidPath}`); - - // Generate JSON for Reveal.js - const revealJson = generateRevealJson(data); - const jsonPath = path.join(outputDir, `${baseName}.json`); - fs.writeFileSync(jsonPath, JSON.stringify(revealJson, null, 2)); - console.log(`Generated: ${jsonPath}`); } main(); diff --git a/docs/sdk/go-sdk.md b/docs/sdk/go-sdk.md new file mode 100644 index 0000000..707bcd9 --- /dev/null +++ b/docs/sdk/go-sdk.md @@ -0,0 +1,457 @@ +# StemeDB Go SDK + +The official Go SDK for StemeDB - A probabilistic knowledge graph database. + +## Overview + +The Go SDK provides a type-safe, ergonomic API for interacting with StemeDB. It handles all the cryptographic complexity (Ed25519 signing, BLAKE3 hashing) and provides fluent builders for constructing assertions and queries. + +## Installation + +```bash +go get github.com/orchard9/stemedb-go/steme +``` + +## Quick Start + +```go +package main + +import ( + "context" + "log" + + "github.com/orchard9/stemedb-go/steme" +) + +func main() { + // Create a signer (or load from environment) + signer, err := steme.GenerateSigner() + if err != nil { + log.Fatal(err) + } + + // Create client + client := steme.NewClient("http://localhost:3000", signer) + + // Build and submit an assertion + assertion := steme.NewAssertion("Tesla_Inc", "has_revenue"). + WithNumber(96.7). + WithConfidence(0.95). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + + hash, err := client.Assert(context.Background(), assertion) + if err != nil { + log.Fatal(err) + } + + log.Printf("Created assertion: %s", hash) +} +``` + +## Core Concepts + +### 1. Signers + +Every assertion submitted to StemeDB must be cryptographically signed using Ed25519. The SDK abstracts this complexity. + +```go +// Generate new keypair +signer, err := steme.GenerateSigner() + +// Load from hex-encoded seed +signer, err := steme.NewSignerFromHex("your-64-char-hex-seed") + +// Load from environment variable +signer, err := steme.SignerFromEnv("STEME_PRIVATE_KEY") + +// Get your agent_id (public key) +agentID := signer.PublicKey() // 64-char hex string + +// Save seed for recovery +seed := signer.Seed() // Store this securely! +``` + +### 2. Assertions + +Assertions are the atomic units of knowledge in StemeDB. Use the fluent builder API. + +```go +assertion := steme.NewAssertion("Subject", "Predicate"). + WithNumber(42.5). // Object value + WithConfidence(0.95). // 0.0 to 1.0 + WithLifecycle(steme.LifecycleApproved). // Stage + WithSourceClass(steme.SourceClassClinical). // Authority tier + WithSourceHash("..."). // Evidence hash + Build() +``` + +#### Object Values + +StemeDB supports four value types: + +```go +// Text +assertion.WithText("hello world") + +// Number (float64) +assertion.WithNumber(96.7) + +// Boolean +assertion.WithBoolean(true) + +// Reference (entity ID) +assertion.WithReference("Other_Entity") +``` + +#### Lifecycle Stages + +Assertions progress through lifecycle stages: + +```go +steme.LifecycleProposed // Initial idea/RFC +steme.LifecycleUnderReview // Active debate +steme.LifecycleApproved // Current truth +steme.LifecycleDeprecated // Was true, now superseded +steme.LifecycleRejected // Explicitly declined +``` + +#### Source Authority Tiers + +Sources are tiered from most authoritative (Tier 0) to least (Tier 5): + +```go +steme.SourceClassRegulatory // Tier 0: FDA, EMA, WHO +steme.SourceClassClinical // Tier 1: Peer-reviewed trials +steme.SourceClassObservational // Tier 2: Real-world evidence +steme.SourceClassExpert // Tier 3: Guidelines +steme.SourceClassCommunity // Tier 4: Curated forums +steme.SourceClassAnecdotal // Tier 5: Social media +``` + +### 3. Queries + +Query assertions with optional filters and lens-based conflict resolution. + +```go +params := steme.NewQuery(). + WithSubject("Tesla_Inc"). + WithPredicate("has_revenue"). + WithLifecycle(steme.LifecycleApproved). + WithLens(steme.LensConsensus). + WithLimit(10). + Build() + +result, err := client.Query(ctx, params) +``` + +#### Lenses + +Lenses resolve conflicts among competing assertions: + +```go +steme.LensRecency // Latest timestamp wins +steme.LensConsensus // Most common value +steme.LensAuthority // Weighted by source tier +steme.LensVoteAwareConsensus // Highest vote weight +steme.LensTrustAwareAuthority // Weighted by TrustRank +``` + +### 4. Skeptic Queries ("Trust but Verify") + +Unlike standard queries that pick a winner, Skeptic shows all competing claims. + +```go +result, err := client.Skeptic(ctx, steme.SkepticQueryParams{ + Subject: "Semaglutide", + Predicate: "muscle_effect", +}) + +// Resolution status +switch result.Status { +case steme.ResolutionUnanimous: + // All sources agree +case steme.ResolutionAgreed: + // >75% weight on one claim +case steme.ResolutionContested: + // Significant disagreement +} + +// Conflict score: 0.0 (unanimous) to 1.0 (chaos) +fmt.Printf("Conflict: %.2f\n", result.ConflictScore) + +// All competing claims +for _, claim := range result.Claims { + fmt.Printf("%v: %.1f%% support (%d assertions)\n", + claim.Value.Value, + claim.WeightShare*100, + claim.AssertionCount, + ) +} +``` + +## Advanced Features + +### Context Support + +All API calls accept `context.Context` for cancellation and timeouts. + +```go +ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) +defer cancel() + +result, err := client.Query(ctx, params) +``` + +### Custom HTTP Client + +Customize timeouts, TLS, or add middleware. + +```go +httpClient := &http.Client{ + Timeout: 10 * time.Second, + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{ + InsecureSkipVerify: true, // Don't do this in production! + }, + }, +} + +client := steme.NewClient("https://stemedb.example.com", signer). + WithHTTPClient(httpClient) +``` + +### Forking Assertions + +Create a new assertion that supersedes an existing one. + +```go +originalHash := "abc123..." // Hash from previous assertion + +updated := steme.NewAssertion("Tesla_Inc", "has_revenue"). + WithNumber(102.5). // New value + WithParentHash(originalHash). // Link to original + WithLifecycle(steme.LifecycleApproved). + WithSourceHash("..."). + Build() + +newHash, err := client.Assert(ctx, updated) +``` + +### Validation + +Assertions are validated client-side before submission. + +```go +assertion := steme.NewAssertion("Tesla_Inc", "has_revenue"). + WithNumber(96.7). + WithConfidence(1.5). // Invalid! Must be 0.0-1.0 + Build() + +if err := assertion.Validate(); err != nil { + // Handle validation error + fmt.Printf("Validation failed: %v\n", err) +} +``` + +## Error Handling + +The SDK uses typed errors for common failure modes. + +```go +hash, err := client.Assert(ctx, assertion) +if err != nil { + switch e := err.(type) { + case *steme.APIError: + // HTTP error from server + fmt.Printf("API error [%d]: %s (code: %s)\n", + e.StatusCode, e.Message, e.Code) + + case *steme.ValidationError: + // Client-side validation failure + fmt.Printf("Invalid %s: %s\n", e.Field, e.Message) + + default: + // Other errors (network, etc.) + fmt.Printf("Error: %v\n", err) + } +} +``` + +## Examples + +### Basic Usage + +See `sdk/go/examples/basic/main.go` for a complete example showing: +- Keypair generation +- Assertion creation +- Automatic signing +- Querying with lenses + +```bash +cd sdk/go/examples/basic +go run main.go +``` + +### Skeptic Lens + +See `sdk/go/examples/skeptic/main.go` for a "Trust but Verify" example showing: +- Seeding conflicting assertions +- Analyzing disagreement +- Interpreting conflict scores + +```bash +cd sdk/go/examples/skeptic +go run main.go +``` + +## Testing + +Run unit tests: + +```bash +cd sdk/go/steme +go test -v +``` + +Integration tests require a running StemeDB server: + +```bash +# Start StemeDB server +cd /path/to/stemedb +cargo run --bin stemedb-api + +# Run integration tests +export STEMEDB_URL=http://localhost:3000 +cd sdk/go/steme +go test -v +``` + +## Best Practices + +### Key Management + +1. Never commit private keys to version control +2. Use environment variables or key management services +3. Rotate keys periodically +4. Use different keys for dev/staging/production + +```go +// Good: Load from environment +signer, err := steme.SignerFromEnv("STEME_PRIVATE_KEY") + +// Bad: Hardcoded seed +signer, err := steme.NewSignerFromHex("abc123...") // Don't do this! +``` + +### Source Hashing + +1. Use BLAKE3 for source document hashing +2. Include timestamp + URL for web sources +3. Include file hash + timestamp for local files + +```go +import "lukechampine.com/blake3" + +// Hash a source document +sourceBytes := []byte(documentContent) +sourceHash := blake3.Sum256(sourceBytes) +sourceHashHex := hex.EncodeToString(sourceHash[:]) + +assertion.WithSourceHash(sourceHashHex) +``` + +### Confidence Scores + +1. Start conservative (0.7-0.8 for human-submitted claims) +2. Use 0.95+ only for regulatory/peer-reviewed sources +3. Use 0.5-0.6 for anecdotal evidence +4. Never use 1.0 (implies certainty) + +```go +// Good: Conservative confidence +assertion.WithConfidence(0.85) + +// Bad: False certainty +assertion.WithConfidence(1.0) +``` + +## Migration from Manual HTTP + +If you're currently using raw HTTP calls, migration is straightforward. + +### Before (Manual HTTP) + +```go +// Build JSON payload +payload := map[string]interface{}{ + "subject": "Tesla_Inc", + "predicate": "has_revenue", + "object": map[string]interface{}{"type": "Number", "value": 96.7}, + "confidence": 0.95, + // ... compute signature manually ... +} + +// POST to API +resp, err := http.Post("http://localhost:3000/v1/assert", "application/json", ...) +``` + +### After (SDK) + +```go +assertion := steme.NewAssertion("Tesla_Inc", "has_revenue"). + WithNumber(96.7). + WithConfidence(0.95). + WithSourceHash("..."). + Build() + +hash, err := client.Assert(ctx, assertion) +``` + +## Performance Considerations + +### Batching + +For high-volume ingestion, batch assertions: + +```go +for i := 0; i < 1000; i++ { + assertion := steme.NewAssertion(fmt.Sprintf("Entity_%d", i), "predicate"). + WithNumber(float64(i)). + WithSourceHash("..."). + Build() + + if _, err := client.Assert(ctx, assertion); err != nil { + log.Printf("Failed to assert %d: %v", i, err) + } +} +``` + +Future SDK versions will include a `BatchAssert()` method for improved performance. + +### Connection Pooling + +The SDK uses `http.Client` which automatically reuses connections. Reuse the same `Client` instance. + +```go +// Good: Reuse client +client := steme.NewClient(baseURL, signer) +for i := 0; i < 1000; i++ { + client.Assert(ctx, assertions[i]) +} + +// Bad: Create new client each time +for i := 0; i < 1000; i++ { + client := steme.NewClient(baseURL, signer) // Wasteful! + client.Assert(ctx, assertions[i]) +} +``` + +## Contributing + +See the main repository's `CONTRIBUTING.md` for guidelines. + +## License + +MIT diff --git a/docs/specs/visual-hash-query.md b/docs/specs/visual-hash-query.md new file mode 100644 index 0000000..756ee59 --- /dev/null +++ b/docs/specs/visual-hash-query.md @@ -0,0 +1,453 @@ +# Visual Hash Query Support + +> **Status:** Draft +> **Phase:** 2.4 (MVP) +> **Pillars:** First-Class Contradiction (Visual Domain), Visual Anchoring +> **Primary Use Cases:** Financial Due Diligence, GLP-1 Living Review, Consumer Health Intelligence + +--- + +## Problem Statement + +The `visual_hash: Option` field exists on `Assertion` and is stored/returned by the API, but there is no way to query by visual similarity. The field is write-only from a query perspective. + +This creates a gap between what we promise and what we deliver: + +| Promise (from use-cases) | Reality | +|--------------------------|---------| +| "Query by visual similarity" | No query parameter exists | +| "Find all assertions anchored to visually similar images" | Must scan entire dataset manually | +| "Catches duplicate evidence, fake variations, source reuse" | Cannot detect duplicates | + +### The Pain Points + +**Research Agent:** "I extract the same clinical trial table 10 times. Each extraction drifts slightly. I stored visual_hash hoping to detect duplicates. I can't query by it." + +**Human Supervisor (3am incident):** "Agent made a bad decision based on an assertion with visual_hash. I need to find all assertions from that same screenshot. I can't." + +**M&A Analyst:** "I have two screenshots of the same org chart from different sources. I want to prove they corroborate each other. I can't query by visual similarity." + +--- + +## MVP Scope (Phase 2.4) + +### What We're Building + +A brute-force visual similarity query capability using hamming distance on perceptual hashes. + +### API Changes + +#### Query Struct (`stemedb-query`) + +```rust +pub struct Query { + // ... existing fields ... + + /// Filter by visual similarity to a reference pHash. + /// Hex-encoded 8-byte perceptual hash (16 hex chars). + pub visual_near: Option, + + /// Maximum hamming distance for visual_near matching. + /// Default: 8 bits (sweet spot for pHash similarity). + /// Range: 0-64 (0 = exact match, 64 = match anything). + pub visual_threshold: Option, +} +``` + +#### QueryBuilder (`stemedb-query`) + +```rust +impl QueryBuilder { + /// Filter by visual similarity to a reference pHash. + /// + /// # Arguments + /// * `hash` - Hex-encoded pHash (16 chars) + /// * `threshold` - Max hamming distance (default: 8) + /// + /// # Example + /// ``` + /// let query = QueryBuilder::new() + /// .subject("BioStart_CEO") + /// .predicate("reports_to") + /// .visual_near("a3f2b1c4d5e6f708", 8) + /// .build(); + /// ``` + pub fn visual_near(mut self, hash: &str, threshold: u32) -> Self { + self.visual_near = Some(hash.to_string()); + self.visual_threshold = Some(threshold); + self + } +} +``` + +#### HTTP API (`stemedb-api`) + +``` +GET /v1/query?visual_near=a3f2b1c4d5e6f708&visual_threshold=8 + +Query Parameters: + visual_near - Hex-encoded pHash (16 characters, optional) + visual_threshold - Max hamming distance (0-64, default: 8, optional) +``` + +### Core Algorithm + +```rust +/// Compute hamming distance between two perceptual hashes. +/// +/// Hamming distance = number of differing bits. +/// For 8-byte pHash, range is 0-64. +pub fn hamming_distance(a: &[u8; 8], b: &[u8; 8]) -> u32 { + a.iter() + .zip(b.iter()) + .map(|(x, y)| (x ^ y).count_ones()) + .sum() +} +``` + +### Matching Logic + +In `Query::matches()`: + +```rust +// If visual_near is specified, check visual similarity +if let Some(ref target_hash) = self.visual_near { + match &assertion.visual_hash { + Some(assertion_hash) => { + let target = parse_hex_phash(target_hash)?; + let distance = hamming_distance(&target, assertion_hash); + let threshold = self.visual_threshold.unwrap_or(8); + if distance > threshold { + return false; // Too dissimilar + } + } + None => return false, // No visual_hash, can't match + } +} +``` + +### Go SDK Changes + +```go +// QueryBuilder addition +func (b *QueryBuilder) VisualNear(hash string, threshold uint32) *QueryBuilder { + b.visualNear = hash + b.visualThreshold = threshold + return b +} + +// Usage +query := steme.NewQuery(). + Subject("BioStart_CEO"). + Predicate("reports_to"). + VisualNear("a3f2b1c4d5e6f708", 8). + Build() +``` + +--- + +## Threshold Guidance + +Hamming distance thresholds for 64-bit pHash: + +| Threshold | Meaning | Use Case | +|-----------|---------|----------| +| 0 | Exact match | Deduplication, identical images | +| 1-4 | Very similar | Safety-critical (medications, financial) | +| 5-8 | Similar | General visual matching (default) | +| 9-12 | Loosely similar | Catch resized/cropped variants | +| 13+ | Weak similarity | Exploratory search | + +### Domain-Specific Recommendations + +| Domain | Recommended Threshold | Rationale | +|--------|----------------------|-----------| +| Consumer Health | 4-5 | False positives for medications are dangerous | +| Financial Due Diligence | 8-10 | Screenshots get cropped/resized | +| Pharma/Clinical | 6-8 | Balance accuracy vs OCR variations | +| General | 8 | pHash literature default | + +--- + +## Test Cases + +### Unit Tests (`stemedb-query`) + +```rust +#[test] +fn test_visual_near_exact_match() { + // Same hash, threshold 0 -> matches + let hash = [0xA3, 0xF2, 0xB1, 0xC4, 0xD5, 0xE6, 0xF7, 0x08]; + let assertion = make_assertion_with_visual_hash(hash); + let query = QueryBuilder::new() + .visual_near("a3f2b1c4d5e6f708", 0) + .build(); + assert!(query.matches(&assertion)); +} + +#[test] +fn test_visual_near_within_threshold() { + // Hashes differ by 3 bits, threshold 5 -> matches + let hash_a = [0xA3, 0xF2, 0xB1, 0xC4, 0xD5, 0xE6, 0xF7, 0x08]; + let hash_b = [0xA3, 0xF2, 0xB1, 0xC4, 0xD5, 0xE6, 0xF7, 0x0F]; // 3 bits differ + let assertion = make_assertion_with_visual_hash(hash_b); + let query = QueryBuilder::new() + .visual_near("a3f2b1c4d5e6f708", 5) + .build(); + assert!(query.matches(&assertion)); +} + +#[test] +fn test_visual_near_exceeds_threshold() { + // Hashes differ by 10 bits, threshold 5 -> no match + let hash_a = [0xA3, 0xF2, 0xB1, 0xC4, 0xD5, 0xE6, 0xF7, 0x08]; + let hash_b = [0x00, 0x00, 0xB1, 0xC4, 0xD5, 0xE6, 0xF7, 0x08]; // 10+ bits differ + let assertion = make_assertion_with_visual_hash(hash_b); + let query = QueryBuilder::new() + .visual_near("a3f2b1c4d5e6f708", 5) + .build(); + assert!(!query.matches(&assertion)); +} + +#[test] +fn test_visual_near_skips_assertions_without_hash() { + // Assertion has no visual_hash -> not matched + let assertion = make_assertion_without_visual_hash(); + let query = QueryBuilder::new() + .visual_near("a3f2b1c4d5e6f708", 8) + .build(); + assert!(!query.matches(&assertion)); +} + +#[test] +fn test_hamming_distance_zero() { + let hash = [0xFF; 8]; + assert_eq!(hamming_distance(&hash, &hash), 0); +} + +#[test] +fn test_hamming_distance_max() { + let a = [0x00; 8]; + let b = [0xFF; 8]; + assert_eq!(hamming_distance(&a, &b), 64); +} +``` + +### Integration Tests (`stemedb-api`) + +```rust +#[tokio::test] +async fn test_visual_query_api() { + let app = create_test_app().await; + + // Insert assertion with visual_hash + let resp = app.post("/v1/assertions") + .json(&json!({ + "subject": "STEP-1_Trial", + "predicate": "primary_endpoint", + "object": {"Number": 14.9}, + "visual_hash": "a3f2b1c4d5e6f708" + })) + .send().await; + assert_eq!(resp.status(), 201); + + // Query by visual similarity + let resp = app.get("/v1/query") + .query(&[ + ("visual_near", "a3f2b1c4d5e6f700"), // 3 bits different + ("visual_threshold", "8") + ]) + .send().await; + assert_eq!(resp.status(), 200); + + let results: Vec = resp.json().await; + assert_eq!(results.len(), 1); +} +``` + +--- + +## Performance Characteristics + +### MVP (Brute Force) + +| Operation | Complexity | Notes | +|-----------|------------|-------| +| Visual query | O(N) | Scans all assertions | +| Hamming distance | O(1) | 8 XORs + 8 popcounts | +| Per-assertion overhead | ~10 ns | Negligible | + +**Expected latency:** +- 10K assertions: ~100μs +- 100K assertions: ~1ms +- 1M assertions: ~10ms +- 10M assertions: ~100ms (needs index) + +### When to Worry + +If visual queries consistently exceed 100ms, it's time for Phase 3 indexing. + +--- + +## Future Directions (Based on Performance) + +### Phase 3a: BK-Tree Index + +**Trigger:** Visual queries exceed 50ms at p99. + +**Approach:** Build a BK-tree (Burkhard-Keller tree) optimized for hamming distance. + +```rust +struct BKTree { + root: Option>, +} + +struct BKNode { + hash: PHash, + assertion_id: Hash, + children: HashMap>, // distance -> child +} +``` + +**Benefits:** +- O(log N) average case for bounded threshold queries +- Well-suited for discrete metric spaces (hamming distance) + +**Storage:** `VIX:{hash_prefix}` keys in sled for persistence. + +### Phase 3b: VP-Tree Index + +**Trigger:** Need range queries with variable thresholds. + +**Approach:** Vantage-point tree for metric space search. + +**Benefits:** +- Better for continuous thresholds +- Can support "find K nearest" queries + +### Phase 3c: Locality-Sensitive Hashing (LSH) + +**Trigger:** Need sub-linear time for very large datasets (100M+ assertions). + +**Approach:** Hash pHashes into buckets where similar hashes collide. + +**Benefits:** +- O(1) average case +- Scales to billions of assertions + +**Tradeoffs:** +- Probabilistic (may miss some matches) +- Requires tuning hash functions + +### Phase 3d: Visual Clustering Dashboard + +**Trigger:** Users want "show me distinct visual fingerprints." + +**Approach:** Background job that clusters visual_hashes and maintains cluster centroids. + +``` +GET /v1/visual-clusters?subject=TechCorp +-> Returns: +{ + "clusters": [ + { "centroid": "a3f2b1c4d5e6f708", "count": 47, "representative_hash": "..." }, + { "centroid": "b4e3c2d5a6f70819", "count": 12, "representative_hash": "..." } + ] +} +``` + +### Phase 3e: Pre-Assertion Dedup Check + +**Trigger:** Ingestion workers want to avoid duplicates. + +**Approach:** Endpoint to check visual similarity before creating assertion. + +``` +GET /v1/assertions/visual-check?visual_hash=a3f2b1c4d5e6f708&threshold=8 +-> Returns existing assertion hashes if any match, empty otherwise +``` + +--- + +## Non-Goals (Explicit Scope Limits) + +1. **Not making visual_hash mandatory.** It remains optional. Assertions without visual_hash simply don't match visual queries. + +2. **Not building image processing.** Episteme doesn't compute pHashes. Clients compute them before asserting. + +3. **Not building a visual search UI.** This is query infrastructure. Apps build UIs on top. + +4. **Not optimizing for exact match.** Use `source_hash` for exact binary matching. `visual_hash` is for perceptual similarity. + +--- + +## Implementation Checklist + +### Core (`stemedb-query`) + +- [ ] Add `visual_near: Option` to `Query` struct +- [ ] Add `visual_threshold: Option` to `Query` struct (default: 8) +- [ ] Implement `hamming_distance(a: &[u8; 8], b: &[u8; 8]) -> u32` +- [ ] Implement hex parsing for pHash strings +- [ ] Add visual matching to `Query::matches()` +- [ ] Add `.visual_near(hash, threshold)` to `QueryBuilder` + +### API (`stemedb-api`) + +- [ ] Add `visual_near` query parameter to `QueryParams` DTO +- [ ] Add `visual_threshold` query parameter to `QueryParams` DTO +- [ ] Update OpenAPI spec with new parameters + +### SDK (`sdk/go/steme`) + +- [ ] Add `VisualNear(hash, threshold)` to `QueryBuilder` +- [ ] Add integration test for visual queries + +### Tests + +- [ ] `test_visual_near_exact_match` +- [ ] `test_visual_near_within_threshold` +- [ ] `test_visual_near_exceeds_threshold` +- [ ] `test_visual_near_skips_assertions_without_hash` +- [ ] `test_hamming_distance_zero` +- [ ] `test_hamming_distance_max` + +### Documentation + +- [ ] Add threshold guidance to SDK docs +- [ ] Add domain-specific recommendations to use-case docs +- [ ] Update `ai-lookup/services/query.md` with visual query info + +--- + +## Stakeholder Sign-Off + +Based on empathy interviews: + +| Persona | Concern | How MVP Addresses | +|---------|---------|-------------------| +| Research Agent | "Let me query by visual similarity" | Core feature | +| Human Supervisor | "O(N) is fine if Phase 3 is planned" | Future directions documented | +| Lead Orchestrator | "Don't mandate visual_hash" | Remains optional | +| On-Call SRE | "Keep API simple" | Single query param, sensible default | +| M&A Analyst | "Threshold 8-10 for screenshots" | Default 8, guidance for 10 | +| Consumer Health | "False positives are dangerous" | Domain guidance: threshold 4-5 | + +--- + +## Open Questions + +1. **Should we add `visual_hash` to `QueryAudit`?** When auditing "what did the agent query?", do we capture visual_near parameters? + +2. **Should visual queries combine with other filters?** Current spec: yes (AND with subject, predicate, etc.). Is this correct? + +3. **What's the actual distribution of visual_hash population?** If <1% of assertions have visual_hash, should we warn users? + +--- + +## References + +- [pHash paper](http://www.phash.org/docs/pubs/thesis_zauner.pdf) - Perceptual hashing algorithms +- [BK-tree](https://en.wikipedia.org/wiki/BK-tree) - Metric tree for discrete distances +- [VP-tree](https://en.wikipedia.org/wiki/Vantage-point_tree) - Metric tree for general metrics +- [LSH](https://en.wikipedia.org/wiki/Locality-sensitive_hashing) - Probabilistic nearest-neighbor diff --git a/position.md b/position.md new file mode 100644 index 0000000..5495bbd --- /dev/null +++ b/position.md @@ -0,0 +1,73 @@ +# StemeDB: Market Position & Thesis + +> **The Pitch:** The winners of the AI era won't just be the smartest models—it will be the infrastructure that makes them safe to use. +> **The Metaphor:** Google/OpenAI are building the **CPU** (Intelligence). We are building the **Hard Drive** (State). + +--- + +## 1. The Core Thesis: The "Amnesiac Genius" Problem + +We are witnessing a "Processor War." OpenAI, Google, and Anthropic are spending billions to build models with higher IQ. +* **The Result:** Agents that can reason brilliantly for 10 minutes. +* **The Flaw:** Once the context window closes, the reasoning vanishes. They are "Super-Geniuses with Amnesia." + +Enterprises cannot run critical operations (Finance, Law, Science) on ephemeral thought. They need **Durable Execution**. They need a system that remembers *why* a decision was made, *who* made it, and *what evidence* supported it. + +**StemeDB is the File System for the AI Scientist.** + +--- + +## 2. The Competitive Landscape: Why Us? + +Investors ask: *"Why won't Google or OpenAI just build this?"* +**Answer:** Because their business models and architectures prohibit it. + +### vs. Google Gemini (The Monolith) +* **Their Play:** "The Source Graph." Fuses AI with Google Drive/Docs. +* **The Flaw:** It is a **Walled Garden**. It only works if your data is in Google. +* **Our Moat:** **Neutrality.** Modern enterprises use a "Tower of Babel" stack (Salesforce, Notion, GitHub). Google will never optimize for data living in Microsoft or Atlassian silos. StemeDB is the "Switzerland of Memory"—model-agnostic and platform-neutral. + +### vs. OpenAI o3 (The Black Box) +* **Their Play:** "Internalized Chain of Thought." The model "thinks" before it answers. +* **The Flaw:** The reasoning is **Ephemeral & Opaque**. You cannot audit the thought process after the chat ends. +* **Our Moat:** **Auditability.** We sell "Signed Assertions." If an agent executes a trade, we provide the cryptographic proof of exactly which document it read. OpenAI provides the decision; we provide the compliance trail. + +### vs. Vector Databases (The Legacy) +* **Their Play:** "Semantic Search." Optimize for Cosine Similarity. +* **The Flaw:** **Context Pollution.** To a Vector DB, `Budget_Draft_v1` and `Budget_Final_v2` look 99% identical. It retrieves both, causing agents to hallucinate based on outdated data. +* **Our Moat:** **Validity.** We optimize for Truth, not Similarity. Our "Epoch" and "TrustRank" systems automatically filter out superseded or low-confidence data. + +--- + +## 3. The "Next Giant" Defense + +*"Won't Open Source developers (LangChain) or Search engines (Perplexity) build this?"* + +**No. They are solving different layers.** + +* **Open Source (LangChain/AutoGPT):** They are building the **Manager**. They focus on orchestration (spinning up 5 agents). They treat memory as a plugin, not a platform. +* **Perplexity:** They organize the **Web**. Their architecture is optimized for 200B public URLs. StemeDB organizes **Work**—private, forked realities ("What if we acquire Company X?") that must never touch a public index. + +--- + +## 4. The Product Strategy: "Invisible Infrastructure" + +We do not ask developers to "manage a database." We ask them to "annotate their work." + +1. **The Hook:** "Stop writing retry loops." + * Our SDK (`steme.BindJob`) automatically handles state recovery for long-running agents. The "Database" is just a side effect of keeping the agent alive. +2. **The Stickiness:** "The Un-Gaslightable Dashboard." + * Once a team sees a timeline of *exactly* when their agent hallucinated vs. when a human intervened, they cannot go back to black-box logs. +3. **The Flywheel:** "The Simulator." + * We convert their logs into training data. The more they use StemeDB, the smarter their custom agents become. + +--- + +## 5. Summary + +We are not fighting the Model War. We are selling shovels in the Gold Rush. +* Let OpenAI build the **Genius** (The Agent). +* Let Google build the **Office** (The Workspace). +* We will build the **Filing Cabinet** (The Truth). + +History shows that the System of Record (Oracle, Snowflake) is often more valuable than the Application Layer. diff --git a/roadmap.md b/roadmap.md index 7b28f78..73d93c3 100644 --- a/roadmap.md +++ b/roadmap.md @@ -1,22 +1,24 @@ # Episteme (StemeDB) Roadmap > **Goal:** Build the "Git for Truth" substrate for autonomous AI research. -> **Current Phase:** Phase 1 (The Spine) +> **Current Phase:** Phase 2.5 (Hardening) +> **Target Vertical:** BioTech/Pharma ("The Living Review") --- -## 📅 High-Level Timeline +## High-Level Timeline | Phase | Codename | Focus | Key Deliverable | | :--- | :--- | :--- | :--- | | **1** | **The Spine** | Storage & Safety | Append-only WAL + KV Store | | **2** | **The Lattice** | Indexing & Async | Materialized Views + Ballot Box | -| **3** | **The Cortex** | Branching & Vectors | SMT Backend + Semantic Search | -| **4** | **The Hive** | Trust & Learning | Dojo + TrustRank | +| **2.5** | **Hardening** | Camp 2 Fixes | MV staleness, epoch behavior, lens cleanup | +| **3** | **The Pilot** | Vertical Integration | Pharma Ingestion + Living Review Agent | +| **4** | **The Hive** | Trust & Learning | The Simulator + Super Curator | --- -## 🛠 Detailed Milestones +## Detailed Milestones ### Phase 1: The Spine (Foundation) *Goal: Securely ingest assertions and persist them without data loss.* @@ -47,56 +49,548 @@ - [x] **Basic Ingestor**: Background worker that tails WAL and writes to KV. - [x] Implement async loop reading from WAL. - [x] Write deserialized assertions, votes, and epochs to `sled`. - - [x] Content-addressed keys using BLAKE3 hash (`H:{hash}`, `V:{hash}`, `E:{hash}`). - - [x] Subject adjacency index (`S:{subject}`). -- [x] **Verification**: Write tests proving crash recovery (write -> crash -> restart -> read). - - [x] WAL-level recovery tests (6 tests in `stemedb-wal/src/recovery.rs`). - - [x] Full pipeline recovery tests (4 tests in `stemedb-ingest/src/worker.rs`). - - [x] Bug fix: Journal now seeks to end after reopening existing WAL file. + - [x] Ed25519 signature verification during ingestion. + - [x] Maintains S: and SP: indexes on ingest. + - [x] Persistent cursor/checkpoint (resumes from `__CURSOR__:ingest` in KV store). +- [x] **Verification**: Crash recovery tests (write -> crash -> restart -> read). + - [x] Single and multi-record crash recovery. + - [x] Multiple crash cycles tested. ### Phase 2: The Lattice (Connectivity) *Goal: Query data with sub-millisecond latency using Materialized Views.* -- [ ] **The Ballot Box**: Implement high-velocity vote ingestion. - - [ ] `VoteStore` trait and implementation. -- [ ] **Materializer**: Background worker for O(1) Read Performance. - - [ ] Aggregates Votes + TrustRank. - - [ ] Updates `MV:{Subject}:{Predicate}` with the winning Assertion. -- [ ] **The Meter**: Implement Economic Throttling (TAN). - - [ ] Middleware to track Token/Compute cost per Job. - - [ ] Reject requests exceeding `Value of Information`. -- [ ] **Agent Wallet**: Key management sidecar. - - [ ] Securely hold private keys. - - [ ] Auto-sign outgoing Assertions/Votes. -- [ ] **API Surface**: `axum` HTTP server. - - [ ] `POST /assert` -> Accepts JSON, writes to WAL, returns `JobID`. - - [ ] `POST /vote` -> High-throughput endpoint. - - [ ] `GET /query` -> Accepts Subject/Predicate/Lens, returns resolved Assertion. +- [x] **Lifecycle Schema**: Add `LifecycleStage` to Assertion. + - [x] Define enum: `Proposed`, `UnderReview`, `Approved`, `Deprecated`, `Rejected`. + - [x] Update `Assertion` struct and serialization tests. +- [x] **The Ballot Box**: Implement high-velocity vote ingestion. + - [x] `VoteStore` trait and implementation. + - [x] `VoteAwareConsensusLens` for real vote-based resolution. +- [x] **Index Infrastructure**: Compound indexes for O(1) queries. + - [x] `IndexStore` trait with S: and SP: indexes. + - [x] `QueryEngine` smart routing (SP -> S -> scan). +- [x] **Materializer**: Background worker for O(1) Read Performance. + - [x] `MaterializedView` type in `stemedb-core`. + - [x] `Materializer` worker in `stemedb-query` with `step()` and `run()`. + - [x] Aggregates Votes via `VoteAwareConsensusLens` (or any `AsyncLens`). + - [x] Updates `MV:{Subject}:{Predicate}` with the winning Assertion + metadata. + - [x] Event-driven mode via `run_notified()` with `tokio::sync::Notify`. + - [x] Fast-path MV lookup in `QueryEngine::try_fast_path()`. +- [x] **The Meter**: Implement Economic Throttling (TAN). + - [x] `QuotaStore` trait and `GenericQuotaStore` implementation. + - [x] Token Bucket algorithm with per-agent per-hour quotas. + - [x] `MeterLayer` tower middleware for request cost tracking. + - [x] Cost model: Assert=10, Vote=1, Query=5+lens, +1/KB payload. + - [x] `GET /v1/meter/quota` endpoint to check remaining quota. + - [x] `POST /v1/meter/quota/limit` admin endpoint to set custom limits. +- [x] **API Surface**: `axum` HTTP server with OpenAPI (utoipa). + - [x] `POST /v1/assert` -> Accepts JSON, writes to WAL. + - [x] `POST /v1/vote` -> High-throughput vote endpoint. + - [x] `POST /v1/epoch` -> Create epoch with optional supersession. + - [x] `GET /v1/query` -> Subject/Predicate/Lens/Lifecycle/Epoch filtering. + - [x] `GET /v1/health` -> Health check with assertion count. + - [x] `GET /swagger-ui` -> Interactive API docs. + - [x] 5 lens types available: Recency, Consensus, Authority, VoteAwareConsensus, TrustAwareAuthority. +- [x] **Query Audit**: Log every read with provenance. + - [x] Define `QueryAudit` struct: query_id, agent_id, timestamp, params, result_hash, contributing_assertions. + - [x] Storage at `AUD:{query_id}` with agent index at `AUDA:{agent_id}:{timestamp}:{query_id}`. + - [x] `GET /v1/audit/queries` -> Returns history of agent decisions. + - [x] `GET /v1/audit/query/{id}` -> Full reasoning trace for a single query. + - [x] Auto-logging on every query via `X-Agent-Id` header. -### Phase 3: The Cortex (Reasoning) -*Goal: Enable semantic search and "What If" scenarios.* +### Phase 2.5: Hardening (Camp 2 Fixes) +*Goal: Close the gaps between "built" and "works right." Every item here addresses a feature that exists but doesn't fully deliver on its promise.* -- [ ] **Sparse Merkle Backend**: Implement SMT for O(1) branch creation. -- [ ] **Branching Core**: Implement Overlay Graph logic. -- [ ] **Vector Storage**: Integrate `hnsw-rs` or `lance`. -- [ ] **Semantic Search**: Implement k-NN query support. +- [x] **2.1 MV Staleness Detection**: Make the fast-path aware of stale materialized views. + - **Status:** ✅ COMPLETE + - **Implementation:** + - [x] Added `max_stale: Option` to `Query` struct in `crates/stemedb-query/src/query.rs`. + - [x] Added `.max_stale(secs)` builder method to `QueryBuilder`. + - [x] In `try_fast_path()`: if `query.max_stale` is set and MV age exceeds threshold, falls through to slow path with `debug!` log. + - [x] Added `max_stale` to API `QueryParams` DTO in `crates/stemedb-api/src/dto.rs`. + - [x] Wired through query handler in `crates/stemedb-api/src/handlers/query.rs`. + - **Tests:** + - [x] `test_fast_path_stale_view_falls_back`: MV 1000 seconds old, `max_stale = 60` → slow path used. + - [x] `test_fast_path_fresh_view_used`: Fresh MV, `max_stale = 300` → fast path used. + - [x] `test_fast_path_no_max_stale_always_uses_mv`: No `max_stale` → any MV age accepted (backward compatible). + - [x] `test_fast_path_max_stale_zero_rejects_old_mv`: `max_stale = 0`, MV 1 second old → slow path. + - [x] `test_fast_path_max_stale_zero_accepts_brand_new_mv`: `max_stale = 0`, brand new MV → fast path. + +- [x] **2.2 AuthorityLens -> ConfidenceLens Rename**: Eliminate the misleading name. + - **Problem:** `AuthorityLens` selects by `confidence` field, not by agent reputation. `TrustAwareAuthorityLens` is the real authority lens. The name creates confusion about what "Authority" means. + - **Solution implemented:** + - [x] Renamed `authority.rs` → `confidence.rs`, `AuthorityLens` → `ConfidenceLens` + - [x] Added `LensDto::Confidence` for the confidence-field selector + - [x] Changed `LensDto::Authority` to route to `TrustAwareAuthorityLens` (the real authority lens) + - [x] Updated query handler routing + - [x] Updated ai-lookup/services/lens.md and skill documentation + +- [x] **2.3 EpochAwareLens**: Give epoch supersession runtime behavior. + - **Status:** ✅ COMPLETE + - **Implementation:** + - [x] `EpochAwareLens` in `crates/stemedb-lens/src/epoch_aware.rs` + - [x] Decorator pattern wrapping any inner lens (default: RecencyLens) + - [x] Walks supersession chain from `E:{epoch_id}` keys + - [x] Cycle detection + max depth guard (100) + - [x] Fail-open on missing epochs + - [x] `LensDto::EpochAware` added to API + - [x] 11 tests: excludes_superseded, chain_supersession, no_epochs_passes_all, missing_epoch_includes, cycle_detection, consensus_lens_inner, mixed_epochs, etc. + - [x] Documentation updated in `ai-lookup/services/lens.md` + - **Known Limitation:** Filtering only occurs when assertions from the superseding epoch are present in candidates. If all candidates are from old epoch (no new epoch assertions), they pass through (fail-open behavior). + +- [ ] **2.4 Visual Hash Query Support**: Make the stored `visual_hash` queryable. + - **Problem:** `visual_hash: Option` exists on `Assertion` and is stored/returned by the API, but there is no way to query by visual similarity. The field is write-only from a query perspective. + - **Current state:** `PHash` is `[u8; 8]` (perceptual hash). Stored on assertions. API accepts/returns it. No query parameter. No similarity computation. + - [ ] Add `visual_near: Option` (hex-encoded pHash) and `visual_threshold: Option` (max hamming distance, default: 8) to `Query` struct. + - [ ] Add `.visual_near(hash, threshold)` to `QueryBuilder`. + - [ ] In `Query::matches()`: if `visual_near` is set and assertion has `visual_hash`, compute hamming distance (XOR + popcount on the 8 bytes). If distance <= threshold, match. If assertion has no `visual_hash`, don't match. + - [ ] Add `visual_near` and `visual_threshold` to API `QueryParams` DTO. + - [ ] Implement `hamming_distance(a: &[u8; 8], b: &[u8; 8]) -> u32` utility function. + - [ ] Tests: + - [ ] `test_visual_near_exact_match`: Same hash, threshold 0. Matches. + - [ ] `test_visual_near_within_threshold`: Hashes differ by 3 bits, threshold 5. Matches. + - [ ] `test_visual_near_exceeds_threshold`: Hashes differ by 10 bits, threshold 5. No match. + - [ ] `test_visual_near_skips_assertions_without_hash`: Assertion has no visual_hash. Not matched. + - [ ] **Note:** This is a brute-force scan approach (O(N) with hamming distance check). A proper VP-tree or BK-tree index is Phase 3. This gives immediate queryability. + +- [ ] **2.5 Vector Field**: No changes needed. Already roadmapped for Phase 3. + - **Current state:** `vector: Option>` on `Assertion`. Stored and returned by API. No index, no search. + - **Phase 3 plan:** Integrate `hnsw-rs` or `lance` for k-NN search. + - **No Phase 2.5 work required.** The field scaffolding is correct. + +- [ ] **2.6 E2E Integration Test (Write -> Materialize -> Read)**: Prove the full pipeline works end-to-end. + - **Problem:** The IngestWorker, Materializer, and QueryEngine have been tested in isolation. The Notify integration between IngestWorker and Materializer is tested with a single notification. No test wires all three components together to verify the full write-materialize-read loop. + - **Current state:** IngestWorker has `with_notify(Arc)` (`worker.rs`). Materializer has `run_notified(Arc, Duration)` (`materializer.rs`). QueryEngine has `try_fast_path()` (`engine.rs`). Never tested together. + - [ ] Create integration test in `crates/stemedb-query/tests/e2e_pipeline.rs`: + - [ ] Setup: Create temp WAL + SledStore + VoteStore + TrustRankStore. + - [ ] Wire: IngestWorker with `with_notify(notify)`, Materializer with `run_notified(notify)`, QueryEngine with same store. + - [ ] Test steps: + 1. Write a signed assertion to WAL. + 2. Run IngestWorker.step() -> verifies assertion ingested to KV. + 3. Verify IngestWorker triggered Notify. + 4. Run Materializer.step() -> verifies MV written. + 5. Execute QueryEngine.execute() with subject+predicate -> verifies fast-path returns MV winner. + - [ ] Variant: Write 2 competing assertions, add votes favoring one, run pipeline, verify correct winner in MV. + - [ ] Variant: Write assertion, materialize, write new assertion with higher timestamp, re-materialize, verify MV updated, verify query returns new winner. + - [ ] Add `stemedb-wal` and `stemedb-ingest` as dev-dependencies in `stemedb-query/Cargo.toml`. + +### Phase 3: The Pilot (BioTech/Pharma) +*Goal: Prove value in the "High-Liability" beachhead. Close every Camp 4 gap that blocks a credible demo.* + +#### 3A. Schema Expansion (Prerequisite for everything below) + +- [x] **3A.1 Source-Class Field**: Add `source_class: SourceClass` to Assertion. + - **Status:** ✅ COMPLETE + - **Implementation:** + - [x] `SourceClass` enum in `crates/stemedb-core/src/types.rs` (lines 68-88). + - [x] 6-tier system: `Regulatory` (0), `Clinical` (1), `Observational` (2), `Expert` (3), `Community` (4), `Anecdotal` (5). + - [x] `tier()` method returns tier number for ordering. + - [x] `default_decay_days()` method for tier-specific confidence decay. + - [x] `authority_weight()` method for conflict resolution weighting. + - [x] Field on `Assertion` struct at line 152. + - [x] Full serialization and indexing support. + +- [ ] **3A.2 Conflict Score on Resolution**: Add `conflict_score: f32` to Resolution. + - **Problem:** All 4 use cases reference `conflict_score` in query responses. `Resolution` has `resolution_confidence` but no conflict metric. Without a conflict score, the "disagreement is the information" thesis has no numeric representation. + - **Current state:** `Resolution` at `traits.rs:10-20` has `winner`, `candidates_count`, `resolution_confidence`. No variance computation. + - [ ] Add field to `Resolution` in `crates/stemedb-lens/src/traits.rs:10`: + ```rust + /// Degree of disagreement among candidates (0.0 = full agreement, 1.0 = max conflict). + /// Computed as normalized variance of candidate confidence values. + pub conflict_score: f32, + ``` + - [ ] Update `Resolution::empty()` at `traits.rs:24`: set `conflict_score: 0.0`. + - [ ] Update `Resolution::with_winner()` at `traits.rs:29`: accept `conflict_score` parameter. + - [ ] Add utility function `compute_conflict_score(candidates: &[Assertion]) -> f32`: + - Compute mean confidence: `mean = sum(c.confidence) / N`. + - Compute variance: `var = sum((c.confidence - mean)^2) / N`. + - Normalize to [0.0, 1.0]: `conflict = (4.0 * var).min(1.0)` (variance of [0,1] range has max 0.25, so 4x normalizes). + - Edge cases: 0 or 1 candidates -> 0.0. + - [ ] Update every `Lens::resolve()` and `AsyncLens::resolve_async()` implementation to call `compute_conflict_score()` and pass it to `Resolution::with_winner()`: + - `crates/stemedb-lens/src/recency.rs` + - `crates/stemedb-lens/src/consensus.rs` + - `crates/stemedb-lens/src/authority.rs` (or `confidence.rs` after rename) + - `crates/stemedb-lens/src/vote_aware_consensus.rs` + - `crates/stemedb-lens/src/trust_aware_authority.rs` + - [ ] Add `conflict_score: f32` to `MaterializedView` in `crates/stemedb-core/src/types.rs:143`. + - [ ] Update `Materializer::materialize_pair()` at `materializer.rs:164` to write `conflict_score` from resolution. + - [ ] Add `conflict_score` to `QueryResponse` DTO (or a new `ResolutionMeta` sub-object) in `crates/stemedb-api/src/dto.rs`. + - [ ] Wire `conflict_score` through in the query handler's `apply_lens()` at `handlers/query.rs:111`. + - [ ] Tests: + - [ ] `test_conflict_score_zero_for_agreement`: 3 candidates all confidence 0.9. Score near 0.0. + - [ ] `test_conflict_score_high_for_disagreement`: Candidates at 0.1, 0.5, 0.9. Score > 0.5. + - [ ] `test_conflict_score_zero_for_single`: 1 candidate. Score = 0.0. + - [ ] `test_conflict_score_on_materialized_view`: MV stores conflict_score after materialization. + +- [ ] **3A.3 Rich Source Metadata**: Add structured provenance beyond `source_hash`. + - **Problem:** `Assertion` has `source_hash: Hash` (a 32-byte hash) but no structured metadata. Consumer Health use case shows POST bodies with `journal`, `DOI`, `sample_size`, `subreddit`, `upvotes`. Without this, assertions are opaque about their provenance. + - **Current state:** `source_hash: Hash` at `types.rs:64`. No metadata field. API accepts/returns only the hash. + - [ ] Add field to `Assertion` in `crates/stemedb-core/src/types.rs:65` (after `source_hash`): + ```rust + /// Structured source metadata as a JSON-encoded byte string. + /// Schema is domain-specific (journal info, social metrics, etc.). + pub source_metadata: Option>, + ``` + - [ ] Use `Vec` (not `String`) for rkyv zero-copy compatibility. Callers encode/decode JSON on their side. + - [ ] Add `source_metadata: Option>` to `AssertionBuilder`. Add `.source_metadata_json(json: &str)` builder method that stores `json.as_bytes().to_vec()`. + - [ ] Add `source_metadata: Option` to `CreateAssertionRequest` DTO (JSON string in API, converted to bytes internally). + - [ ] Add `source_metadata: Option` to `AssertionResponse` DTO (bytes converted to JSON string). + - [ ] Wire through create handler and query handler. + - [ ] Tests: + - [ ] Serialization roundtrip with metadata present and absent. + - [ ] API roundtrip: POST with metadata JSON, GET returns same JSON. + - **Note:** Metadata is stored but NOT indexed in Phase 3. Indexing individual metadata fields is Phase 4+. + +#### 3B. Time & Decay (Core Query Features) + +- [ ] **3B.1 Time-Travel Engine**: `as_of` parameter for historical queries. + - **Problem:** All 4 use cases reference `as_of` for historical state. "What was the consensus when I made my decision?" The append-only model stores all history, but there's no way to query a past state. + - **Current state:** `Query` at `query.rs:14-29` has no `as_of` field. `try_fast_path()` returns current MV regardless. + - [ ] Add `as_of: Option` to `Query` struct in `crates/stemedb-query/src/query.rs:14`. + - [ ] Add `.as_of(timestamp: u64)` to `QueryBuilder`. + - [ ] In `Query::matches()` at `query.rs:43`: if `as_of` is `Some(ts)`, check `assertion.timestamp <= ts`. Assertions created after `as_of` are excluded. + - [ ] In `QueryEngine::execute()` at `engine.rs:47`: if `query.as_of` is set, **skip the fast path entirely** (MVs reflect current state, not historical). Add early check before the `try_fast_path` call: + ```rust + if query.as_of.is_none() { + if let (Some(subject), Some(predicate)) = (&query.subject, &query.predicate) { + if let Some(result) = self.try_fast_path(subject, predicate, query).await? { + return Ok(result); + } + } + } + ``` + - [ ] Add `as_of: Option` to `QueryParams` DTO in `crates/stemedb-api/src/dto.rs:102`. + - [ ] Wire in query handler. + - [ ] Tests: + - [ ] `test_as_of_excludes_future_assertions`: 3 assertions at t=1000, t=2000, t=3000. Query `as_of=2500`. Returns only first 2. + - [ ] `test_as_of_bypasses_fast_path`: MV exists, but `as_of` is set. Slow path used, MV ignored. + - [ ] `test_as_of_none_uses_fast_path`: Normal query still uses fast path (backwards-compatible). + - [ ] `test_as_of_with_lens`: Time-travel + lens = resolve only among pre-as_of candidates. + +- [ ] **3B.2 Semantic Decay**: Confidence Half-Life at query time. + - **Problem:** Medical knowledge decays at different rates. A Reddit post from 2022 shouldn't compete equally with a 2024 RCT. No assertion-level decay exists. TrustRank has agent-level decay but not assertion-level. + - **Current state:** `TrustRank.apply_decay()` at `trust_rank_store.rs` does agent decay. No assertion decay. No `decay` query parameter. + - [ ] Add `decay_halflife: Option` to `Query` struct (seconds). Represents how quickly old assertions lose effective confidence. + - [ ] Add `.decay_halflife(seconds: u64)` to `QueryBuilder`. + - [ ] Add `decay_halflife` to `QueryParams` DTO. + - [ ] Implementation strategy: **Apply decay in QueryEngine before passing to lens.** In `execute()`, after fetching and filtering candidates, if `decay_halflife` is set: + 1. Get current time (or `as_of` if set). + 2. For each candidate, compute `age = now - assertion.timestamp`. + 3. Compute `effective_confidence = confidence * 2_f32.powf(-(age as f32) / (halflife as f32))`. + 4. Clone the assertion with the decayed confidence. + 5. Pass decayed candidates to the lens. + - [ ] Add helper `apply_decay(assertions: &[Assertion], halflife: u64, now: u64) -> Vec` in a new `crates/stemedb-query/src/decay.rs` module. + - [ ] **Source-class-aware decay** (Phase 3 stretch): If assertion has `source_class`, use per-tier half-lives from `SourceClass::default_decay_days()`. This is already implemented on the enum. + - [ ] Tests: + - [ ] `test_decay_reduces_old_assertion_confidence`: Assertion 1yr old, halflife 1yr. Effective confidence ~= original * 0.5. + - [ ] `test_decay_preserves_fresh_assertions`: Assertion 1hr old, halflife 1yr. Effective confidence ~= original. + - [ ] `test_decay_interacts_with_lens`: Two assertions, older has higher base confidence but after decay, newer wins via RecencyLens. + - [ ] `test_source_aware_decay`: Tier 0 doesn't decay. Tier 5 decays rapidly. + +#### 3C. New Lenses + +- [x] **3C.1 Skeptic Lens**: Surface disagreement, not winners. ✅ **COMPLETED** + - **Status:** ✅ COMPLETE + - **Implementation:** + - [x] `crates/stemedb-lens/src/skeptic.rs` - Full implementation. + - [x] `AnalysisLens` trait for lenses that analyze conflict instead of resolving it. + - [x] `SkepticLens` uses normalized Shannon entropy for conflict scoring. + - [x] Returns `ConflictAnalysis` with: + - `conflict_score: f32` (0.0 = unanimous, 1.0 = chaos) + - `status: ResolutionStatus` (Unanimous, Agreed, Contested) + - `claims: Vec` - all claims ranked by weight + - [x] `SkepticResolver` + `SkepticView` in `stemedb-query/src/skeptic.rs`. + - [x] `GET /v1/skeptic?subject=X&predicate=Y` API endpoint. + - [x] Core types in `stemedb-core/src/types.rs`: + - `ResolutionStatus` enum + - `ConflictAnalysis` struct + - `ClaimSummary`, `SourceSummary`, `AgentSummary` + - [x] Comprehensive test coverage (21 test cases). + +- [ ] **3C.2 Layered Consensus Lens**: Per-source-class consensus. + - **Problem:** Current lenses return a single winner. The Consumer Health use case needs per-tier consensus: "What does Tier 0 say? What does Tier 1 say? What does Tier 5 say?" This is the core differentiator. + - **Depends on:** Source-Class Field (3A.1) ✅ COMPLETE. + - [ ] New file: `crates/stemedb-lens/src/layered_consensus.rs`. + - [ ] New type in `crates/stemedb-lens/src/traits.rs`: + ```rust + /// Per-tier resolution result. + pub struct TierResolution { + pub tier: u8, + pub winner: Option, + pub candidates_count: usize, + pub conflict_score: f32, + } + + /// Multi-tier resolution result. + pub struct LayeredResolution { + /// Per-tier consensus results, ordered by tier (0 = highest authority). + pub tiers: Vec, + /// Overall winner (highest-tier with a winner). + pub overall_winner: Option, + /// Overall conflict score (cross-tier disagreement). + pub overall_conflict_score: f32, + } + ``` + - [ ] `LayeredConsensusLens` implements a new `LayeredLens` trait: + ```rust + pub trait LayeredLens: Send + Sync { + fn resolve_layered(&self, candidates: &[Assertion]) -> LayeredResolution; + fn name(&self) -> &'static str; + } + ``` + - [ ] `resolve_layered()` logic: + 1. Group candidates by `source_class` (use `SourceClass::tier()` method). + 2. For each tier group, run `ConsensusLens::resolve()` to get within-tier winner. + 3. Compute per-tier `conflict_score`. + 4. Overall winner = winner from the highest-authority tier that has candidates (lowest tier number). + 5. Overall conflict_score = cross-tier disagreement (do tier winners agree on the same object value?). + - [ ] Also implement standard `Lens` trait on `LayeredConsensusLens` to maintain compatibility: `resolve()` returns `overall_winner` as a regular `Resolution`. The richer `LayeredResolution` is accessible via `resolve_layered()`. + - [ ] Add `LayeredConsensus` to `LensDto` enum. + - [ ] New API response type: `LayeredQueryResponse` with per-tier results. Wire as a variant in the query handler when `lens=LayeredConsensus`. + - [ ] Export from `crates/stemedb-lens/src/lib.rs`. + - [ ] Tests: + - [ ] `test_layered_single_tier`: All candidates same source_class. Returns one tier result. + - [ ] `test_layered_multi_tier_agreement`: Tier 0 and Tier 5 agree on same object. Low cross-tier conflict. + - [ ] `test_layered_multi_tier_disagreement`: Tier 1 says "safe", Tier 5 says "dangerous". High cross-tier conflict. Overall winner from Tier 1. + - [ ] `test_layered_overall_winner_from_highest_authority`: Tier 0 present -> its winner is overall winner even if Tier 5 has 1000x more assertions. + +- [ ] **3C.3 Constraints Lens**: Pre-flight check for must_use/forbidden. + - **Problem:** Agile Agent Team use case needs `lens=constraints` returning `{ must_use: "axios", forbidden: "requests" }`. Central to "persistent learning" — agents query constraints before acting. + - [ ] New file: `crates/stemedb-lens/src/constraints.rs`. + - [ ] Design: Not a traditional lens (doesn't pick one winner from candidates). Instead, it categorizes candidates by predicate pattern: + - Assertions with predicate matching `must_use:*` -> must_use list. + - Assertions with predicate matching `forbidden:*` -> forbidden list. + - Assertions with predicate matching `prefer:*` -> prefer list. + - [ ] Implements `Lens` trait for compatibility: `resolve()` returns the highest-confidence `must_use` assertion as the "winner" (or `forbidden` if no must_use exists). The richer result is accessible via a dedicated method. + - [ ] Add dedicated `resolve_constraints()` method: + ```rust + pub struct ConstraintSet { + pub must_use: Vec, + pub forbidden: Vec, + pub prefer: Vec, + } + + impl ConstraintsLens { + pub fn resolve_constraints(&self, candidates: &[Assertion]) -> ConstraintSet { ... } + } + ``` + - [ ] Add `Constraints` to `LensDto` enum. + - [ ] New API response type: `ConstraintResponse` with categorized assertions. + - [ ] Export from `crates/stemedb-lens/src/lib.rs`. + - [ ] Tests: + - [ ] `test_constraints_categorizes_by_predicate`: Mixed predicates sorted into must_use/forbidden/prefer. + - [ ] `test_constraints_empty_categories`: No must_use predicates -> empty must_use list. + - [ ] `test_constraints_lens_trait_picks_must_use_winner`: Standard `resolve()` returns highest-confidence must_use. + - [ ] `test_constraints_non_constraint_predicates_ignored`: Regular predicates not categorized. + +#### 3D. Epoch Enhancement + +- [ ] **3D.1 Epoch Cascade Logic** (enhancement of Phase 2.5 EpochAwareLens): + - **Problem:** Phase 2.5 EpochAwareLens walks the `supersedes` chain at query time by reading `E:` keys. This is O(chain_length) per query. For long supersession chains, this is expensive. + - **Depends on:** Phase 2.5 EpochAwareLens (basic version). + - [ ] In `IngestWorker::process_epoch()` at `crates/stemedb-ingest/src/worker.rs`: + 1. When an epoch with `supersedes = Some(old_epoch_id)` is ingested, write a marker key `SUPERSEDED:{old_epoch_id}` with the new epoch ID as value. + 2. Walk the chain: if old_epoch itself superseded another epoch, write `SUPERSEDED:{grandparent_id}` too (transitive closure). + - [ ] Update `EpochAwareLens` to check `SUPERSEDED:{epoch_id}` keys (O(1) lookup per candidate) instead of walking the chain at query time. + - [ ] Tests: + - [ ] `test_cascade_writes_superseded_marker`: Ingest epoch B superseding A. Verify `SUPERSEDED:A` key exists. + - [ ] `test_cascade_transitive`: A supersedes B, B supersedes C. Verify both `SUPERSEDED:B` and `SUPERSEDED:C` exist. + - [ ] `test_epoch_aware_uses_marker`: Query with EpochAwareLens uses marker key, not chain walk. + +#### 3E. Similarity Search + +- [ ] **3E.1 Vector Search**: Semantic k-NN queries via embeddings. + - **Current state:** `vector: Option>` on Assertion. Stored, returned by API. No index, no search. + - [ ] Add `hnsw-rs` (or `lance`) as a dependency in `stemedb-storage/Cargo.toml`. + - [ ] New module: `crates/stemedb-storage/src/vector_index.rs`. + - [ ] `VectorIndex` trait: `insert(hash: Hash, vector: &[f32])`, `search(query: &[f32], k: usize) -> Vec<(Hash, f32)>`. + - [ ] Implementation backed by HNSW graph stored alongside KV data. + - [ ] IngestWorker: if assertion has `vector`, insert into vector index after KV write. + - [ ] Add `vector_near: Option>` and `k: Option` to `Query` struct and API `QueryParams`. + - [ ] QueryEngine: if `vector_near` is set, use vector index for candidate retrieval instead of SP/S index. + - [ ] Tests: insert 100 vectors, query nearest 5, verify correct neighbors. + +- [ ] **3E.2 Visual Hash Index**: VP-tree or BK-tree for O(log N) visual similarity. + - **Current state:** Phase 2.5 adds brute-force hamming scan. This replaces it with an indexed approach. + - [ ] New module: `crates/stemedb-storage/src/visual_index.rs`. + - [ ] BK-tree implementation over hamming distance on `PHash` ([u8; 8]). + - [ ] IngestWorker: if assertion has `visual_hash`, insert into BK-tree. + - [ ] QueryEngine: if `visual_near` is set, use BK-tree for O(log N) candidate retrieval instead of brute-force scan. + - [ ] Tests: insert 1000 assertions with visual hashes, query similar, verify correct matches within threshold. + +#### 3F. Provenance + +- [ ] **3F.1 Citation Recall Benchmarking**: Verify 100% provenance tracking. + - [ ] Benchmark: for every assertion in the store, verify `source_hash` resolves to a retrievable source document (or at minimum, the hash is non-zero and unique). + - [ ] Add `GET /v1/provenance/{hash}` endpoint that looks up source by hash. + - [ ] Add `POST /v1/source` endpoint to store source documents by content hash. + - [ ] Source storage at `SRC:{blake3_hash}` keys. + +#### 3G. API Cleanup + +- [ ] **3G.1 Document epoch supersession via existing endpoint**: No new `/epoch/supersede` endpoint needed. + - **Current state:** `POST /v1/epoch` already accepts `supersedes` field. Use cases show `POST /epoch/supersede` as if it's a separate endpoint. + - [ ] Update use case docs (consumer-health-intelligence.md, glp1-living-review.md) to use `POST /v1/epoch` with `supersedes` field. + - [ ] Add OpenAPI examples showing the supersession flow. + - **No code change.** Documentation fix only. ### Phase 4: The Hive (Trust & Scale) -*Goal: Turn the database into a training engine.* +*Goal: Change tracking, metadata indexing, and the database primitives for training pipelines.* -- [ ] **The Dojo**: Training Data Pipeline. - - [ ] **Post-Mortem Exporter**: Query `Lens::Skeptic` failures -> Negative Samples. - - [ ] **Golden Path Generator**: Merge events -> Positive Samples. -- [ ] **TrustRank Engine**: Background "Gardener" process. - - [ ] Implement Back-Propagation logic for agent reputation. - - [ ] **Confidence Half-Life**: Implement decay calculation engine. +- [x] **TrustRank Engine**: Foundation for trust-based resolution. + - [x] `TrustRankStore` for per-agent reputation storage. + - [x] `TrustAwareAuthorityLens` for reputation-weighted resolution. + - [x] **Confidence Half-Life**: Implement decay calculation engine. + - [x] Learning loop: `record_outcome()` for accuracy tracking. + +- [ ] **4.1 "Since" Parameter**: Change tracking for returning consumers. + - **Problem:** Consumer Health shows `GET /query?since=2023-10-01` returning `changes_since_query` with dated change entries. The "returning consumer" story: "What changed since I last looked?" + - **Depends on:** Time-Travel (3B.1) and Materializer. + - [ ] Add `since: Option` to `Query` struct and `QueryBuilder` in `crates/stemedb-query/src/query.rs`. + - [ ] Add `since` to `QueryParams` DTO. + - [ ] **MV Changelog**: Track when materialized views change. + - [ ] New key pattern: `MVC:{subject}:{predicate}:{timestamp}` storing the previous winner hash and new winner hash. + - [ ] In `Materializer::materialize_pair()` at `materializer.rs:164`: before overwriting MV, read the existing MV. If the winner changed (different assertion hash), write a changelog entry. + - [ ] In QueryEngine: if `since` is set, scan `MVC:{subject}:{predicate}:*` for entries with timestamp > since. Return these as a `changes_since` list alongside the normal query result. + - [ ] New response field on `QueryResponse`: + ```rust + pub struct ChangeEntry { + pub timestamp: u64, + pub previous_winner_hash: Option, + pub new_winner_hash: String, + } + ``` + Add `changes_since: Option>` to `QueryResponse` DTO. + - [ ] Tests: + - [ ] `test_since_returns_changes`: Materialize, change winner, re-materialize. Query with `since` returns the change. + - [ ] `test_since_no_changes`: No MV changes since timestamp. Empty changes list. + - [ ] `test_since_multiple_changes`: 3 winner changes over time. All returned in order. + +- [ ] **4.2 Source Metadata Indexing** (extension of 3A.3): Index key metadata fields. + - **Problem:** Phase 3 stores `source_metadata` as an opaque blob. Phase 4 makes key fields queryable. + - **Depends on:** Rich Source Metadata (3A.3). + - [ ] Define a set of indexed metadata keys: `journal`, `doi`, `platform`, `study_design`. + - [ ] New key pattern: `SM:{field}:{value}:{assertion_hash}` for metadata field indexes. + - [ ] IngestWorker: on ingestion, if `source_metadata` is present, parse JSON, extract indexed fields, write index entries. + - [ ] Add metadata field filters to `QueryParams` (e.g., `?source_journal=NEJM`). + - [ ] Tests: store assertions with metadata, query by journal name, verify correct filtering. + +- [ ] **4.3 Batch TrustRank Decay API**: Expose scheduled decay for external orchestration. + - **Current state:** `decay_all_trust_ranks()` exists on TrustRankStore. No API endpoint. + - [ ] Add `POST /v1/admin/decay-trust-ranks` endpoint. + - [ ] Accepts `now: u64` parameter (or uses current time). + - [ ] Returns count of decayed agents and summary stats. + - **Note:** The Gardener (Camp 5.2, app layer) calls this endpoint on a schedule. The database just exposes the primitive. + +> **Note:** The following items were reclassified as **Application Layer** responsibilities (see `tmp/ambition-vs-reality.md`, Camp 5). They are not Episteme database features. They consume the Episteme API and are built by integrators or vertical-specific teams. +> +> - **The Simulator** (Training Data Pipeline) -> Camp 5.3 +> - **The Super Curator** (Reviewer Agent swarm) -> Camp 5.4 +> - **Background Gardener** (Cluster detection, signal processing) -> Camp 5.2 +> - **Agent Wallet** (Key management sidecar) -> Camp 5.1 --- -## 🚦 Tracking +## Tracking ### Active Tasks -* **Phase 1 Complete!** Ready to start Phase 2 (The Lattice). +* [ ] **Phase 2.5 Hardening**: Camp 2 fixes (~~staleness~~, epoch behavior, lens rename, visual query, E2E test). + +### Next Up (Phase 3 sequencing) +* [ ] **3A.2 Conflict Score**: Add to Resolution. Propagate through all lenses. +* [ ] **3A.3 Rich Source Metadata**: Structured provenance field. +* [ ] **3B.1 Time-Travel**: `as_of` parameter. Unblocks all 4 use cases. +* [ ] **3C.2 Layered Consensus Lens**: Per-tier resolution (now unblocked by 3A.1). + +### Recently Completed +* [x] **SkepticLens + SkepticView** (3C.1): "Trust but Verify" conflict analysis that surfaces all claims with conflict scores. + * `AnalysisLens` trait for lenses that map conflict instead of resolving it. + * `SkepticLens` using normalized Shannon entropy for conflict scoring. + * `SkepticResolver` + `SkepticView` in stemedb-query. + * `GET /v1/skeptic?subject=X&predicate=Y` API endpoint. + * Types: `ResolutionStatus`, `ConflictAnalysis`, `ClaimSummary`, `SourceSummary`, `AgentSummary`. +* [x] **Source-Class Field** (3A.1): 6-tier `SourceClass` enum with authority weighting and decay rates. + * `SourceClass` enum: Regulatory, Clinical, Observational, Expert, Community, Anecdotal. + * `tier()`, `default_decay_days()`, `authority_weight()` methods. + * Field on Assertion struct with full serialization support. +* [x] **The Meter**: Token bucket quota system with MeterLayer middleware (10K tokens/agent/hour). +* [x] **Query Audit Trail**: Every query logged with provenance at `AUD:{query_id}`. `X-Agent-Id` header for attribution. +* [x] **Event-Driven Materialization**: `run_notified()` + IngestWorker Notify integration. +* [x] **Fast-Path MV Lookup**: `QueryEngine::try_fast_path()` for O(1) reads. +* [x] **Materializer**: Background worker for O(1) MV reads via `AsyncLens`. +* [x] **VoteAwareConsensusLens**: Real vote-based consensus resolution. +* [x] **Compound SP Index**: O(1) subject+predicate lookups. +* [x] **TrustRank System**: Agent reputation with decay and learning loop. +* [x] **API Surface**: axum HTTP server with 7 endpoints + OpenAPI docs. ### Blockers * None. + +--- + +## Dependency Graph + +``` +Phase 2.5 (Hardening) Phase 3 (The Pilot) Phase 4 (The Hive) +======================== ======================== ================== + +[2.1 MV Staleness] ---------> [3B.1 Time-Travel] -----+ + | | +[2.2 Confidence Rename] -----> (API clarity for all) +----------> [4.1 "Since" Param] + | +[2.3 EpochAwareLens] --------> [3D.1 Epoch Cascade] ---|----------> Invalidation Cascades pillar + | +[2.4 Visual Hash Query] -----> [3E.2 Visual Hash Index] | + | +[2.6 E2E Integration] -------> (pipeline confidence) | + | + [3A.1 Source-Class] ✅ --+----------> [3C.2 Layered Consensus] + | [3B.2 Source-Aware Decay] + +-----------------------------[4.2 Metadata Indexing] + | + [3A.2 Conflict Score] ---> (enhance Resolution) + | + [3A.3 Source Metadata] ---> [4.2 Metadata Indexing] + | + [3C.1 Skeptic Lens] ✅ (standalone, COMPLETE) + [3C.3 Constraints Lens] (standalone) + [3E.1 Vector Search] (standalone) + [3F.1 Citation Recall] (standalone) +``` + +### Critical Path for Consumer Health Demo + +``` +[3A.1 Source-Class] ✅ --> [3A.2 Conflict Score] --> [3C.2 Layered Consensus] + | + +----> CONSUMER HEALTH MVP + | +[3B.1 Time-Travel] ------------------------------------------+ + | +[3A.3 Source Metadata] --------------------------------------+ + | +[3C.1 Skeptic Lens] ✅ --------------------------------------+ +``` + +### Critical Path for Financial DD Demo + +``` +[3A.2 Conflict Score] --> [3C.1 Skeptic Lens] ✅ -------+ + | +[3B.1 Time-Travel] -------------------------------------+----> FINANCIAL DD MVP + | +[2.3 EpochAwareLens] --> [3D.1 Epoch Cascade] ----------+ + | +[3B.2 Semantic Decay] ----------------------------------+ +``` + +### Critical Path for Agile Agent Team Demo + +``` +[3C.3 Constraints Lens] (standalone) ------+ + | +[3B.1 Time-Travel] -----------------------+----> AGENT TEAM MVP + | +[2.3 EpochAwareLens] ---------------------+ + | +[Query Audit (Phase 2)] ✅ ----------------+ +``` diff --git a/sdk/go/SDK_IMPLEMENTATION.md b/sdk/go/SDK_IMPLEMENTATION.md new file mode 100644 index 0000000..af5bf30 --- /dev/null +++ b/sdk/go/SDK_IMPLEMENTATION.md @@ -0,0 +1,408 @@ +# Go SDK Implementation Summary + +## Overview + +The StemeDB Go SDK (`steme`) provides a type-safe, ergonomic API for interacting with the StemeDB HTTP API. It eliminates cryptographic complexity and provides fluent builders for assertions and queries. + +## Implementation Status + +✅ **Complete** - All core features implemented and tested. + +## Architecture + +### Directory Structure + +``` +sdk/go/ +├── steme/ # Core SDK package +│ ├── signer.go # Ed25519 signing utilities +│ ├── assertion.go # Assertion type and fluent builder +│ ├── client.go # HTTP client with auto-signing +│ ├── query.go # Query parameters and results +│ ├── types.go # Enums and value types +│ ├── errors.go # Typed error handling +│ ├── steme_test.go # Unit tests +│ ├── go.mod # Module definition +│ └── README.md # SDK documentation +│ +├── examples/ +│ ├── basic/ # Basic usage example +│ │ ├── main.go +│ │ └── go.mod +│ └── skeptic/ # "Trust but Verify" example +│ ├── main.go +│ └── go.mod +│ +└── SDK_IMPLEMENTATION.md # This file +``` + +## Core Features + +### 1. Signing Helpers (`signer.go`) + +Abstracts Ed25519 cryptography for assertion signing. + +**Features:** +- Generate new keypairs +- Load from hex-encoded seed +- Load from environment variable +- Sign messages +- Verify signatures +- Extract public key (agent_id) + +**API:** +```go +signer, err := steme.GenerateSigner() +signer, err := steme.NewSignerFromHex("hex-seed") +signer, err := steme.SignerFromEnv("STEME_PRIVATE_KEY") + +agentID := signer.PublicKey() +signature := signer.Sign(message) +``` + +**Test Coverage:** +- ✅ Keypair generation +- ✅ Seed serialization/deserialization +- ✅ Signature creation +- ✅ Signature verification + +### 2. Type-Safe Assertion Builder (`assertion.go`) + +Fluent API for constructing assertions without manual JSON. + +**Features:** +- Required fields enforced at construction +- Optional fields via builder methods +- Client-side validation +- Four object value types (Text, Number, Boolean, Reference) + +**API:** +```go +assertion := steme.NewAssertion("subject", "predicate"). + WithNumber(42.5). + WithConfidence(0.95). + WithLifecycle(steme.LifecycleApproved). + WithSourceClass(steme.SourceClassClinical). + WithSourceHash("..."). + Build() + +err := assertion.Validate() // Client-side validation +``` + +**Test Coverage:** +- ✅ Fluent builder API +- ✅ Confidence validation (0.0-1.0) +- ✅ Hex hash validation (length and encoding) +- ✅ Required field validation + +### 3. HTTP Client with Auto-Signing (`client.go`) + +HTTP client that automatically signs all assertions. + +**Features:** +- Automatic Ed25519 signing +- Context support for cancellation/timeouts +- Typed error responses +- Configurable HTTP client +- Agent ID header for audit trail + +**API:** +```go +client := steme.NewClient("http://localhost:3000", signer) +client = client.WithHTTPClient(customHTTPClient) + +hash, err := client.Assert(ctx, assertion) +result, err := client.Query(ctx, params) +skeptic, err := client.Skeptic(ctx, params) +health, err := client.Health(ctx) +``` + +**Signing Algorithm:** +``` +canonical_message = BLAKE2b( + subject || 0x00 || + predicate || 0x00 || + json(object) || 0x00 || + json(confidence) || 0x00 || + source_hash_bytes +) + +signature = Ed25519.Sign(private_key, canonical_message) +``` + +**Test Coverage:** +- ✅ Canonical message generation (deterministic) +- ✅ Message uniqueness across different assertions +- 🔲 Integration test placeholder (requires running server) + +### 4. Query API (`query.go`) + +Fluent query builder and result types. + +**Features:** +- Optional filters (subject, predicate, lifecycle, epoch) +- Lens-based conflict resolution +- Skeptic lens for "Trust but Verify" +- Pagination support + +**API:** +```go +// Standard query with lens +params := steme.NewQuery(). + WithSubject("Tesla_Inc"). + WithPredicate("has_revenue"). + WithLens(steme.LensConsensus). + WithLimit(10). + Build() + +// Skeptic query (shows all competing claims) +skepticParams := steme.SkepticQueryParams{ + Subject: "Semaglutide", + Predicate: "muscle_effect", +} +``` + +**Test Coverage:** +- ✅ Query builder fluent API +- ✅ Parameter construction + +### 5. Type System (`types.go`) + +Type-safe enums and value types matching StemeDB's data model. + +**Enums:** +- `LifecycleStage`: Proposed, UnderReview, Approved, Deprecated, Rejected +- `SourceClass`: Regulatory, Clinical, Observational, Expert, Community, Anecdotal +- `Lens`: Recency, Consensus, Authority, VoteAwareConsensus, TrustAwareAuthority +- `ResolutionStatus`: Unanimous, Agreed, Contested + +**Value Types:** +- `ObjectValue`: Tagged union (Text, Number, Boolean, Reference) +- `SignatureEntry`: Ed25519 signature metadata +- `QueryParams`: Query filter parameters +- `AssertionResponse`: Assertion with metadata +- `QueryResult`: Query response with pagination +- `SkepticResult`: Conflict analysis response + +**Test Coverage:** +- ✅ Object value constructors +- ✅ Type serialization + +### 6. Error Handling (`errors.go`) + +Typed errors for common failure modes. + +**Error Types:** +- `APIError`: HTTP errors from server (status code, message, code) +- `ValidationError`: Client-side validation failures (field, message) +- Predefined errors: `ErrInvalidKeySize`, `ErrInvalidConfidence`, etc. + +**Usage:** +```go +hash, err := client.Assert(ctx, assertion) +if err != nil { + switch e := err.(type) { + case *steme.APIError: + log.Printf("API error [%d]: %s", e.StatusCode, e.Message) + case *steme.ValidationError: + log.Printf("Invalid %s: %s", e.Field, e.Message) + default: + log.Printf("Error: %v", err) + } +} +``` + +## Quality Metrics + +### Test Results + +``` +=== RUN TestSignerGeneration +--- PASS: TestSignerGeneration (0.00s) +=== RUN TestSignerSignAndVerify +--- PASS: TestSignerSignAndVerify (0.00s) +=== RUN TestAssertionBuilder +--- PASS: TestAssertionBuilder (0.00s) +=== RUN TestAssertionValidation +--- PASS: TestAssertionValidation (0.00s) +=== RUN TestQueryBuilder +--- PASS: TestQueryBuilder (0.00s) +=== RUN TestCanonicalMessage +--- PASS: TestCanonicalMessage (0.00s) +=== RUN TestObjectValueConstructors +--- PASS: TestObjectValueConstructors (0.00s) + +PASS +ok github.com/orchard9/stemedb-go/steme 0.188s +``` + +### Code Quality + +- ✅ Zero `unwrap()` or `expect()` calls +- ✅ Context support for all I/O operations +- ✅ Proper error wrapping with `fmt.Errorf` +- ✅ Godoc comments on all public types/functions +- ✅ Go idiomatic code (no Java-isms) +- ✅ Defensive validation +- ✅ Typed error handling + +## Examples + +### 1. Basic Usage (`examples/basic/`) + +Demonstrates: +- Keypair generation +- Assertion creation with fluent API +- Automatic signing +- Querying with lens +- Health check + +**Run:** +```bash +cd sdk/go/examples/basic +go run main.go +``` + +### 2. Skeptic Lens (`examples/skeptic/`) + +Demonstrates: +- Creating conflicting assertions +- Skeptic query for "Trust but Verify" +- Conflict analysis interpretation +- Resolution status handling + +**Run:** +```bash +cd sdk/go/examples/skeptic +go run main.go +``` + +## Integration with StemeDB API + +### Endpoint Mapping + +| SDK Method | HTTP Endpoint | DTO | +|------------|---------------|-----| +| `client.Assert()` | `POST /v1/assert` | `CreateAssertionRequest` → `CreateResponse` | +| `client.Query()` | `GET /v1/query` | `QueryParams` → `QueryResponse` | +| `client.Skeptic()` | `GET /v1/skeptic` | `SkepticQueryParams` → `SkepticResponse` | +| `client.Health()` | `GET /v1/health` | - → `HealthResponse` | + +### Type Alignment + +All SDK types align 1:1 with API DTOs: + +- `Assertion` ↔ `CreateAssertionRequest` +- `AssertionResponse` ↔ `AssertionResponse` +- `ObjectValue` ↔ `ObjectValueDto` +- `LifecycleStage` ↔ `LifecycleDto` +- `SourceClass` ↔ `SourceClassDto` +- `Lens` ↔ `LensDto` +- `SignatureEntry` ↔ `SignatureDto` + +### Serialization + +- **Enums:** Serialized as PascalCase strings (e.g., `"Approved"`, `"Clinical"`) +- **Object Values:** Tagged union with `{"type": "...", "value": ...}` +- **Hashes:** Hex-encoded (64 chars for 32-byte hashes, 16 chars for 8-byte) +- **Signatures:** Hex-encoded (128 chars for 64-byte Ed25519 signatures) + +## Documentation + +- **SDK README:** `sdk/go/steme/README.md` - Quick start and API overview +- **Full Guide:** `docs/sdk/go-sdk.md` - Comprehensive usage guide +- **Examples:** `sdk/go/examples/` - Runnable code examples +- **Usage Guide:** `usage.md` - Updated with SDK quick start + +## Future Enhancements + +### Planned Features + +1. **Batch Assertions:** `client.BatchAssert(ctx, []Assertion)` for high-volume ingestion +2. **Streaming Queries:** SSE-based real-time updates +3. **Materialized View API:** Direct MV:{subject}:{predicate} reads +4. **Vote Submission:** `client.Vote(ctx, assertionHash, weight)` +5. **Epoch Management:** `client.CreateEpoch(ctx, name, supersedes)` +6. **Trust Score Queries:** `client.GetTrustScore(ctx, agentID)` + +### Potential Optimizations + +1. **Connection Pooling:** Reuse HTTP connections (already done via `http.Client`) +2. **Request Compression:** gzip compression for large assertion batches +3. **Response Caching:** Client-side cache for frequently-queried assertions +4. **Retry Logic:** Automatic retry with exponential backoff for transient failures + +## Migration Path + +For users currently using raw HTTP calls: + +**Before (Manual HTTP):** +```go +payload := map[string]interface{}{ + "subject": "Tesla_Inc", + "predicate": "has_revenue", + "object": map[string]interface{}{"type": "Number", "value": 96.7}, + // ... manual signature computation ... +} + +resp, err := http.Post("http://localhost:3000/v1/assert", ...) +``` + +**After (SDK):** +```go +assertion := steme.NewAssertion("Tesla_Inc", "has_revenue"). + WithNumber(96.7). + WithSourceHash("..."). + Build() + +hash, err := client.Assert(ctx, assertion) +``` + +**Benefits:** +- ✅ No manual signature computation +- ✅ Type safety (compile-time errors vs runtime JSON errors) +- ✅ Client-side validation +- ✅ Fluent, readable API +- ✅ Automatic error handling + +## Compliance with Requirements + +All original requirements met: + +### 1. Signing Helper ✅ +- `NewSigner()`, `GenerateSigner()`, `SignerFromEnv()` +- Ed25519 keypair management +- Automatic signing + +### 2. Type-Safe Assertion Builder ✅ +- Fluent API: `NewAssertion().With*().Build()` +- All optional fields via builder methods +- Client-side validation + +### 3. Client with Automatic Signing ✅ +- `NewClient(baseURL, signer)` +- Auto-signs all assertions +- Context support + +### 4. Query Results ✅ +- `QueryResult` with `Assertions`, `TotalCount`, `HasMore` +- `AssertionResponse` with full metadata +- Skeptic lens support + +### 5. Quality Requirements ✅ +- Proper error handling with wrapped errors +- Context support for cancellation +- Unit tests for signer and builder +- Integration test placeholder +- Go idiomatic code +- Godoc comments on all public types + +## Conclusion + +The Go SDK is production-ready and provides a complete, type-safe abstraction over the StemeDB HTTP API. It eliminates cryptographic complexity, provides excellent error handling, and follows Go best practices throughout. + +**Next Steps:** +1. Publish to GitHub as `github.com/orchard9/stemedb-go` +2. Add CI/CD for automated testing +3. Create Go package documentation site (pkg.go.dev) +4. Implement batch assertion API for high-volume use cases diff --git a/sdk/go/adk/README.md b/sdk/go/adk/README.md new file mode 100644 index 0000000..dcd16ad --- /dev/null +++ b/sdk/go/adk/README.md @@ -0,0 +1,416 @@ +# StemeDB ADK-Go Integration + +ADK-Go tool wrappers for integrating AI agents with Episteme (StemeDB) using Google's Agent Development Kit. + +## Overview + +This package provides: + +- **Tool Definitions**: Query, Assert, ConstraintCheck, Trace, Supersede +- **Callback Helpers**: Confidence escalation, constraint enforcement, audit logging +- **Agent Configuration**: Pre-configured setups for standard agent types + +## Installation + +```bash +go get github.com/orchard9/stemedb-go/adk +``` + +## Quick Start + +```go +package main + +import ( + "context" + "log" + + "github.com/orchard9/stemedb-go/adk" + "github.com/orchard9/stemedb-go/steme" +) + +func main() { + // Create StemeDB client + signer, _ := steme.GenerateSigner() + client := steme.NewClient("http://localhost:3000", signer) + + // Get all Episteme tools + tools := adk.AllTools(client) + + // Or get pre-configured agent setups + configs := adk.AllConfigs( + client, + 0.8, // confidence threshold + setState, + log.Printf, + ) + + // Use with your ADK agent + // agent := configureAgent(configs["implementation"]) +} + +func setState(key string, value interface{}) { + // Store session state +} +``` + +## Tools + +### Query Tool + +Query Episteme with lens-based conflict resolution. + +```go +tool := adk.NewQueryTool(client) + +input := adk.QueryInput{ + Subject: "auth/jwt", + Predicate: "signing_algorithm", + Lens: "authority", + Lifecycle: "approved", + MinConfidence: 0.8, +} + +// Execute returns QueryOutput with resolved value +``` + +**Critical Rules:** +- Always filter by `lifecycle=approved` for production decisions +- Check confidence thresholds before acting +- Use appropriate lens (authority, consensus, recency) + +### Assert Tool + +Store knowledge with lifecycle and confidence. + +```go +tool := adk.NewAssertTool(client) + +input := adk.AssertInput{ + Subject: "Tesla_Inc", + Predicate: "has_revenue", + Object: 96.7, + SourceHash: "0000...0000", // BLAKE3 hash of evidence + Confidence: 0.95, + Lifecycle: "proposed", // Default to proposed +} + +// Execute returns AssertOutput with content-addressed hash +``` + +**Critical Rules:** +- Always include `source_hash` for provenance +- Use confidence to express uncertainty (0.0-1.0) +- Default to `lifecycle=proposed` (not approved) +- Store conflicting sources without resolving + +### Constraint Check Tool + +Pre-flight validation for Implementation Agent. + +```go +tool := adk.NewConstraintCheckTool(client) + +input := adk.ConstraintCheckInput{ + Context: "auth_jwt", +} + +// Execute returns ConstraintCheckOutput with must-use and forbidden patterns +``` + +**Critical Rules:** +- Implementation Agent MUST call before code generation +- Returns both positive (must_use) and negative (forbidden) constraints +- Enables contrastive learning ("use X, not Y, because Z") + +### Trace Tool + +Audit trail queries for incident investigation. + +```go +tool := adk.NewTraceTool() + +input := adk.TraceInput{ + AgentID: "deployment-agent", + From: "-6h", + Subject: "auth/*", +} + +// Execute returns TraceOutput with query history +``` + +**Use Cases:** +- On-Call SRE: "What did the agent query during the incident?" +- Human Supervisor: "What values did the agent see at that time?" +- Incident investigation: Sub-second trace queries + +### Supersede Tool + +Error correction with cascade tracking. + +```go +tool := adk.NewSupersedeTool() + +input := adk.SupersedeInput{ + Hash: "bad_assertion_hash", + Reason: "Proposal treated as approved", + Type: "Invalidate", +} + +// Execute returns SupersedeOutput with affected assertions +``` + +**Use Cases:** +- Correct bad assertions +- Track downstream impact +- Incident remediation + +## Callbacks + +### Constraint Enforcement + +Enforce constraints before code generation. + +```go +callback := adk.ConstraintEnforcementCallback(client, []string{ + "write_code", + "generate_config", +}) + +// Use in agent config +agent.BeforeToolCallback = callback +``` + +Blocks code generation if forbidden patterns would be used. + +### Confidence Escalation + +Escalate to human when confidence is too low. + +```go +callback := adk.ConfidenceEscalationCallback(0.8, setState) + +// Use in agent config +agent.AfterToolCallback = callback +``` + +Sets session state for human review when confidence < threshold. + +### Audit Logging + +Log all tool calls for debugging. + +```go +callback := adk.AuditLoggingCallback(log.Printf) + +// Use in agent config +agent.AfterToolCallback = callback +``` + +### Chaining Callbacks + +Combine multiple callbacks. + +```go +beforeCallback := adk.ChainBeforeCallbacks( + adk.ConstraintEnforcementCallback(client, codeGenTools), + customValidation, +) + +afterCallback := adk.ChainAfterCallbacks( + adk.ConfidenceEscalationCallback(0.8, setState), + adk.AuditLoggingCallback(log.Printf), +) +``` + +## Agent Configurations + +### Implementation Agent + +Writes code against approved patterns only. + +```go +config := adk.ConfigForImplementationAgent(client, log.Printf) +``` + +**Features:** +- Queries only approved patterns +- Checks constraints before code generation +- Blocks forbidden patterns +- Audit logging + +**Workflow:** +1. Query approved pattern +2. Check constraints +3. Write code +4. Never use proposed/deprecated patterns + +### Lead Orchestrator + +Coordinates agent team based on knowledge state. + +```go +config := adk.ConfigForLeadOrchestrator( + client, + 0.8, // confidence threshold + setState, + log.Printf, +) +``` + +**Features:** +- Queries with appropriate lens +- Confidence threshold escalation +- Routes work to implementation or human +- Audit logging + +**Workflow:** +1. Query current state +2. Check confidence +3. If high: route to implementation +4. If low: escalate to human + +### Research Agent + +Discovers and stores knowledge with source attribution. + +```go +config := adk.ConfigForResearchAgent(client, log.Printf) +``` + +**Features:** +- Stores all sources (even conflicting) +- Expresses uncertainty via confidence +- Marks as proposed (not approved) +- Source provenance tracking + +**Workflow:** +1. Research from multiple sources +2. Create assertion for each source +3. Don't resolve conflicts (store all) +4. Let orchestrator resolve via lens + +### Human Supervisor + +Investigates incidents and corrects knowledge. + +```go +config := adk.ConfigForHumanSupervisor(client, log.Printf) +``` + +**Features:** +- Time-travel queries (as_of parameter) +- Trace queries +- Supersede for corrections +- Approve proposed assertions + +**Workflow:** +1. Time-travel to incident +2. Trace agent queries +3. Identify bad assertion +4. Supersede with correction +5. Verify fix + +### On-Call SRE + +Fast incident investigation via trace queries. + +```go +config := adk.ConfigForOnCallSRE(client, log.Printf) +``` + +**Features:** +- Sub-second trace queries +- Fast read-only investigation +- Escalation to supervisor for corrections + +**Workflow (under 10 minutes):** +1. Trace: What did agent query? +2. Diff: What changed? +3. Identify: Which assertion is bad? +4. Escalate: Flag for supervisor + +## Agent Coordination Pattern + +```go +// Create multi-agent pipeline +client := steme.NewClient("http://localhost:3000", signer) + +configs := adk.AllConfigs(client, 0.8, setState, log.Printf) + +// Research Agent: Discovers knowledge +researchAgent := configureAgent(configs["research"]) + +// Lead Orchestrator: Routes based on confidence +leadAgent := configureAgent(configs["lead"]) + +// Implementation Agent: Writes code +implAgent := configureAgent(configs["implementation"]) + +// Sequential pipeline +pipeline := sequentialAgent(researchAgent, leadAgent, implAgent) +``` + +## Session State vs. Episteme + +| Use Case | Mechanism | Why | +|----------|-----------|-----| +| Agent handoff in pipeline | Session State + OutputKey | Ephemeral, same conversation | +| Permanent org knowledge | Episteme Assert | Persists across sessions | +| "What was decided here?" | Session State | Temporary | +| "What should agents know forever?" | Episteme + lifecycle:approved | Permanent | +| Agent decision audit | Episteme QueryAudit | Immutable, time-travel | + +## Testing + +```bash +cd sdk/go/adk +go test -v +``` + +Tests include: +- Tool execution with mock client +- Confidence threshold enforcement +- Constraint checking +- Config creation +- Lifecycle/lens parsing + +## Interface-Based Design + +Since ADK-Go is not yet publicly released, this package uses interface-based design: + +```go +// Generic tool interface +type Tool interface { + Name() string + Description() string + Execute(ctx context.Context, input []byte) ([]byte, error) +} + +// Generic client interface +type EpistemeClient interface { + Query(ctx context.Context, params steme.QueryParams) (*steme.QueryResult, error) + Assert(ctx context.Context, assertion steme.Assertion) (string, error) +} +``` + +This allows: +- Easy testing with mock clients +- Adaptation to any ADK implementation +- Standalone usage without ADK + +## Examples + +See `.claude/guides/integrations/adk-go-episteme.md` for complete examples: + +- Multi-agent pipeline +- Confidence escalation +- Constraint enforcement +- Time-travel queries +- Incident investigation + +## For More Information + +- **Use case context**: [use-cases/agile-agent-team.md](../../../use-cases/agile-agent-team.md) +- **Integration guide**: [.claude/guides/integrations/adk-go-episteme.md](../../../.claude/guides/integrations/adk-go-episteme.md) +- **Base SDK**: [sdk/go/steme/](../steme/) diff --git a/sdk/go/adk/adk_test.go b/sdk/go/adk/adk_test.go new file mode 100644 index 0000000..99e2ece --- /dev/null +++ b/sdk/go/adk/adk_test.go @@ -0,0 +1,610 @@ +package adk + +import ( + "context" + "encoding/json" + "testing" + + "github.com/orchard9/stemedb-go/steme" +) + +// mockClient implements EpistemeClient for testing +type mockClient struct { + queryFunc func(ctx context.Context, params steme.QueryParams) (*steme.QueryResult, error) + assertFunc func(ctx context.Context, assertion steme.Assertion) (string, error) + traceFunc func(ctx context.Context, params steme.TraceParams) (*steme.TraceResult, error) + supersedeFunc func(ctx context.Context, params steme.SupersedeParams) (*steme.SupersedeResult, error) +} + +func (m *mockClient) Query(ctx context.Context, params steme.QueryParams) (*steme.QueryResult, error) { + if m.queryFunc != nil { + return m.queryFunc(ctx, params) + } + return &steme.QueryResult{}, nil +} + +func (m *mockClient) Assert(ctx context.Context, assertion steme.Assertion) (string, error) { + if m.assertFunc != nil { + return m.assertFunc(ctx, assertion) + } + return "mock_hash", nil +} + +func (m *mockClient) Trace(ctx context.Context, params steme.TraceParams) (*steme.TraceResult, error) { + if m.traceFunc != nil { + return m.traceFunc(ctx, params) + } + return &steme.TraceResult{}, nil +} + +func (m *mockClient) Supersede(ctx context.Context, params steme.SupersedeParams) (*steme.SupersedeResult, error) { + if m.supersedeFunc != nil { + return m.supersedeFunc(ctx, params) + } + return &steme.SupersedeResult{ + Status: "superseded", + TargetHash: params.TargetHash, + SupersessionType: params.SupersessionType, + Timestamp: 1704067200, + }, nil +} + +func TestQueryTool(t *testing.T) { + // Mock client that returns a test assertion + client := &mockClient{ + queryFunc: func(ctx context.Context, params steme.QueryParams) (*steme.QueryResult, error) { + lifecycle := steme.LifecycleApproved + return &steme.QueryResult{ + Assertions: []steme.AssertionResponse{ + { + Hash: "test_hash", + Subject: "Tesla_Inc", + Predicate: "has_revenue", + Object: steme.NewNumberValue(96.7), + Confidence: 0.95, + SourceHash: "source_hash", + Lifecycle: lifecycle, + }, + }, + TotalCount: 1, + HasMore: false, + }, nil + }, + } + + tool := NewQueryTool(client) + + // Test basic query + input := QueryInput{ + Subject: "Tesla_Inc", + Predicate: "has_revenue", + Lens: "consensus", + } + + inputBytes, err := json.Marshal(input) + if err != nil { + t.Fatalf("failed to marshal input: %v", err) + } + + outputBytes, err := tool.Execute(context.Background(), inputBytes) + if err != nil { + t.Fatalf("query failed: %v", err) + } + + var output QueryOutput + if err := json.Unmarshal(outputBytes, &output); err != nil { + t.Fatalf("failed to unmarshal output: %v", err) + } + + // Verify output + if output.Confidence != 0.95 { + t.Errorf("expected confidence 0.95, got %f", output.Confidence) + } + + if output.Lifecycle != "Approved" { + t.Errorf("expected lifecycle Approved, got %s", output.Lifecycle) + } + + if output.QueryID == "" { + t.Error("expected non-empty query ID") + } + + if len(output.Sources) == 0 { + t.Error("expected at least one source") + } +} + +func TestQueryToolConfidenceThreshold(t *testing.T) { + // Mock client that returns low confidence + client := &mockClient{ + queryFunc: func(ctx context.Context, params steme.QueryParams) (*steme.QueryResult, error) { + lifecycle := steme.LifecycleApproved + return &steme.QueryResult{ + Assertions: []steme.AssertionResponse{ + { + Hash: "test_hash", + Subject: "test", + Predicate: "test", + Object: steme.NewTextValue("test"), + Confidence: 0.6, // Low confidence + SourceHash: "source_hash", + Lifecycle: lifecycle, + }, + }, + TotalCount: 1, + }, nil + }, + } + + tool := NewQueryTool(client) + + input := QueryInput{ + Subject: "test", + Predicate: "test", + MinConfidence: 0.8, // Require high confidence + } + + inputBytes, _ := json.Marshal(input) + outputBytes, err := tool.Execute(context.Background(), inputBytes) + if err != nil { + t.Fatalf("query failed: %v", err) + } + + var output QueryOutput + json.Unmarshal(outputBytes, &output) + + // Should have error about low confidence + if output.Error == "" { + t.Error("expected error for low confidence") + } +} + +func TestAssertTool(t *testing.T) { + // Track what assertion was created + var capturedAssertion steme.Assertion + + client := &mockClient{ + assertFunc: func(ctx context.Context, assertion steme.Assertion) (string, error) { + capturedAssertion = assertion + return "created_hash", nil + }, + } + + tool := NewAssertTool(client) + + input := AssertInput{ + Subject: "Tesla_Inc", + Predicate: "has_revenue", + Object: 96.7, + SourceHash: "0000000000000000000000000000000000000000000000000000000000000000", + Confidence: 0.95, + Lifecycle: "approved", + } + + inputBytes, _ := json.Marshal(input) + outputBytes, err := tool.Execute(context.Background(), inputBytes) + if err != nil { + t.Fatalf("assert failed: %v", err) + } + + var output AssertOutput + json.Unmarshal(outputBytes, &output) + + // Verify output + if !output.Success { + t.Errorf("expected success, got error: %s", output.Error) + } + + if output.Hash != "created_hash" { + t.Errorf("expected hash created_hash, got %s", output.Hash) + } + + // Verify captured assertion + if capturedAssertion.Subject != "Tesla_Inc" { + t.Errorf("expected subject Tesla_Inc, got %s", capturedAssertion.Subject) + } + + // Use approximate comparison for floating point + if capturedAssertion.Confidence < 0.94 || capturedAssertion.Confidence > 0.96 { + t.Errorf("expected confidence ~0.95, got %f", capturedAssertion.Confidence) + } +} + +func TestConstraintCheckTool(t *testing.T) { + // Mock client that returns constraint assertions + client := &mockClient{ + queryFunc: func(ctx context.Context, params steme.QueryParams) (*steme.QueryResult, error) { + lifecycle := steme.LifecycleApproved + return &steme.QueryResult{ + Assertions: []steme.AssertionResponse{ + { + Hash: "constraint1", + Subject: "auth_jwt", + Predicate: "must_use", + Object: steme.NewTextValue("Ed25519"), + Confidence: 1.0, + SourceHash: "source", + Lifecycle: lifecycle, + }, + { + Hash: "constraint2", + Subject: "auth_jwt", + Predicate: "forbidden", + Object: steme.NewTextValue("MD5"), + Confidence: 1.0, + SourceHash: "source", + Lifecycle: lifecycle, + }, + }, + TotalCount: 2, + }, nil + }, + } + + tool := NewConstraintCheckTool(client) + + input := ConstraintCheckInput{ + Context: "auth_jwt", + } + + inputBytes, _ := json.Marshal(input) + outputBytes, err := tool.Execute(context.Background(), inputBytes) + if err != nil { + t.Fatalf("constraint check failed: %v", err) + } + + var output ConstraintCheckOutput + json.Unmarshal(outputBytes, &output) + + // Verify constraints were returned + if len(output.Constraints) != 2 { + t.Errorf("expected 2 constraints, got %d", len(output.Constraints)) + } + + // Check for must-use constraint + foundMustUse := false + for _, c := range output.Constraints { + if c.MustUse == "Ed25519" { + foundMustUse = true + } + } + if !foundMustUse { + t.Error("expected to find Ed25519 must-use constraint") + } + + // Check for forbidden constraint + foundForbidden := false + for _, c := range output.Constraints { + if c.Forbidden == "MD5" { + foundForbidden = true + } + } + if !foundForbidden { + t.Error("expected to find MD5 forbidden constraint") + } +} + +func TestTraceTool(t *testing.T) { + // Mock client that returns audit records + agentID := "deadbeef00000000000000000000000000000000000000000000000000000000" + subject := "Tesla_Inc" + predicate := "has_revenue" + resultHash := "result_hash_123" + lens := steme.LensConsensus + + client := &mockClient{ + traceFunc: func(ctx context.Context, params steme.TraceParams) (*steme.TraceResult, error) { + return &steme.TraceResult{ + Audits: []steme.QueryAuditRecord{ + { + QueryID: "query_123", + AgentID: &agentID, + Timestamp: 1704067200, + Params: steme.QueryParamsAudit{ + Subject: &subject, + Predicate: &predicate, + Lens: &lens, + }, + ResultHash: &resultHash, + ResultConfidence: 0.95, + ContributingAssertions: []steme.ContributingAssertion{ + { + AssertionHash: "assertion_1", + Weight: 1.0, + SourceHash: "source_1", + Lifecycle: steme.LifecycleApproved, + }, + { + AssertionHash: "assertion_2", + Weight: 0.5, + SourceHash: "source_2", + Lifecycle: steme.LifecycleProposed, + }, + }, + }, + }, + TotalCount: 1, + AgentID: agentID, + FromTimestamp: 1704067200, + ToTimestamp: 1704153600, + }, nil + }, + } + + tool := NewTraceTool(client) + + input := TraceInput{ + AgentID: agentID, + From: "1704067200", + To: "1704153600", + Subject: "Tesla*", + } + + inputBytes, _ := json.Marshal(input) + outputBytes, err := tool.Execute(context.Background(), inputBytes) + if err != nil { + t.Fatalf("trace failed: %v", err) + } + + var output TraceOutput + json.Unmarshal(outputBytes, &output) + + // Verify output + if len(output.Queries) != 1 { + t.Errorf("expected 1 query, got %d", len(output.Queries)) + } + + if len(output.Queries) > 0 { + query := output.Queries[0] + + if query.QueryID != "query_123" { + t.Errorf("expected query_id query_123, got %s", query.QueryID) + } + + if query.Subject != "Tesla_Inc" { + t.Errorf("expected subject Tesla_Inc, got %s", query.Subject) + } + + if query.Predicate != "has_revenue" { + t.Errorf("expected predicate has_revenue, got %s", query.Predicate) + } + + if query.Lens != "consensus" { + t.Errorf("expected lens consensus, got %s", query.Lens) + } + + if query.Confidence != 0.95 { + t.Errorf("expected confidence 0.95, got %f", query.Confidence) + } + + if len(query.Contributing) != 2 { + t.Errorf("expected 2 contributing assertions, got %d", len(query.Contributing)) + } + } +} + +func TestSupersedeTool(t *testing.T) { + // Track what supersession was created + var capturedParams steme.SupersedeParams + + client := &mockClient{ + supersedeFunc: func(ctx context.Context, params steme.SupersedeParams) (*steme.SupersedeResult, error) { + capturedParams = params + return &steme.SupersedeResult{ + Status: "superseded", + TargetHash: params.TargetHash, + SupersessionType: params.SupersessionType, + Timestamp: 1704067200, + }, nil + }, + } + + tool := NewSupersedeTool(client) + + input := SupersedeInput{ + Hash: "abc123def456", + Type: "Invalidate", + Reason: "Proposal treated as approved. See incident INC-2024-001", + NewHash: "def456abc123", + AgentID: "deadbeef00000000000000000000000000000000000000000000000000000000", + Signature: "0000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000", + } + + inputBytes, err := json.Marshal(input) + if err != nil { + t.Fatalf("failed to marshal input: %v", err) + } + + outputBytes, err := tool.Execute(context.Background(), inputBytes) + if err != nil { + t.Fatalf("supersede failed: %v", err) + } + + var output SupersedeOutput + if err := json.Unmarshal(outputBytes, &output); err != nil { + t.Fatalf("failed to unmarshal output: %v", err) + } + + // Verify output + if !output.Success { + t.Errorf("expected success, got error: %s", output.Error) + } + + if output.TargetHash != "abc123def456" { + t.Errorf("expected target hash abc123def456, got %s", output.TargetHash) + } + + if output.SupersessionType != "Invalidate" { + t.Errorf("expected supersession type Invalidate, got %s", output.SupersessionType) + } + + // Verify captured params + if capturedParams.TargetHash != "abc123def456" { + t.Errorf("expected target hash abc123def456, got %s", capturedParams.TargetHash) + } + + if capturedParams.SupersessionType != steme.SupersessionInvalidate { + t.Errorf("expected supersession type Invalidate, got %s", capturedParams.SupersessionType) + } + + if capturedParams.Reason != "Proposal treated as approved. See incident INC-2024-001" { + t.Errorf("expected reason about proposal, got %s", capturedParams.Reason) + } +} + +func TestParseSupersessionType(t *testing.T) { + tests := []struct { + input string + expected steme.SupersessionType + }{ + {"Invalidate", steme.SupersessionInvalidate}, + {"invalidate", steme.SupersessionInvalidate}, + {"Temporal", steme.SupersessionTemporal}, + {"temporal", steme.SupersessionTemporal}, + {"Refinement", steme.SupersessionRefinement}, + {"RequiresReview", steme.SupersessionRequiresReview}, + {"requires_review", steme.SupersessionRequiresReview}, + {"Additive", steme.SupersessionAdditive}, + {"additive", steme.SupersessionAdditive}, + {"unknown", steme.SupersessionInvalidate}, // Default + } + + for _, tt := range tests { + result := parseSupersessionType(tt.input) + if result != tt.expected { + t.Errorf("parseSupersessionType(%s) = %v, expected %v", tt.input, result, tt.expected) + } + } +} + +func TestToolNames(t *testing.T) { + client := &mockClient{} + + tests := []struct { + tool Tool + expectedName string + }{ + {NewQueryTool(client), "episteme_query"}, + {NewAssertTool(client), "episteme_assert"}, + {NewConstraintCheckTool(client), "episteme_constraint_check"}, + {NewTraceTool(client), "episteme_trace"}, + {NewSupersedeTool(client), "episteme_supersede"}, + } + + for _, tt := range tests { + if tt.tool.Name() != tt.expectedName { + t.Errorf("expected tool name %s, got %s", tt.expectedName, tt.tool.Name()) + } + } +} + +func TestAllTools(t *testing.T) { + client := &mockClient{} + tools := AllTools(client) + + if len(tools) != 5 { + t.Errorf("expected 5 tools, got %d", len(tools)) + } + + // Verify all expected tools are present + expectedNames := map[string]bool{ + "episteme_query": false, + "episteme_assert": false, + "episteme_constraint_check": false, + "episteme_trace": false, + "episteme_supersede": false, + } + + for _, tool := range tools { + expectedNames[tool.Name()] = true + } + + for name, found := range expectedNames { + if !found { + t.Errorf("expected to find tool %s", name) + } + } +} + +func TestConfigCreation(t *testing.T) { + client := &mockClient{} + logFunc := func(format string, args ...any) {} + setState := func(key string, value any) {} + + configs := AllConfigs(client, 0.8, setState, logFunc) + + expectedAgents := []string{ + "implementation", + "lead", + "research", + "supervisor", + "oncall", + } + + for _, agentType := range expectedAgents { + config, ok := configs[agentType] + if !ok { + t.Errorf("expected config for %s", agentType) + continue + } + + if config.Name == "" { + t.Errorf("config for %s has empty name", agentType) + } + + if config.Description == "" { + t.Errorf("config for %s has empty description", agentType) + } + + if config.Instruction == "" { + t.Errorf("config for %s has empty instruction", agentType) + } + + if len(config.Tools) == 0 { + t.Errorf("config for %s has no tools", agentType) + } + } +} + +func TestParseLifecycle(t *testing.T) { + tests := []struct { + input string + expected steme.LifecycleStage + }{ + {"proposed", steme.LifecycleProposed}, + {"under_review", steme.LifecycleUnderReview}, + {"approved", steme.LifecycleApproved}, + {"deprecated", steme.LifecycleDeprecated}, + {"rejected", steme.LifecycleRejected}, + {"invalid", steme.LifecycleProposed}, // Default + } + + for _, tt := range tests { + result := parseLifecycle(tt.input) + if result != tt.expected { + t.Errorf("parseLifecycle(%s) = %v, expected %v", tt.input, result, tt.expected) + } + } +} + +func TestParseLens(t *testing.T) { + tests := []struct { + input string + expected steme.Lens + }{ + {"recency", steme.LensRecency}, + {"consensus", steme.LensConsensus}, + {"authority", steme.LensAuthority}, + {"vote_aware_consensus", steme.LensVoteAwareConsensus}, + {"trust_aware_authority", steme.LensTrustAwareAuthority}, + {"invalid", steme.LensConsensus}, // Default + } + + for _, tt := range tests { + result := parseLen(tt.input) + if result != tt.expected { + t.Errorf("parseLen(%s) = %v, expected %v", tt.input, result, tt.expected) + } + } +} diff --git a/sdk/go/adk/callbacks.go b/sdk/go/adk/callbacks.go new file mode 100644 index 0000000..0f7e856 --- /dev/null +++ b/sdk/go/adk/callbacks.go @@ -0,0 +1,237 @@ +package adk + +import ( + "context" + "encoding/json" + "fmt" + "slices" +) + +// CallbackContext provides context for agent callbacks. +// +// This interface matches the pattern expected by ADK-Go but is generic +// enough to work with any agent framework. +type CallbackContext interface { + Context() context.Context + AgentName() string + SessionID() string +} + +// ToolCall represents a tool invocation. +type ToolCall struct { + Name string `json:"name"` + Input json.RawMessage `json:"input"` +} + +// ToolResult represents the result of a tool invocation. +type ToolResult struct { + Output json.RawMessage `json:"output"` + Error error `json:"error,omitempty"` +} + +// BeforeToolCallback is a function that runs before a tool is called. +// +// This can be used to: +// - Validate tool inputs +// - Enforce constraints +// - Block dangerous operations +// +// Return an error to prevent the tool from executing. +type BeforeToolCallback func(ctx CallbackContext, call *ToolCall) error + +// AfterToolCallback is a function that runs after a tool is called. +// +// This can be used to: +// - Log tool results +// - Check confidence thresholds +// - Trigger escalations +// +// Return an error to indicate the tool result should be treated as a failure. +type AfterToolCallback func(ctx CallbackContext, call *ToolCall, result *ToolResult) error + +// ConstraintEnforcementCallback enforces constraints before code generation. +// +// This callback is designed for Implementation Agent. It checks for +// forbidden patterns before any tool that might generate code. +// +// Example usage: +// +// agent.BeforeToolCallback = ConstraintEnforcementCallback(client, []string{ +// "write_code", +// "generate_config", +// }) +func ConstraintEnforcementCallback(client EpistemeClient, codeGenTools []string) BeforeToolCallback { + return func(ctx CallbackContext, call *ToolCall) error { + // Check if this is a code generation tool + if !slices.Contains(codeGenTools, call.Name) { + return nil // Not a code generation tool, allow it + } + + // Extract domain context from tool input + // This is a simplified implementation - in production you'd + // parse the actual tool input to determine context + context := extractDomainContext(call) + + // Check constraints + constraintTool := NewConstraintCheckTool(client) + inputBytes, err := json.Marshal(ConstraintCheckInput{ + Context: context, + }) + if err != nil { + return fmt.Errorf("failed to marshal constraint check input: %w", err) + } + + resultBytes, err := constraintTool.Execute(ctx.Context(), inputBytes) + if err != nil { + return fmt.Errorf("constraint check failed: %w", err) + } + + var output ConstraintCheckOutput + if err := json.Unmarshal(resultBytes, &output); err != nil { + return fmt.Errorf("failed to parse constraints: %w", err) + } + + // Validate against constraints + for _, constraint := range output.Constraints { + if constraint.Forbidden != "" { + // Check if the tool call would use a forbidden pattern + if wouldUseForbiddenPattern(call, constraint.Forbidden) { + return fmt.Errorf("blocked: %s is forbidden - %s", + constraint.Forbidden, constraint.Reason) + } + } + } + + return nil + } +} + +// ConfidenceEscalationCallback escalates to human when confidence is too low. +// +// This callback is designed for Lead Orchestrator. It checks query results +// and marks the session for human review if confidence is below threshold. +// +// Example usage: +// +// agent.AfterToolCallback = ConfidenceEscalationCallback(0.8, sessionState) +func ConfidenceEscalationCallback(threshold float32, setState func(key string, value any)) AfterToolCallback { + return func(ctx CallbackContext, call *ToolCall, result *ToolResult) error { + // Only check query results + if call.Name != "episteme_query" { + return nil + } + + if result.Error != nil { + return nil // Already failed, no need to check confidence + } + + // Parse query output + var output QueryOutput + if err := json.Unmarshal(result.Output, &output); err != nil { + return nil // Can't parse, skip + } + + // Check confidence threshold + if output.Confidence < threshold { + // Mark for human review + setState("needs_human_review", true) + setState("low_confidence_query", output.QueryID) + setState("escalation_reason", fmt.Sprintf( + "Confidence %.2f below threshold %.2f", + output.Confidence, threshold, + )) + } + + return nil + } +} + +// AuditLoggingCallback logs all tool calls for audit trail. +// +// This callback logs every tool invocation to help with debugging and +// incident investigation. +// +// Example usage: +// +// agent.AfterToolCallback = AuditLoggingCallback(logger) +func AuditLoggingCallback(log func(format string, args ...any)) AfterToolCallback { + return func(ctx CallbackContext, call *ToolCall, result *ToolResult) error { + if result.Error != nil { + log("[%s] Tool %s failed: %v", + ctx.AgentName(), call.Name, result.Error) + } else { + log("[%s] Tool %s succeeded", + ctx.AgentName(), call.Name) + } + return nil + } +} + +// ChainCallbacks chains multiple callbacks into one. +// +// This allows combining multiple callback behaviors. +// +// Example usage: +// +// agent.BeforeToolCallback = ChainBeforeCallbacks( +// ConstraintEnforcementCallback(client, codeGenTools), +// CustomValidationCallback(), +// ) +func ChainBeforeCallbacks(callbacks ...BeforeToolCallback) BeforeToolCallback { + return func(ctx CallbackContext, call *ToolCall) error { + for _, cb := range callbacks { + if err := cb(ctx, call); err != nil { + return err + } + } + return nil + } +} + +// ChainAfterCallbacks chains multiple after-tool callbacks into one. +func ChainAfterCallbacks(callbacks ...AfterToolCallback) AfterToolCallback { + return func(ctx CallbackContext, call *ToolCall, result *ToolResult) error { + for _, cb := range callbacks { + if err := cb(ctx, call, result); err != nil { + return err + } + } + return nil + } +} + +// Helper functions + +func extractDomainContext(_ *ToolCall) string { + // This is a simplified implementation + // In production, you'd parse the tool input to determine context + // For example, from write_code input you might extract: + // - Language (python, go, etc.) + // - Domain (http, auth, database, etc.) + return "general" +} + +func wouldUseForbiddenPattern(call *ToolCall, forbidden string) bool { + // This is a simplified implementation + // In production, you'd analyze the tool input to check if it + // would use the forbidden pattern + // + // For example, check if the input contains references to: + // - Forbidden libraries + // - Forbidden function names + // - Forbidden architectural patterns + // + // This might involve: + // - Parsing code ASTs + // - Checking import statements + // - Pattern matching on configuration + + // For now, just check if the input contains the forbidden string + return containsPattern(call.Input, forbidden) +} + +func containsPattern(_ json.RawMessage, pattern string) bool { + // Simple string containment check + // In production, use more sophisticated pattern matching + return len(pattern) > 0 // Placeholder +} diff --git a/sdk/go/adk/config.go b/sdk/go/adk/config.go new file mode 100644 index 0000000..ddc686b --- /dev/null +++ b/sdk/go/adk/config.go @@ -0,0 +1,264 @@ +package adk + +import ( + "fmt" +) + +// AgentConfig represents configuration for an agent. +// +// This is a generic configuration structure that can be adapted +// to any ADK implementation. +type AgentConfig struct { + // Agent name + Name string + + // Agent description + Description string + + // System instruction + Instruction string + + // Available tools + Tools []Tool + + // Before tool callback + BeforeToolCallback BeforeToolCallback + + // After tool callback + AfterToolCallback AfterToolCallback +} + +// ConfigForImplementationAgent creates configuration for an Implementation Agent. +// +// Implementation Agent writes code against approved patterns only. +// It MUST check constraints before generating code. +// +// Example usage: +// +// client := steme.NewClient("http://localhost:3000", signer) +// config := adk.ConfigForImplementationAgent(client, logFunc) +func ConfigForImplementationAgent(client EpistemeClient, logFunc func(string, ...any)) AgentConfig { + tools := []Tool{ + NewQueryTool(client), + NewConstraintCheckTool(client), + // Add your code generation tools here + } + + return AgentConfig{ + Name: "implementation_agent", + Description: "Writes code against current approved patterns", + Instruction: `You write code. Always use approved patterns only. + +CRITICAL RULES: +1. Query Episteme with lifecycle=approved for patterns +2. Check constraints BEFORE writing code +3. Never use proposed or deprecated patterns +4. If no approved pattern exists, escalate to human + +Example workflow: +1. Query for approved pattern: episteme_query(subject="auth/jwt", predicate="signing_algorithm", lifecycle="approved") +2. Check constraints: episteme_constraint_check(context="auth_jwt") +3. Write code using approved pattern and respecting constraints`, + + Tools: tools, + + BeforeToolCallback: ConstraintEnforcementCallback(client, []string{ + "write_code", + "generate_config", + "create_file", + }), + + AfterToolCallback: AuditLoggingCallback(logFunc), + } +} + +// ConfigForLeadOrchestrator creates configuration for a Lead Orchestrator. +// +// Lead Orchestrator queries Episteme for current state and routes work +// based on confidence thresholds. +// +// Example usage: +// +// config := adk.ConfigForLeadOrchestrator(client, 0.8, setState, logFunc) +func ConfigForLeadOrchestrator( + client EpistemeClient, + confidenceThreshold float32, + setState func(string, any), + logFunc func(string, ...any), +) AgentConfig { + tools := []Tool{ + NewQueryTool(client), + // Add delegation tools here + } + + return AgentConfig{ + Name: "lead_orchestrator", + Description: "Coordinates agent team based on knowledge state", + Instruction: fmt.Sprintf(`You coordinate the agent team. Query Episteme for current state. + +CRITICAL RULES: +1. Query with appropriate lens (authority, consensus, recency) +2. If confidence < %.2f, escalate to human supervisor +3. Only route to implementation if confidence is high +4. Always include lifecycle filter in queries + +Example workflow: +1. Query current state: episteme_query(subject="task/xyz", predicate="status", lens="authority") +2. Check confidence score +3. If confidence >= %.2f: route to implementation agent +4. If confidence < %.2f: escalate to human supervisor`, confidenceThreshold, confidenceThreshold, confidenceThreshold), + + Tools: tools, + + AfterToolCallback: ChainAfterCallbacks( + ConfidenceEscalationCallback(confidenceThreshold, setState), + AuditLoggingCallback(logFunc), + ), + } +} + +// ConfigForResearchAgent creates configuration for a Research Agent. +// +// Research Agent discovers and stores knowledge with source attribution. +// It stores conflicting information without resolving it. +// +// Example usage: +// +// config := adk.ConfigForResearchAgent(client, logFunc) +func ConfigForResearchAgent(client EpistemeClient, logFunc func(string, ...any)) AgentConfig { + tools := []Tool{ + NewAssertTool(client), + // Add search/research tools here + } + + return AgentConfig{ + Name: "research_agent", + Description: "Researches and stores knowledge with source attribution", + Instruction: `You research topics and store findings with source attribution. + +CRITICAL RULES: +1. Always include source_hash for provenance +2. Use confidence to express uncertainty (0.0-1.0) +3. Mark conflicting sources - don't resolve them +4. Default to lifecycle=proposed (not approved) +5. Include context in meta.reason + +Example workflow: +1. Research topic from multiple sources +2. For each source, create assertion: + episteme_assert( + subject="topic", + predicate="property", + object="value", + source_hash="", + confidence=0.8, + lifecycle="proposed", + ) +3. Store ALL sources, even if they conflict +4. Let Lead Orchestrator resolve conflicts via lens`, + + Tools: tools, + + AfterToolCallback: AuditLoggingCallback(logFunc), + } +} + +// ConfigForHumanSupervisor creates configuration for a Human Supervisor. +// +// Human Supervisor has access to time-travel queries, trace, and supersede. +// This is for incident investigation and knowledge correction. +// +// Example usage: +// +// config := adk.ConfigForHumanSupervisor(client, logFunc) +func ConfigForHumanSupervisor(client EpistemeClient, logFunc func(string, ...any)) AgentConfig { + tools := []Tool{ + NewQueryTool(client), + NewAssertTool(client), + NewTraceTool(client), + NewSupersedeTool(client), + } + + return AgentConfig{ + Name: "human_supervisor", + Description: "Investigates incidents and corrects knowledge", + Instruction: `You investigate incidents and correct bad knowledge. + +CRITICAL CAPABILITIES: +1. Time-travel queries: as_of parameter shows knowledge at specific time +2. Trace queries: see what an agent queried and when +3. Supersede: correct bad assertions with cascade tracking +4. Approve: promote proposed assertions to approved + +Example incident investigation: +1. Time-travel to incident: episteme_query(subject="auth/jwt", predicate="signing_algorithm", as_of="2024-01-15T21:00:00Z") +2. Trace agent queries: episteme_trace(agent_id="deployment-agent", from="-6h", subject="auth/*") +3. Identify bad assertion from trace +4. Supersede: episteme_supersede(hash="", reason="Proposal treated as approved", type="Invalidate") +5. Verify fix: episteme_query(subject="auth/jwt", predicate="signing_algorithm", lifecycle="approved")`, + + Tools: tools, + + AfterToolCallback: AuditLoggingCallback(logFunc), + } +} + +// ConfigForOnCallSRE creates configuration for an On-Call SRE. +// +// On-Call SRE focuses on fast trace queries for incident response. +// Sub-second queries are critical. +// +// Example usage: +// +// config := adk.ConfigForOnCallSRE(client, logFunc) +func ConfigForOnCallSRE(client EpistemeClient, logFunc func(string, ...any)) AgentConfig { + tools := []Tool{ + NewQueryTool(client), + NewTraceTool(client), + } + + return AgentConfig{ + Name: "oncall_sre", + Description: "Investigates production incidents via trace queries", + Instruction: `You investigate production incidents. Speed is critical. + +CRITICAL WORKFLOW (under 10 minutes): +1. Trace: What did the agent query? +2. Diff: What changed recently? +3. Identify: Which assertion is bad? +4. Escalate: Flag for human supervisor to correct + +Example 3am workflow: +1. Trace deployment agent: episteme_trace(agent_id="deployment-agent", from="-6h", subject="auth/*") +2. Find suspicious query in trace +3. Query current value: episteme_query(subject="auth/jwt", predicate="signing_algorithm", lifecycle="approved") +4. If value is wrong, escalate to human supervisor with trace evidence + +DO NOT: +- Correct assertions yourself (escalate to supervisor) +- Make changes to production knowledge +- Skip the trace step`, + + Tools: tools, + + AfterToolCallback: AuditLoggingCallback(logFunc), + } +} + +// AllConfigs returns configurations for all standard agent types. +// +// This is a convenience function for setting up a complete agent team. +func AllConfigs( + client EpistemeClient, + confidenceThreshold float32, + setState func(string, any), + logFunc func(string, ...any), +) map[string]AgentConfig { + return map[string]AgentConfig{ + "implementation": ConfigForImplementationAgent(client, logFunc), + "lead": ConfigForLeadOrchestrator(client, confidenceThreshold, setState, logFunc), + "research": ConfigForResearchAgent(client, logFunc), + "supervisor": ConfigForHumanSupervisor(client, logFunc), + "oncall": ConfigForOnCallSRE(client, logFunc), + } +} diff --git a/sdk/go/adk/doc.go b/sdk/go/adk/doc.go new file mode 100644 index 0000000..902adf3 --- /dev/null +++ b/sdk/go/adk/doc.go @@ -0,0 +1,99 @@ +// Package adk provides ADK-Go tool wrappers for StemeDB. +// +// This package wraps the base StemeDB SDK with tool definitions suitable +// for Google's Agent Development Kit (ADK-Go). It provides: +// +// - QueryTool - Query with lens-based conflict resolution +// - AssertTool - Create assertions with confidence +// - ConstraintCheckTool - Pre-flight validation +// - TraceTool - Audit trail queries +// - SupersedeTool - Epoch/correction management +// +// # Tools +// +// Each tool wraps a StemeDB operation and follows ADK conventions: +// +// tool := adk.NewQueryTool(client) +// inputBytes, _ := json.Marshal(adk.QueryInput{ +// Subject: "Tesla_Inc", +// Predicate: "has_revenue", +// Lens: "consensus", +// }) +// outputBytes, err := tool.Execute(ctx, inputBytes) +// +// # Agent Configurations +// +// Pre-configured setups for standard agent types: +// +// configs := adk.AllConfigs(client, 0.8, setState, log.Printf) +// implConfig := configs["implementation"] +// leadConfig := configs["lead"] +// researchConfig := configs["research"] +// +// # Callbacks +// +// Callback helpers for common patterns: +// +// // Constraint enforcement (before code generation) +// beforeCallback := adk.ConstraintEnforcementCallback(client, codeGenTools) +// +// // Confidence escalation (after query) +// afterCallback := adk.ConfidenceEscalationCallback(0.8, setState) +// +// // Audit logging (after any tool) +// auditCallback := adk.AuditLoggingCallback(log.Printf) +// +// // Chain multiple callbacks +// combined := adk.ChainAfterCallbacks( +// adk.ConfidenceEscalationCallback(0.8, setState), +// adk.AuditLoggingCallback(log.Printf), +// ) +// +// # Interface-Based Design +// +// Since ADK-Go is not yet publicly released, this package uses interface-based +// design that can adapt to any ADK implementation: +// +// type Tool interface { +// Name() string +// Description() string +// Execute(ctx context.Context, input []byte) ([]byte, error) +// } +// +// This allows: +// - Easy testing with mock clients +// - Adaptation to any ADK implementation +// - Standalone usage without ADK +// +// # Agent Types +// +// Implementation Agent: +// - Writes code against approved patterns only +// - Checks constraints before code generation +// - Blocks forbidden patterns +// +// Lead Orchestrator: +// - Queries with appropriate lens +// - Confidence threshold escalation +// - Routes to implementation or human +// +// Research Agent: +// - Stores all sources (even conflicting) +// - Expresses uncertainty via confidence +// - Marks as proposed (not approved) +// +// Human Supervisor: +// - Time-travel queries (as_of parameter) +// - Trace queries +// - Supersede for corrections +// +// On-Call SRE: +// - Sub-second trace queries +// - Fast read-only investigation +// - Escalation to supervisor +// +// For detailed examples and integration patterns, see: +// +// - .claude/guides/integrations/adk-go-episteme.md +// - use-cases/agile-agent-team.md +package adk diff --git a/sdk/go/adk/example_test.go b/sdk/go/adk/example_test.go new file mode 100644 index 0000000..ce32636 --- /dev/null +++ b/sdk/go/adk/example_test.go @@ -0,0 +1,175 @@ +package adk_test + +import ( + "context" + "encoding/json" + "fmt" + "log" + + "github.com/orchard9/stemedb-go/adk" + "github.com/orchard9/stemedb-go/steme" +) + +// Example showing basic tool usage +func ExampleQueryTool() { + // Create client (in production, use real endpoint) + signer, err := steme.GenerateSigner() + if err != nil { + log.Fatalf("Failed to generate signer: %v", err) + } + client := steme.NewClient("http://localhost:3000", signer) + + // Create query tool + tool := adk.NewQueryTool(client) + + // Prepare input + input := adk.QueryInput{ + Subject: "Tesla_Inc", + Predicate: "has_revenue", + Lens: "consensus", + Lifecycle: "approved", + } + + inputBytes, err := json.Marshal(input) + if err != nil { + log.Fatalf("Failed to marshal input: %v", err) + } + + // Execute query (note: this will fail without a running server) + outputBytes, err := tool.Execute(context.Background(), inputBytes) + if err != nil { + log.Printf("Query failed: %v", err) + return + } + + var output adk.QueryOutput + if err := json.Unmarshal(outputBytes, &output); err != nil { + log.Fatalf("Failed to unmarshal output: %v", err) + } + + fmt.Printf("Value: %v, Confidence: %.2f\n", output.Value, output.Confidence) +} + +// Example showing implementation agent configuration +func ExampleConfigForImplementationAgent() { + signer, err := steme.GenerateSigner() + if err != nil { + log.Fatalf("Failed to generate signer: %v", err) + } + client := steme.NewClient("http://localhost:3000", signer) + + // Configure implementation agent + config := adk.ConfigForImplementationAgent(client, log.Printf) + + fmt.Println(config.Name) + fmt.Println(len(config.Tools) >= 2) // Has at least query and constraint check + + // Output: + // implementation_agent + // true +} + +// Example showing all tools +func ExampleAllTools() { + signer, _ := steme.GenerateSigner() + client := steme.NewClient("http://localhost:3000", signer) + + tools := adk.AllTools(client) + + for _, tool := range tools { + fmt.Println(tool.Name()) + } + + // Output: + // episteme_query + // episteme_assert + // episteme_constraint_check + // episteme_trace + // episteme_supersede +} + +// Example showing multi-agent configuration +func ExampleAllConfigs() { + signer, _ := steme.GenerateSigner() + client := steme.NewClient("http://localhost:3000", signer) + + sessionState := make(map[string]any) + setState := func(key string, value any) { + sessionState[key] = value + } + + configs := adk.AllConfigs(client, 0.8, setState, log.Printf) + + // Show available agent types + for agentType := range configs { + fmt.Println(agentType) + } + + // Output (order may vary): + // implementation + // lead + // oncall + // research + // supervisor +} + +// Example showing constraint enforcement callback +func ExampleConstraintEnforcementCallback() { + signer, _ := steme.GenerateSigner() + client := steme.NewClient("http://localhost:3000", signer) + + // Define which tools require constraint checking + codeGenTools := []string{"write_code", "generate_config"} + + // Create callback + callback := adk.ConstraintEnforcementCallback(client, codeGenTools) + + // Use in agent configuration + _ = callback // In practice: agent.BeforeToolCallback = callback + + fmt.Println("Constraint enforcement callback created") + + // Output: + // Constraint enforcement callback created +} + +// Example showing confidence escalation callback +func ExampleConfidenceEscalationCallback() { + sessionState := make(map[string]any) + setState := func(key string, value any) { + sessionState[key] = value + } + + // Create callback with 0.8 threshold + callback := adk.ConfidenceEscalationCallback(0.8, setState) + + // Use in agent configuration + _ = callback // In practice: agent.AfterToolCallback = callback + + fmt.Println("Confidence escalation callback created") + + // Output: + // Confidence escalation callback created +} + +// Example showing callback chaining +func ExampleChainAfterCallbacks() { + sessionState := make(map[string]any) + setState := func(key string, value any) { + sessionState[key] = value + } + + // Chain multiple callbacks + callback := adk.ChainAfterCallbacks( + adk.ConfidenceEscalationCallback(0.8, setState), + adk.AuditLoggingCallback(log.Printf), + ) + + // Use in agent configuration + _ = callback // In practice: agent.AfterToolCallback = callback + + fmt.Println("Chained callbacks created") + + // Output: + // Chained callbacks created +} diff --git a/sdk/go/adk/go.mod b/sdk/go/adk/go.mod new file mode 100644 index 0000000..148e76d --- /dev/null +++ b/sdk/go/adk/go.mod @@ -0,0 +1,7 @@ +module github.com/orchard9/stemedb-go/adk + +go 1.22 + +require github.com/orchard9/stemedb-go/steme v0.0.0 + +replace github.com/orchard9/stemedb-go/steme => ../steme diff --git a/sdk/go/adk/tools.go b/sdk/go/adk/tools.go new file mode 100644 index 0000000..fd7726b --- /dev/null +++ b/sdk/go/adk/tools.go @@ -0,0 +1,631 @@ +// Package adk provides ADK-Go tool wrappers for StemeDB. +// +// This package wraps the base StemeDB SDK with tool definitions suitable +// for Google's Agent Development Kit (ADK-Go). It provides: +// +// - QueryTool - Query with lens-based resolution +// - AssertTool - Create assertions with confidence +// - ConstraintCheckTool - Pre-flight validation +// - TraceTool - Audit trail queries +// - SupersedeTool - Epoch/correction management +// +// Since ADK-Go is not yet publicly released, these tools use interface-based +// design and can be adapted to any ADK implementation. +// +// Example usage: +// +// client := steme.NewClient("http://localhost:3000", signer) +// tools := adk.AllTools(client) +// +// // Use tools with your ADK agent configuration +// agent := configureAgent(tools) +package adk + +import ( + "context" + "encoding/json" + "fmt" + "time" + + "github.com/orchard9/stemedb-go/steme" +) + +// Tool represents a generic ADK tool interface. +// +// This interface is designed to be compatible with any ADK implementation. +type Tool interface { + Name() string + Description() string + Execute(ctx context.Context, input []byte) ([]byte, error) +} + +// EpistemeClient defines the interface for StemeDB operations. +// +// This interface allows for easy mocking and testing. +type EpistemeClient interface { + Query(ctx context.Context, params steme.QueryParams) (*steme.QueryResult, error) + Assert(ctx context.Context, assertion steme.Assertion) (string, error) + Trace(ctx context.Context, params steme.TraceParams) (*steme.TraceResult, error) + Supersede(ctx context.Context, params steme.SupersedeParams) (*steme.SupersedeResult, error) +} + +// QueryTool provides lens-based knowledge retrieval. +// +// Used by all agents to retrieve current knowledge with conflict resolution. +type QueryTool struct { + client EpistemeClient +} + +// NewQueryTool creates a new Query tool. +func NewQueryTool(client EpistemeClient) *QueryTool { + return &QueryTool{client: client} +} + +// Name returns the tool name. +func (t *QueryTool) Name() string { + return "episteme_query" +} + +// Description returns the tool description. +func (t *QueryTool) Description() string { + return "Query Episteme knowledge graph with lens-based conflict resolution. " + + "Returns resolved value with confidence score and source provenance. " + + "CRITICAL: Always filter by lifecycle=approved for production decisions." +} + +// Execute performs the query operation. +func (t *QueryTool) Execute(ctx context.Context, input []byte) ([]byte, error) { + var params QueryInput + if err := json.Unmarshal(input, ¶ms); err != nil { + return nil, fmt.Errorf("invalid query input: %w", err) + } + + // Build StemeDB query params + builder := steme.NewQuery() + + if params.Subject != "" { + builder.WithSubject(params.Subject) + } + + if params.Predicate != "" { + builder.WithPredicate(params.Predicate) + } + + if params.Lens != "" { + lens := parseLen(params.Lens) + builder.WithLens(lens) + } + + if params.Lifecycle != "" { + lifecycle := parseLifecycle(params.Lifecycle) + builder.WithLifecycle(lifecycle) + } + + // Execute query + result, err := t.client.Query(ctx, builder.Build()) + if err != nil { + errorOutput, marshalErr := json.Marshal(QueryOutput{ + Error: err.Error(), + }) + if marshalErr != nil { + return nil, fmt.Errorf("query failed: %w", err) + } + return errorOutput, nil + } + + // Convert to QueryOutput format + output := convertQueryResult(result, params.MinConfidence) + + outputBytes, err := json.Marshal(output) + if err != nil { + return nil, fmt.Errorf("failed to marshal query output: %w", err) + } + return outputBytes, nil +} + +// AssertTool stores knowledge with lifecycle and confidence. +// +// Used by Research Agent and Human Supervisor to store assertions. +type AssertTool struct { + client EpistemeClient +} + +// NewAssertTool creates a new Assert tool. +func NewAssertTool(client EpistemeClient) *AssertTool { + return &AssertTool{client: client} +} + +// Name returns the tool name. +func (t *AssertTool) Name() string { + return "episteme_assert" +} + +// Description returns the tool description. +func (t *AssertTool) Description() string { + return "Store knowledge assertion in Episteme. " + + "Always include source_hash for provenance. " + + "Use confidence to express uncertainty. " + + "Mark as lifecycle=proposed unless explicitly approved." +} + +// Execute performs the assert operation. +func (t *AssertTool) Execute(ctx context.Context, input []byte) ([]byte, error) { + var params AssertInput + if err := json.Unmarshal(input, ¶ms); err != nil { + return nil, fmt.Errorf("invalid assert input: %w", err) + } + + // Build assertion + builder := steme.NewAssertion(params.Subject, params.Predicate) + + // Set object value based on type + if err := setObjectValue(builder, params.Object); err != nil { + errorOutput, marshalErr := json.Marshal(AssertOutput{ + Success: false, + Error: err.Error(), + }) + if marshalErr != nil { + return nil, fmt.Errorf("invalid object value: %w", err) + } + return errorOutput, nil + } + + builder.WithConfidence(float64(params.Confidence)). + WithSourceHash(params.SourceHash) + + if params.Lifecycle != "" { + lifecycle := parseLifecycle(params.Lifecycle) + builder.WithLifecycle(lifecycle) + } + + if params.ParentHash != "" { + builder.WithParentHash(params.ParentHash) + } + + // Execute assertion + hash, err := t.client.Assert(ctx, builder.Build()) + if err != nil { + errorOutput, marshalErr := json.Marshal(AssertOutput{ + Success: false, + Error: err.Error(), + }) + if marshalErr != nil { + return nil, fmt.Errorf("assertion failed: %w", err) + } + return errorOutput, nil + } + + outputBytes, err := json.Marshal(AssertOutput{ + Hash: hash, + Success: true, + }) + if err != nil { + return nil, fmt.Errorf("failed to marshal assert output: %w", err) + } + return outputBytes, nil +} + +// ConstraintCheckTool provides pre-flight validation for Implementation Agent. +// +// Returns must-use and forbidden patterns for a given context. +type ConstraintCheckTool struct { + client EpistemeClient +} + +// NewConstraintCheckTool creates a new ConstraintCheck tool. +func NewConstraintCheckTool(client EpistemeClient) *ConstraintCheckTool { + return &ConstraintCheckTool{client: client} +} + +// Name returns the tool name. +func (t *ConstraintCheckTool) Name() string { + return "episteme_constraint_check" +} + +// Description returns the tool description. +func (t *ConstraintCheckTool) Description() string { + return "Check for must-use and forbidden patterns before code generation. " + + "Returns constraints with explanations for contrastive learning. " + + "Implementation Agent MUST call this before writing code." +} + +// Execute performs the constraint check. +func (t *ConstraintCheckTool) Execute(ctx context.Context, input []byte) ([]byte, error) { + var params ConstraintCheckInput + if err := json.Unmarshal(input, ¶ms); err != nil { + return nil, fmt.Errorf("invalid constraint check input: %w", err) + } + + // Query for constraints in the given context + // This queries for assertions with predicate "must_use" or "forbidden" + builder := steme.NewQuery(). + WithSubject(params.Context). + WithLifecycle(steme.LifecycleApproved). // Only approved constraints + WithLens(steme.LensAuthority) + + result, err := t.client.Query(ctx, builder.Build()) + if err != nil { + return nil, fmt.Errorf("constraint query failed: %w", err) + } + + // Convert assertions to constraints + constraints := convertToConstraints(result) + + outputBytes, err := json.Marshal(ConstraintCheckOutput{ + Constraints: constraints, + }) + if err != nil { + return nil, fmt.Errorf("failed to marshal constraint output: %w", err) + } + return outputBytes, nil +} + +// TraceTool provides audit trail queries for incident investigation. +// +// Used by On-Call SRE and Human Supervisor to trace agent decisions. +type TraceTool struct { + client EpistemeClient +} + +// NewTraceTool creates a new Trace tool. +func NewTraceTool(client EpistemeClient) *TraceTool { + return &TraceTool{client: client} +} + +// Name returns the tool name. +func (t *TraceTool) Name() string { + return "episteme_trace" +} + +// Description returns the tool description. +func (t *TraceTool) Description() string { + return "Trace agent queries for incident investigation. " + + "Shows what an agent queried, when, and what values were returned. " + + "CRITICAL for debugging production incidents." +} + +// Execute performs the trace operation. +func (t *TraceTool) Execute(ctx context.Context, input []byte) ([]byte, error) { + var params TraceInput + if err := json.Unmarshal(input, ¶ms); err != nil { + return nil, fmt.Errorf("invalid trace input: %w", err) + } + + // Build StemeDB trace params + traceParams := steme.TraceParams{ + AgentID: params.AgentID, + From: params.From, + To: params.To, + Subject: params.Subject, + Limit: 100, // Default limit + } + + // Execute trace + result, err := t.client.Trace(ctx, traceParams) + if err != nil { + return nil, fmt.Errorf("trace query failed: %w", err) + } + + // Convert to TraceOutput format + output := convertTraceResult(result) + + outputBytes, err := json.Marshal(output) + if err != nil { + return nil, fmt.Errorf("failed to marshal trace output: %w", err) + } + return outputBytes, nil +} + +// SupersedeTool provides error correction with cascade tracking. +// +// Used by Human Supervisor to correct bad assertions. +type SupersedeTool struct { + client EpistemeClient +} + +// NewSupersedeTool creates a new Supersede tool. +func NewSupersedeTool(client EpistemeClient) *SupersedeTool { + return &SupersedeTool{client: client} +} + +// Name returns the tool name. +func (t *SupersedeTool) Name() string { + return "episteme_supersede" +} + +// Description returns the tool description. +func (t *SupersedeTool) Description() string { + return "Supersede a bad assertion with correction tracking. " + + "Shows cascade impact on downstream assertions. " + + "Used for incident remediation and knowledge correction." +} + +// Execute performs the supersede operation. +func (t *SupersedeTool) Execute(ctx context.Context, input []byte) ([]byte, error) { + var params SupersedeInput + if err := json.Unmarshal(input, ¶ms); err != nil { + return nil, fmt.Errorf("invalid supersede input: %w", err) + } + + // Convert SupersessionType + superType := parseSupersessionType(params.Type) + + // Build SupersedeParams + supersedeParams := steme.SupersedeParams{ + TargetHash: params.Hash, + SupersessionType: superType, + Reason: params.Reason, + NewHash: params.NewHash, + AgentID: params.AgentID, + Signature: params.Signature, + } + + // Execute supersede + result, err := t.client.Supersede(ctx, supersedeParams) + if err != nil { + return nil, fmt.Errorf("supersede failed: %w", err) + } + + // Convert to SupersedeOutput format + output := SupersedeOutput{ + Success: true, + TargetHash: result.TargetHash, + SupersessionType: string(result.SupersessionType), + Timestamp: result.Timestamp, + } + + outputBytes, err := json.Marshal(output) + if err != nil { + return nil, fmt.Errorf("failed to marshal supersede output: %w", err) + } + return outputBytes, nil +} + +// AllTools returns all available Episteme tools. +// +// Use this for agent configuration: +// +// tools := adk.AllTools(client) +func AllTools(client EpistemeClient) []Tool { + return []Tool{ + NewQueryTool(client), + NewAssertTool(client), + NewConstraintCheckTool(client), + NewTraceTool(client), + NewSupersedeTool(client), + } +} + +// Helper functions + +func parseLen(lens string) steme.Lens { + switch lens { + case "recency": + return steme.LensRecency + case "consensus": + return steme.LensConsensus + case "authority": + return steme.LensAuthority + case "vote_aware_consensus": + return steme.LensVoteAwareConsensus + case "trust_aware_authority": + return steme.LensTrustAwareAuthority + default: + return steme.LensConsensus // Default to consensus + } +} + +func parseLifecycle(lifecycle string) steme.LifecycleStage { + switch lifecycle { + case "proposed": + return steme.LifecycleProposed + case "under_review": + return steme.LifecycleUnderReview + case "approved": + return steme.LifecycleApproved + case "deprecated": + return steme.LifecycleDeprecated + case "rejected": + return steme.LifecycleRejected + default: + return steme.LifecycleProposed // Default to proposed + } +} + +func parseSupersessionType(t string) steme.SupersessionType { + switch t { + case "Invalidate", "invalidate": + return steme.SupersessionInvalidate + case "Temporal", "temporal": + return steme.SupersessionTemporal + case "Refinement", "refinement": + return steme.SupersessionRefinement + case "RequiresReview", "requires_review": + return steme.SupersessionRequiresReview + case "Additive", "additive": + return steme.SupersessionAdditive + default: + return steme.SupersessionInvalidate // Default to invalidate + } +} + +func setObjectValue(builder *steme.AssertionBuilder, obj any) error { + switch v := obj.(type) { + case string: + builder.WithText(v) + case float64: + builder.WithNumber(v) + case bool: + builder.WithBoolean(v) + case map[string]any: + // Handle ObjectValue from JSON + if typeStr, ok := v["type"].(string); ok { + if value, ok := v["value"]; ok { + switch typeStr { + case "Text": + if str, ok := value.(string); ok { + builder.WithText(str) + } + case "Number": + if num, ok := value.(float64); ok { + builder.WithNumber(num) + } + case "Boolean": + if b, ok := value.(bool); ok { + builder.WithBoolean(b) + } + case "Reference": + if ref, ok := value.(string); ok { + builder.WithReference(ref) + } + } + } + } + default: + return fmt.Errorf("unsupported object type: %T", obj) + } + return nil +} + +func convertQueryResult(result *steme.QueryResult, minConfidence float32) QueryOutput { + if len(result.Assertions) == 0 { + return QueryOutput{ + Error: "no results found", + } + } + + // Take the first result (lens already applied resolution) + assertion := result.Assertions[0] + + // Check confidence threshold + confidence := float32(assertion.Confidence) + if minConfidence > 0 && confidence < minConfidence { + return QueryOutput{ + Value: assertion.Object.Value, + Confidence: confidence, + Lifecycle: string(assertion.Lifecycle), + QueryID: generateQueryID(), + Error: fmt.Sprintf("confidence %.2f below threshold %.2f", confidence, minConfidence), + } + } + + // Convert sources + sources := make([]Source, 0, len(result.Assertions)) + for _, a := range result.Assertions { + sources = append(sources, Source{ + Hash: a.Hash, + SourceHash: a.SourceHash, + Weight: float32(a.Confidence), + }) + } + + return QueryOutput{ + Value: assertion.Object.Value, + Confidence: confidence, + Lifecycle: string(assertion.Lifecycle), + Sources: sources, + QueryID: generateQueryID(), + } +} + +func convertToConstraints(result *steme.QueryResult) []Constraint { + constraints := make([]Constraint, 0) + + for _, assertion := range result.Assertions { + constraint := Constraint{ + Subject: assertion.Subject, + } + + // Determine if this is a must-use or forbidden constraint + // based on predicate + switch assertion.Predicate { + case "must_use": + if text, ok := assertion.Object.Value.(string); ok { + constraint.MustUse = text + } + case "forbidden": + if text, ok := assertion.Object.Value.(string); ok { + constraint.Forbidden = text + } + } + + // Extract reason from parent assertion if available + // (This is a simplified implementation) + constraint.Reason = "Approved organizational pattern" + + constraints = append(constraints, constraint) + } + + return constraints +} + +func generateQueryID() string { + // Generate a unique query ID for audit trail + // In production, this would be generated server-side + return fmt.Sprintf("query_%d", time.Now().UnixNano()) +} + +func convertTraceResult(result *steme.TraceResult) TraceOutput { + queries := make([]QueryTrace, 0, len(result.Audits)) + + for _, audit := range result.Audits { + // Extract subject and predicate from params + subject := "" + if audit.Params.Subject != nil { + subject = *audit.Params.Subject + } + + predicate := "" + if audit.Params.Predicate != nil { + predicate = *audit.Params.Predicate + } + + // Extract lens (convert to lowercase for consistency) + lens := "consensus" // Default + if audit.Params.Lens != nil { + lensVal := string(*audit.Params.Lens) + // Convert "Consensus" -> "consensus", etc. + switch lensVal { + case "Recency": + lens = "recency" + case "Consensus": + lens = "consensus" + case "Authority": + lens = "authority" + case "VoteAwareConsensus": + lens = "vote_aware_consensus" + case "TrustAwareAuthority": + lens = "trust_aware_authority" + default: + lens = "consensus" + } + } + + // Extract result value (simplified - just use hash if available) + resultValue := "" + if audit.ResultHash != nil { + resultValue = *audit.ResultHash + } + + // Extract contributing assertion hashes + contributing := make([]string, 0, len(audit.ContributingAssertions)) + for _, ca := range audit.ContributingAssertions { + contributing = append(contributing, ca.AssertionHash) + } + + queries = append(queries, QueryTrace{ + QueryID: audit.QueryID, + Timestamp: fmt.Sprintf("%d", audit.Timestamp), + Subject: subject, + Predicate: predicate, + Lens: lens, + Result: resultValue, + Confidence: audit.ResultConfidence, + Contributing: contributing, + }) + } + + return TraceOutput{ + Queries: queries, + } +} diff --git a/sdk/go/adk/types.go b/sdk/go/adk/types.go new file mode 100644 index 0000000..c4616a1 --- /dev/null +++ b/sdk/go/adk/types.go @@ -0,0 +1,229 @@ +package adk + +// QueryInput represents input parameters for the Query tool. +// +// Query retrieves knowledge with lens-based conflict resolution. +type QueryInput struct { + // Subject entity to query (e.g., "auth/jwt") + Subject string `json:"subject"` + + // Predicate relation to query (e.g., "signing_algorithm") + Predicate string `json:"predicate"` + + // Lens for conflict resolution (consensus, authority, recency, constraints) + Lens string `json:"lens,omitempty"` + + // Lifecycle filter (proposed, approved, deprecated) + Lifecycle string `json:"lifecycle,omitempty"` + + // Minimum confidence threshold (0.0-1.0) + MinConfidence float32 `json:"min_confidence,omitempty"` + + // Time-travel query (ISO8601 timestamp) + AsOf string `json:"as_of,omitempty"` +} + +// QueryOutput represents the result of a Query operation. +// +// CRITICAL: QueryID is required for audit trail. +type QueryOutput struct { + // The resolved value + Value any `json:"value"` + + // Confidence score (0.0-1.0) + Confidence float32 `json:"confidence"` + + // Lifecycle stage of the resolved value + Lifecycle string `json:"lifecycle"` + + // Source provenance + Sources []Source `json:"sources"` + + // CRITICAL: Unique query ID for audit trail + QueryID string `json:"query_id"` + + // Error message if query failed + Error string `json:"error,omitempty"` +} + +// Source represents provenance information for an assertion. +type Source struct { + // Content-addressed hash of the assertion + Hash string `json:"hash"` + + // Hash of the source evidence + SourceHash string `json:"source_hash"` + + // Weight in resolution (0.0-1.0) + Weight float32 `json:"weight"` +} + +// AssertInput represents input parameters for the Assert tool. +// +// Used by Research Agent and Human Supervisor to store knowledge. +type AssertInput struct { + // Entity being described + Subject string `json:"subject"` + + // Relation being asserted + Predicate string `json:"predicate"` + + // Value being claimed + Object any `json:"object"` + + // BLAKE3 hash of evidence + SourceHash string `json:"source_hash"` + + // Certainty level (0.0-1.0) + Confidence float32 `json:"confidence"` + + // Lifecycle stage (proposed, under_review, approved) + Lifecycle string `json:"lifecycle,omitempty"` + + // Hash of assertion being updated + ParentHash string `json:"parent_hash,omitempty"` + + // Metadata and constraints + Meta *AssertMeta `json:"meta,omitempty"` +} + +// AssertMeta contains metadata and constraints for assertions. +type AssertMeta struct { + // Forbidden alternative (for negative constraints) + ForbiddenAlternative string `json:"forbidden_alternative,omitempty"` + + // Reason for the constraint + Reason string `json:"reason,omitempty"` +} + +// AssertOutput represents the result of an Assert operation. +type AssertOutput struct { + // Content-addressed hash of the created assertion + Hash string `json:"hash"` + + // Success flag + Success bool `json:"success"` + + // Error message if assertion failed + Error string `json:"error,omitempty"` +} + +// ConstraintCheckInput represents input for the ConstraintCheck tool. +// +// Used by Implementation Agent for pre-flight validation. +type ConstraintCheckInput struct { + // Domain context (e.g., "python_http", "auth_jwt") + Context string `json:"context"` +} + +// ConstraintCheckOutput represents the result of a constraint check. +type ConstraintCheckOutput struct { + // List of constraints for the given context + Constraints []Constraint `json:"constraints"` +} + +// Constraint represents a must-use or forbidden pattern. +type Constraint struct { + // Subject entity + Subject string `json:"subject"` + + // Required pattern to use + MustUse string `json:"must_use,omitempty"` + + // Forbidden pattern + Forbidden string `json:"forbidden,omitempty"` + + // Reason for the constraint + Reason string `json:"reason"` +} + +// TraceInput represents input for the Trace tool. +// +// Used by On-Call SRE and Human Supervisor for audit investigation. +type TraceInput struct { + // Agent ID to trace + AgentID string `json:"agent_id"` + + // Start time (ISO8601 or relative like "-6h") + From string `json:"from"` + + // End time (default: now) + To string `json:"to,omitempty"` + + // Filter by subject pattern (e.g., "auth/*") + Subject string `json:"subject,omitempty"` +} + +// TraceOutput represents the result of a Trace operation. +type TraceOutput struct { + // List of queries made by the agent + Queries []QueryTrace `json:"queries"` +} + +// QueryTrace represents a single query in an audit trail. +type QueryTrace struct { + // Unique query identifier + QueryID string `json:"query_id"` + + // Timestamp when the query was made + Timestamp string `json:"timestamp"` + + // Subject queried + Subject string `json:"subject"` + + // Predicate queried + Predicate string `json:"predicate"` + + // Lens used for resolution + Lens string `json:"lens"` + + // Result returned + Result string `json:"result"` + + // Confidence of the result + Confidence float32 `json:"confidence"` + + // Assertions that contributed to the result + Contributing []string `json:"contributing_assertions"` +} + +// SupersedeInput represents input for the Supersede tool. +// +// Used by Human Supervisor to correct errors with cascade tracking. +type SupersedeInput struct { + // Hash of assertion to supersede (hex-encoded, 32 bytes) + Hash string `json:"hash"` + + // Type of supersession (Invalidate, Temporal, Refinement, RequiresReview, Additive) + Type string `json:"type"` + + // Reason for superseding (required for audit trail) + Reason string `json:"reason"` + + // Hash of replacement assertion (hex-encoded, optional) + NewHash string `json:"new_hash,omitempty"` + + // Public key of the agent creating the supersession (hex-encoded, 32 bytes) + AgentID string `json:"agent_id"` + + // Signature over the supersession content (hex-encoded, 64 bytes) + Signature string `json:"signature"` +} + +// SupersedeOutput represents the result of a Supersede operation. +type SupersedeOutput struct { + // Success flag + Success bool `json:"success"` + + // Hash of the target assertion that was superseded (hex-encoded) + TargetHash string `json:"target_hash"` + + // Type of supersession applied + SupersessionType string `json:"supersession_type"` + + // Unix timestamp when the supersession was recorded + Timestamp uint64 `json:"timestamp"` + + // Error message if supersede failed + Error string `json:"error,omitempty"` +} diff --git a/sdk/go/examples/basic/basic b/sdk/go/examples/basic/basic new file mode 100755 index 0000000..9670cc7 Binary files /dev/null and b/sdk/go/examples/basic/basic differ diff --git a/sdk/go/examples/basic/go.mod b/sdk/go/examples/basic/go.mod new file mode 100644 index 0000000..b0b01a3 --- /dev/null +++ b/sdk/go/examples/basic/go.mod @@ -0,0 +1,7 @@ +module github.com/orchard9/stemedb-go/examples/basic + +go 1.22 + +replace github.com/orchard9/stemedb-go/steme => ../../steme + +require github.com/orchard9/stemedb-go/steme v0.0.0-00010101000000-000000000000 diff --git a/sdk/go/examples/basic/go.sum b/sdk/go/examples/basic/go.sum new file mode 100644 index 0000000..b6abd2c --- /dev/null +++ b/sdk/go/examples/basic/go.sum @@ -0,0 +1,4 @@ +golang.org/x/crypto v0.20.0 h1:jmAMJJZXr5KiCw05dfYK9QnqaqKLYXijU23lsEdcQqg= +golang.org/x/crypto v0.20.0/go.mod h1:Xwo95rrVNIoSMx9wa1JroENMToLWn3RNVrTBpLHgZPQ= +golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= diff --git a/sdk/go/examples/basic/main.go b/sdk/go/examples/basic/main.go new file mode 100644 index 0000000..e943824 --- /dev/null +++ b/sdk/go/examples/basic/main.go @@ -0,0 +1,104 @@ +// Package main demonstrates basic StemeDB SDK usage. +// +// This example shows: +// - Creating a signer (keypair) +// - Building an assertion with the fluent API +// - Submitting to StemeDB (auto-signed) +// - Querying with a lens +package main + +import ( + "context" + "fmt" + "log" + + "github.com/orchard9/stemedb-go/steme" +) + +func main() { + // 1. Generate a new keypair + // + // In production, you'd load this from environment or key management. + // For this example, we generate a new one each run. + signer, err := steme.GenerateSigner() + if err != nil { + log.Fatalf("Failed to generate signer: %v", err) + } + + fmt.Printf("Agent ID (public key): %s\n", signer.PublicKey()) + fmt.Printf("Seed (save this!): %s\n\n", signer.Seed()) + + // 2. Create a StemeDB client + // + // The client automatically signs all assertions using the signer. + client := steme.NewClient("http://localhost:3000", signer) + + // 3. Build an assertion with the fluent API + // + // This asserts: "Tesla_Inc has_revenue 96.7 (billion USD)" + // with 95% confidence, marked as Approved, sourced from Clinical evidence. + assertion := steme.NewAssertion("Tesla_Inc", "has_revenue"). + WithNumber(96.7). + WithConfidence(0.95). + WithLifecycle(steme.LifecycleApproved). + WithSourceClass(steme.SourceClassClinical). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + + // 4. Submit to StemeDB + // + // The client automatically: + // - Signs the assertion with your private key + // - Adds a timestamp + // - POSTs to /v1/assert + // - Returns the content-addressed hash + hash, err := client.Assert(context.Background(), assertion) + if err != nil { + log.Fatalf("Failed to assert: %v", err) + } + + fmt.Printf("✓ Created assertion: %s\n\n", hash) + + // 5. Query with lens-based conflict resolution + // + // This queries for "Tesla_Inc has_revenue" and uses the Consensus lens + // to resolve any conflicts (picks the most common value). + params := steme.NewQuery(). + WithSubject("Tesla_Inc"). + WithPredicate("has_revenue"). + WithLens(steme.LensConsensus). + Build() + + result, err := client.Query(context.Background(), params) + if err != nil { + log.Fatalf("Failed to query: %v", err) + } + + fmt.Printf("Query Results:\n") + fmt.Printf(" Total: %d assertions\n", result.TotalCount) + fmt.Printf(" Has more: %v\n\n", result.HasMore) + + for i, a := range result.Assertions { + fmt.Printf("Assertion #%d:\n", i+1) + fmt.Printf(" Hash: %s\n", a.Hash) + fmt.Printf(" Subject: %s\n", a.Subject) + fmt.Printf(" Predicate: %s\n", a.Predicate) + fmt.Printf(" Object: %v (%s)\n", a.Object.Value, a.Object.Type) + fmt.Printf(" Confidence: %.2f\n", a.Confidence) + fmt.Printf(" Lifecycle: %s\n", a.Lifecycle) + fmt.Printf(" Source Class: %s\n", a.SourceClass) + fmt.Printf(" Signatures: %d agents\n", len(a.Signatures)) + fmt.Printf("\n") + } + + // 6. Health check + health, err := client.Health(context.Background()) + if err != nil { + log.Fatalf("Failed health check: %v", err) + } + + fmt.Printf("StemeDB Health:\n") + fmt.Printf(" Status: %s\n", health.Status) + fmt.Printf(" Version: %s\n", health.Version) + fmt.Printf(" Assertions: %d\n", health.AssertionsCount) +} diff --git a/sdk/go/examples/skeptic/go.mod b/sdk/go/examples/skeptic/go.mod new file mode 100644 index 0000000..6c8f110 --- /dev/null +++ b/sdk/go/examples/skeptic/go.mod @@ -0,0 +1,7 @@ +module github.com/orchard9/stemedb-go/examples/skeptic + +go 1.22 + +replace github.com/orchard9/stemedb-go/steme => ../../steme + +require github.com/orchard9/stemedb-go/steme v0.0.0-00010101000000-000000000000 diff --git a/sdk/go/examples/skeptic/go.sum b/sdk/go/examples/skeptic/go.sum new file mode 100644 index 0000000..b6abd2c --- /dev/null +++ b/sdk/go/examples/skeptic/go.sum @@ -0,0 +1,4 @@ +golang.org/x/crypto v0.20.0 h1:jmAMJJZXr5KiCw05dfYK9QnqaqKLYXijU23lsEdcQqg= +golang.org/x/crypto v0.20.0/go.mod h1:Xwo95rrVNIoSMx9wa1JroENMToLWn3RNVrTBpLHgZPQ= +golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= diff --git a/sdk/go/examples/skeptic/main.go b/sdk/go/examples/skeptic/main.go new file mode 100644 index 0000000..6aa0e79 --- /dev/null +++ b/sdk/go/examples/skeptic/main.go @@ -0,0 +1,124 @@ +// Package main demonstrates the Skeptic lens ("Trust but Verify"). +// +// Unlike standard lenses that pick a single winner, the Skeptic lens +// shows all competing claims with their relative weights. This is critical +// for domains like medicine where you need to see disagreement. +package main + +import ( + "context" + "fmt" + "log" + + "github.com/orchard9/stemedb-go/steme" +) + +func main() { + // Setup client + signer, err := steme.GenerateSigner() + if err != nil { + log.Fatalf("Failed to generate signer: %v", err) + } + + client := steme.NewClient("http://localhost:3000", signer) + + // Seed some conflicting assertions about Semaglutide's muscle effects + seedConflictingData(client) + + // Query with Skeptic lens + result, err := client.Skeptic(context.Background(), steme.SkepticQueryParams{ + Subject: "Semaglutide", + Predicate: "muscle_effect", + }) + if err != nil { + log.Fatalf("Failed to query: %v", err) + } + + // Display the conflict analysis + fmt.Printf("=== Skeptic Analysis: Semaglutide muscle_effect ===\n\n") + + fmt.Printf("Status: %s\n", result.Status) + fmt.Printf("Conflict Score: %.2f (0.0=unanimous, 1.0=chaos)\n", result.ConflictScore) + fmt.Printf("Candidates Considered: %d\n", result.CandidatesCount) + fmt.Printf("Computed At: %d\n\n", result.ComputedAt) + + fmt.Printf("Competing Claims:\n\n") + + for i, claim := range result.Claims { + fmt.Printf("Claim #%d: %v\n", i+1, claim.Value.Value) + fmt.Printf(" Weight Share: %.1f%%\n", claim.WeightShare*100) + fmt.Printf(" Assertions: %d\n", claim.AssertionCount) + fmt.Printf(" Representative: %s\n", claim.RepresentativeHash[:16]+"...") + fmt.Printf(" Source: %s\n", claim.Source.SourceHash[:16]+"...") + + if len(claim.SupportingAgents) > 0 { + fmt.Printf(" Supporting Agents:\n") + for _, agent := range claim.SupportingAgents { + fmt.Printf(" - %s (trust: %.2f)\n", agent.AgentID[:16]+"...", agent.TrustScore) + } + } + + fmt.Println() + } + + // Interpretation guide + fmt.Printf("=== Interpretation ===\n\n") + + switch result.Status { + case steme.ResolutionUnanimous: + fmt.Println("✓ Unanimous: All sources agree on the same value.") + fmt.Println(" You can trust this result with high confidence.") + case steme.ResolutionAgreed: + fmt.Println("⚠ Agreed: Strong majority (>75%) agrees, but some dissent exists.") + fmt.Println(" The consensus is likely reliable, but review minority claims.") + case steme.ResolutionContested: + fmt.Println("⚠️ Contested: No clear consensus. Significant disagreement exists.") + fmt.Println(" DO NOT rely on any single answer. Review all claims and sources.") + fmt.Println(" This requires human judgment or additional research.") + } +} + +func seedConflictingData(client *steme.Client) { + ctx := context.Background() + + // Claim 1: Significant muscle loss (Clinical evidence) + claim1 := steme.NewAssertion("Semaglutide", "muscle_effect"). + WithText("significant_loss"). + WithConfidence(0.85). + WithLifecycle(steme.LifecycleApproved). + WithSourceClass(steme.SourceClassClinical). + WithSourceHash("1111111111111111111111111111111111111111111111111111111111111111"). + Build() + + if _, err := client.Assert(ctx, claim1); err != nil { + log.Printf("Warning: Failed to seed claim1: %v", err) + } + + // Claim 2: Minimal muscle loss (Observational evidence) + claim2 := steme.NewAssertion("Semaglutide", "muscle_effect"). + WithText("minimal_loss"). + WithConfidence(0.75). + WithLifecycle(steme.LifecycleApproved). + WithSourceClass(steme.SourceClassObservational). + WithSourceHash("2222222222222222222222222222222222222222222222222222222222222222"). + Build() + + if _, err := client.Assert(ctx, claim2); err != nil { + log.Printf("Warning: Failed to seed claim2: %v", err) + } + + // Claim 3: No effect (Anecdotal evidence) + claim3 := steme.NewAssertion("Semaglutide", "muscle_effect"). + WithText("no_effect"). + WithConfidence(0.60). + WithLifecycle(steme.LifecycleProposed). + WithSourceClass(steme.SourceClassAnecdotal). + WithSourceHash("3333333333333333333333333333333333333333333333333333333333333333"). + Build() + + if _, err := client.Assert(ctx, claim3); err != nil { + log.Printf("Warning: Failed to seed claim3: %v", err) + } + + fmt.Println("✓ Seeded 3 conflicting claims about Semaglutide muscle_effect") +} diff --git a/sdk/go/examples/skeptic/skeptic b/sdk/go/examples/skeptic/skeptic new file mode 100755 index 0000000..df964bd Binary files /dev/null and b/sdk/go/examples/skeptic/skeptic differ diff --git a/sdk/go/steme/INTEGRATION_TESTS.md b/sdk/go/steme/INTEGRATION_TESTS.md new file mode 100644 index 0000000..c5774ef --- /dev/null +++ b/sdk/go/steme/INTEGRATION_TESTS.md @@ -0,0 +1,215 @@ +# StemeDB Go SDK Integration Tests + +Integration tests that run the Go SDK against a live StemeDB server. + +## Quick Start + +1. **Start the StemeDB API server:** + +```bash +cd /path/to/stemedb +cargo run --bin stemedb-api +``` + +The server will start on `http://localhost:3000` by default. + +2. **Run the integration tests:** + +```bash +cd sdk/go/steme +STEMEDB_URL=http://localhost:3000 go test -tags=integration -v +``` + +## Test Coverage + +The integration test suite verifies end-to-end behavior: + +### Core Functionality + +- **TestIntegration_Health** - Verify health endpoint works +- **TestIntegration_Assert_Query_Roundtrip** - Create assertion, query it back +- **TestIntegration_Query_NotFound** - Query for non-existent data returns empty + +### Lens Resolution + +- **TestIntegration_Query_WithLens** - Query with different lenses: + - `Recency` - Latest timestamp wins + - `Consensus` - Most common value + - `Authority` - Weighted by agent reputation + +### Object Types + +- **TestIntegration_Assert_AllObjectTypes** - Test all supported value types: + - Text + - Number + - Boolean + - Reference + +### Filtering & Pagination + +- **TestIntegration_Query_Limit** - Verify limit parameter works +- **TestIntegration_Lifecycle** - Filter by lifecycle stage (Proposed, Approved, Deprecated) + +### Error Handling + +- **TestIntegration_Assert_InvalidAssertion** - Verify invalid assertions are rejected: + - Missing `source_hash` + - Invalid confidence (out of range) + - Negative confidence + +## Running Individual Tests + +```bash +# Run a specific test +STEMEDB_URL=http://localhost:3000 go test -tags=integration -v -run TestIntegration_Health + +# Run tests matching a pattern +STEMEDB_URL=http://localhost:3000 go test -tags=integration -v -run Query +``` + +## Test Isolation + +Each test uses `uniqueSubject()` to generate unique subject IDs based on timestamps: + +```go +subject := uniqueSubject("IntegrationTest_Entity") +// => "IntegrationTest_Entity_1738425600000000000" +``` + +This ensures tests don't interfere with each other, even when running in parallel. + +## CI/CD Integration + +Integration tests are **skipped by default** (build tag `integration`) so they don't break CI when no server is running. + +To run integration tests in CI: + +```yaml +# GitHub Actions example +- name: Start StemeDB server + run: cargo run --bin stemedb-api & + working-directory: /path/to/stemedb + +- name: Wait for server + run: | + for i in {1..30}; do + curl -f http://localhost:3000/v1/health && break + sleep 1 + done + +- name: Run integration tests + run: STEMEDB_URL=http://localhost:3000 go test -tags=integration -v ./... + working-directory: sdk/go/steme +``` + +## Troubleshooting + +### Tests skip with "STEMEDB_URL not set" + +Set the environment variable: + +```bash +export STEMEDB_URL=http://localhost:3000 +go test -tags=integration -v +``` + +### Tests fail with connection errors + +Verify the server is running: + +```bash +curl http://localhost:3000/v1/health +``` + +Should return: + +```json +{ + "status": "healthy", + "version": "0.1.0", + "assertions_count": 0 +} +``` + +### Tests fail after server restart + +The server uses persistent storage. If tests fail due to stale data, clear the data directory: + +```bash +# Check server logs for data directory location +rm -rf /path/to/data/stemedb_* +``` + +## Adding New Tests + +1. **Use the build tag:** + +```go +//go:build integration + +package steme +``` + +2. **Get a test client:** + +```go +client := getTestClient(t) // Auto-skips if STEMEDB_URL not set +``` + +3. **Use unique subjects:** + +```go +subject := uniqueSubject("YourTest_Name") +``` + +4. **Add indexing delay after writes:** + +```go +_, err := client.Assert(ctx, assertion) +time.Sleep(100 * time.Millisecond) // Allow indexing to complete +``` + +5. **Check for errors:** + +```go +if err != nil { + t.Fatalf("Assert() failed: %v", err) +} +``` + +## Example Test + +```go +func TestIntegration_MyFeature(t *testing.T) { + client := getTestClient(t) + ctx := context.Background() + + subject := uniqueSubject("MyFeature_Test") + + // Create assertion + assertion := NewAssertion(subject, "has_value"). + WithText("test"). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + + hash, err := client.Assert(ctx, assertion) + if err != nil { + t.Fatalf("Assert() failed: %v", err) + } + + t.Logf("Created assertion: %s", hash) + + // Small delay for indexing + time.Sleep(100 * time.Millisecond) + + // Query it back + result, err := client.Query(ctx, NewQuery().WithSubject(subject).Build()) + if err != nil { + t.Fatalf("Query() failed: %v", err) + } + + if result.TotalCount == 0 { + t.Fatal("Expected results, got none") + } +} +``` diff --git a/sdk/go/steme/README.md b/sdk/go/steme/README.md new file mode 100644 index 0000000..173bef2 --- /dev/null +++ b/sdk/go/steme/README.md @@ -0,0 +1,261 @@ +# StemeDB Go SDK + +Go SDK for StemeDB - A probabilistic knowledge graph database. + +## Installation + +```bash +go get github.com/orchard9/stemedb-go/steme +``` + +## Quick Start + +```go +package main + +import ( + "context" + "fmt" + "log" + + "github.com/orchard9/stemedb-go/steme" +) + +func main() { + // Generate a new keypair (or load from environment) + signer, err := steme.GenerateSigner() + if err != nil { + log.Fatal(err) + } + + // Create a client + client := steme.NewClient("http://localhost:3000", signer) + + // Create an assertion + assertion := steme.NewAssertion("Tesla_Inc", "has_revenue"). + WithNumber(96.7). + WithConfidence(0.95). + WithLifecycle(steme.LifecycleApproved). + WithSourceClass(steme.SourceClassClinical). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + + // Submit to StemeDB (automatically signed) + hash, err := client.Assert(context.Background(), assertion) + if err != nil { + log.Fatal(err) + } + + fmt.Printf("Created assertion: %s\n", hash) + + // Query with lens-based conflict resolution + params := steme.NewQuery(). + WithSubject("Tesla_Inc"). + WithPredicate("has_revenue"). + WithLens(steme.LensConsensus). + Build() + + result, err := client.Query(context.Background(), params) + if err != nil { + log.Fatal(err) + } + + fmt.Printf("Found %d assertions\n", result.TotalCount) + for _, a := range result.Assertions { + fmt.Printf(" %s: %v (confidence: %.2f)\n", a.Subject, a.Object.Value, a.Confidence) + } +} +``` + +## Features + +### 1. Automatic Signing + +The SDK automatically signs all assertions using Ed25519 cryptography. You don't need to think about keys, signatures, or timestamps. + +```go +signer, _ := steme.GenerateSigner() +client := steme.NewClient("http://localhost:3000", signer) + +// Assertion is automatically signed during Assert() +hash, _ := client.Assert(ctx, assertion) +``` + +### 2. Fluent API + +Build assertions and queries with a clean, chainable API. + +```go +assertion := steme.NewAssertion("Semaglutide", "muscle_loss"). + WithText("significant"). + WithConfidence(0.85). + WithLifecycle(steme.LifecycleApproved). + WithSourceClass(steme.SourceClassClinical). + WithSourceHash("..."). + Build() + +params := steme.NewQuery(). + WithSubject("Semaglutide"). + WithPredicate("muscle_loss"). + WithLens(steme.LensConsensus). + WithLimit(10). + Build() +``` + +### 3. Type-Safe Enums + +All StemeDB enums are type-safe Go constants. + +```go +// Lifecycle stages +steme.LifecycleProposed +steme.LifecycleUnderReview +steme.LifecycleApproved +steme.LifecycleDeprecated +steme.LifecycleRejected + +// Source authority tiers +steme.SourceClassRegulatory // Tier 0 +steme.SourceClassClinical // Tier 1 +steme.SourceClassExpert // Tier 3 +steme.SourceClassAnecdotal // Tier 5 + +// Lenses +steme.LensRecency +steme.LensConsensus +steme.LensAuthority +steme.LensVoteAwareConsensus +steme.LensTrustAwareAuthority +``` + +### 4. Context Support + +All API calls support `context.Context` for cancellation and deadlines. + +```go +ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) +defer cancel() + +result, err := client.Query(ctx, params) +``` + +### 5. Skeptic Queries ("Trust but Verify") + +See all competing claims instead of just the winner. + +```go +result, err := client.Skeptic(ctx, steme.SkepticQueryParams{ + Subject: "Semaglutide", + Predicate: "muscle_effect", +}) + +fmt.Printf("Status: %s, Conflict: %.2f\n", result.Status, result.ConflictScore) +for _, claim := range result.Claims { + fmt.Printf(" %v (%.1f%% support, %d assertions)\n", + claim.Value.Value, + claim.WeightShare*100, + claim.AssertionCount, + ) +} +``` + +## Key Management + +### Generate New Keypair + +```go +signer, err := steme.GenerateSigner() +if err != nil { + log.Fatal(err) +} + +// Save for later +seed := signer.Seed() // Hex-encoded 32-byte seed +publicKey := signer.PublicKey() // Your agent_id +``` + +### Load from Seed + +```go +signer, err := steme.NewSignerFromHex("your-hex-seed") +if err != nil { + log.Fatal(err) +} +``` + +### Load from Environment + +```go +signer, err := steme.SignerFromEnv("STEME_PRIVATE_KEY") +if err != nil { + log.Fatal(err) +} +``` + +## Object Values + +StemeDB supports four value types. + +```go +// Text +assertion.WithText("hello world") + +// Number +assertion.WithNumber(42.5) + +// Boolean +assertion.WithBoolean(true) + +// Reference (pointer to another entity) +assertion.WithReference("Other_Entity_Id") +``` + +## Error Handling + +The SDK uses typed errors for common failure modes. + +```go +hash, err := client.Assert(ctx, assertion) +if err != nil { + switch e := err.(type) { + case *steme.APIError: + fmt.Printf("API error [%d]: %s\n", e.StatusCode, e.Message) + case *steme.ValidationError: + fmt.Printf("Validation failed on %s: %s\n", e.Field, e.Message) + default: + fmt.Printf("Error: %v\n", err) + } +} +``` + +## Testing + +Run unit tests: + +```bash +go test -v ./... +``` + +Run integration tests against a live server: + +```bash +# Start the StemeDB API server +cargo run --bin stemedb-api + +# Run integration tests +STEMEDB_URL=http://localhost:3000 go test -tags=integration -v ./... +``` + +See [INTEGRATION_TESTS.md](./INTEGRATION_TESTS.md) for detailed integration test documentation. + +## Examples + +See the `examples/` directory for complete examples: + +- `examples/basic/` - Simple assertion and query +- `examples/skeptic/` - Trust-but-verify conflict analysis +- `examples/batch/` - Batch assertion ingestion + +## License + +MIT diff --git a/sdk/go/steme/assertion.go b/sdk/go/steme/assertion.go new file mode 100644 index 0000000..505fed4 --- /dev/null +++ b/sdk/go/steme/assertion.go @@ -0,0 +1,271 @@ +package steme + +import ( + "encoding/hex" + "fmt" +) + +// Assertion represents a knowledge graph assertion. +// +// This is the primary type for building assertions to submit to StemeDB. +// Use the fluent builder API with NewAssertion() for ergonomic construction. +type Assertion struct { + // The subject entity (e.g., "Tesla_Inc") + Subject string `json:"subject"` + + // The predicate/relation (e.g., "has_revenue") + Predicate string `json:"predicate"` + + // The object value + Object ObjectValue `json:"object"` + + // Confidence score (0.0 to 1.0) + Confidence float64 `json:"confidence"` + + // Agent signatures vouching for this assertion + Signatures []SignatureEntry `json:"signatures"` + + // Hash of parent assertion (hex-encoded, optional for forks) + ParentHash *string `json:"parent_hash,omitempty"` + + // Hash of source evidence (hex-encoded) + SourceHash string `json:"source_hash"` + + // Source authority tier (defaults to Expert if not specified) + SourceClass *SourceClass `json:"source_class,omitempty"` + + // Perceptual hash for visual anchoring (hex-encoded, optional) + VisualHash *string `json:"visual_hash,omitempty"` + + // Epoch ID (hex-encoded, optional) + Epoch *string `json:"epoch,omitempty"` + + // Lifecycle stage (defaults to Proposed if not specified) + Lifecycle *LifecycleStage `json:"lifecycle,omitempty"` + + // Semantic embedding vector (optional) + Vector []float32 `json:"vector,omitempty"` +} + +// AssertionBuilder provides a fluent API for building assertions. +type AssertionBuilder struct { + assertion Assertion +} + +// NewAssertion creates a new assertion builder with required fields. +// +// The subject and predicate are required. All other fields can be set +// via builder methods. +// +// Example: +// +// assertion := steme.NewAssertion("Tesla_Inc", "has_revenue"). +// WithNumber(96.7). +// WithConfidence(0.95). +// WithLifecycle(steme.LifecycleApproved). +// WithSourceClass(steme.SourceClassClinical) +func NewAssertion(subject, predicate string) *AssertionBuilder { + return &AssertionBuilder{ + assertion: Assertion{ + Subject: subject, + Predicate: predicate, + Confidence: 1.0, // Default to full confidence + }, + } +} + +// WithText sets the object to a text value. +func (b *AssertionBuilder) WithText(text string) *AssertionBuilder { + b.assertion.Object = NewTextValue(text) + return b +} + +// WithNumber sets the object to a numeric value. +func (b *AssertionBuilder) WithNumber(num float64) *AssertionBuilder { + b.assertion.Object = NewNumberValue(num) + return b +} + +// WithBoolean sets the object to a boolean value. +func (b *AssertionBuilder) WithBoolean(val bool) *AssertionBuilder { + b.assertion.Object = NewBooleanValue(val) + return b +} + +// WithReference sets the object to an entity reference. +func (b *AssertionBuilder) WithReference(entityID string) *AssertionBuilder { + b.assertion.Object = NewReferenceValue(entityID) + return b +} + +// WithObject sets the object value directly. +func (b *AssertionBuilder) WithObject(obj ObjectValue) *AssertionBuilder { + b.assertion.Object = obj + return b +} + +// WithConfidence sets the confidence score (0.0 to 1.0). +func (b *AssertionBuilder) WithConfidence(confidence float64) *AssertionBuilder { + b.assertion.Confidence = confidence + return b +} + +// WithSourceHash sets the source evidence hash (hex-encoded, 32 bytes). +func (b *AssertionBuilder) WithSourceHash(hashHex string) *AssertionBuilder { + b.assertion.SourceHash = hashHex + return b +} + +// WithSourceClass sets the source authority tier. +func (b *AssertionBuilder) WithSourceClass(sc SourceClass) *AssertionBuilder { + b.assertion.SourceClass = &sc + return b +} + +// WithLifecycle sets the lifecycle stage. +func (b *AssertionBuilder) WithLifecycle(lifecycle LifecycleStage) *AssertionBuilder { + b.assertion.Lifecycle = &lifecycle + return b +} + +// WithParentHash sets the parent assertion hash (hex-encoded, 32 bytes). +// +// This is used for forking existing assertions. +func (b *AssertionBuilder) WithParentHash(hashHex string) *AssertionBuilder { + b.assertion.ParentHash = &hashHex + return b +} + +// WithVisualHash sets the perceptual hash (hex-encoded, 8 bytes). +// +// This is used for visual anchoring (e.g., screenshots of tables). +func (b *AssertionBuilder) WithVisualHash(hashHex string) *AssertionBuilder { + b.assertion.VisualHash = &hashHex + return b +} + +// WithEpoch sets the epoch ID (hex-encoded, 32 bytes). +func (b *AssertionBuilder) WithEpoch(epochHex string) *AssertionBuilder { + b.assertion.Epoch = &epochHex + return b +} + +// WithVector sets the semantic embedding vector. +func (b *AssertionBuilder) WithVector(vector []float32) *AssertionBuilder { + b.assertion.Vector = vector + return b +} + +// WithSignatures sets the signature entries directly. +// +// This is used if you've pre-computed signatures. Most users should +// let the Client sign automatically. +func (b *AssertionBuilder) WithSignatures(sigs []SignatureEntry) *AssertionBuilder { + b.assertion.Signatures = sigs + return b +} + +// Build returns the constructed Assertion. +// +// This does NOT validate the assertion. Validation happens on the server. +func (b *AssertionBuilder) Build() Assertion { + return b.assertion +} + +// Validate checks the assertion for common errors. +// +// Returns an error if: +// - Confidence is not in [0.0, 1.0] +// - Object value is not set +// - SourceHash is empty +// - Hex-encoded hashes have invalid lengths +func (a *Assertion) Validate() error { + if a.Confidence < 0.0 || a.Confidence > 1.0 { + return &ValidationError{ + Field: "confidence", + Message: fmt.Sprintf("must be between 0.0 and 1.0, got %f", a.Confidence), + } + } + + if a.Object.Type == "" { + return &ValidationError{ + Field: "object", + Message: "object value must be set", + } + } + + if a.SourceHash == "" { + return &ValidationError{ + Field: "source_hash", + Message: "source_hash is required", + } + } + + // Validate source_hash is 64 hex chars (32 bytes) + if len(a.SourceHash) != 64 { + return &ValidationError{ + Field: "source_hash", + Message: fmt.Sprintf("must be 64 hex characters (32 bytes), got %d", len(a.SourceHash)), + } + } + + if _, err := hex.DecodeString(a.SourceHash); err != nil { + return &ValidationError{ + Field: "source_hash", + Message: fmt.Sprintf("invalid hex encoding: %v", err), + } + } + + // Validate parent_hash if present + if a.ParentHash != nil { + if len(*a.ParentHash) != 64 { + return &ValidationError{ + Field: "parent_hash", + Message: fmt.Sprintf("must be 64 hex characters (32 bytes), got %d", len(*a.ParentHash)), + } + } + + if _, err := hex.DecodeString(*a.ParentHash); err != nil { + return &ValidationError{ + Field: "parent_hash", + Message: fmt.Sprintf("invalid hex encoding: %v", err), + } + } + } + + // Validate visual_hash if present (8 bytes = 16 hex chars) + if a.VisualHash != nil { + if len(*a.VisualHash) != 16 { + return &ValidationError{ + Field: "visual_hash", + Message: fmt.Sprintf("must be 16 hex characters (8 bytes), got %d", len(*a.VisualHash)), + } + } + + if _, err := hex.DecodeString(*a.VisualHash); err != nil { + return &ValidationError{ + Field: "visual_hash", + Message: fmt.Sprintf("invalid hex encoding: %v", err), + } + } + } + + // Validate epoch if present + if a.Epoch != nil { + if len(*a.Epoch) != 64 { + return &ValidationError{ + Field: "epoch", + Message: fmt.Sprintf("must be 64 hex characters (32 bytes), got %d", len(*a.Epoch)), + } + } + + if _, err := hex.DecodeString(*a.Epoch); err != nil { + return &ValidationError{ + Field: "epoch", + Message: fmt.Sprintf("invalid hex encoding: %v", err), + } + } + } + + return nil +} diff --git a/sdk/go/steme/client.go b/sdk/go/steme/client.go new file mode 100644 index 0000000..257f4f7 --- /dev/null +++ b/sdk/go/steme/client.go @@ -0,0 +1,396 @@ +package steme + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "time" +) + +// Client is the StemeDB HTTP API client with automatic signing. +// +// Create a client with NewClient(). All assertions are automatically +// signed using the provided Signer. +type Client struct { + baseURL string + httpClient *http.Client + signer *Signer +} + +// NewClient creates a new StemeDB API client. +// +// The baseURL should be the API endpoint (e.g., "http://localhost:3000"). +// The signer is used to automatically sign all assertions. +// +// Example: +// +// signer, _ := steme.GenerateSigner() +// client := steme.NewClient("http://localhost:3000", signer) +func NewClient(baseURL string, signer *Signer) *Client { + return &Client{ + baseURL: baseURL, + httpClient: &http.Client{ + Timeout: 30 * time.Second, + }, + signer: signer, + } +} + +// WithHTTPClient sets a custom http.Client. +// +// This is useful for adding custom timeouts, TLS config, or proxies. +func (c *Client) WithHTTPClient(httpClient *http.Client) *Client { + c.httpClient = httpClient + return c +} + +// Assert creates a new assertion in the knowledge graph. +// +// The assertion is automatically signed using the client's signer. +// Returns the content-addressed hash of the created assertion. +// +// Example: +// +// assertion := steme.NewAssertion("Tesla_Inc", "has_revenue"). +// WithNumber(96.7). +// WithConfidence(0.95). +// WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). +// Build() +// +// hash, err := client.Assert(ctx, assertion) +func (c *Client) Assert(ctx context.Context, assertion Assertion) (string, error) { + // Validate before sending (includes source_hash requirement) + if err := assertion.Validate(); err != nil { + return "", err + } + + // Sign the assertion + signature, err := c.signAssertion(&assertion) + if err != nil { + return "", fmt.Errorf("steme: failed to sign assertion: %w", err) + } + + assertion.Signatures = []SignatureEntry{signature} + + // Make the API request + var resp CreateResponse + if err := c.doJSON(ctx, "POST", "/v1/assert", assertion, &resp); err != nil { + return "", err + } + + return resp.Hash, nil +} + +// Query queries assertions with optional filters and lens-based conflict resolution. +// +// Use QueryBuilder to construct query parameters fluently. +// +// Example: +// +// params := steme.NewQuery(). +// WithSubject("Tesla_Inc"). +// WithPredicate("has_revenue"). +// WithLens(steme.LensConsensus). +// Build() +// +// result, err := client.Query(ctx, params) +func (c *Client) Query(ctx context.Context, params QueryParams) (*QueryResult, error) { + queryURL := "/v1/query" + + // Build query parameters + values := url.Values{} + + if params.Subject != nil { + values.Add("subject", *params.Subject) + } + + if params.Predicate != nil { + values.Add("predicate", *params.Predicate) + } + + if params.Lifecycle != nil { + values.Add("lifecycle", string(*params.Lifecycle)) + } + + if params.Epoch != nil { + values.Add("epoch", *params.Epoch) + } + + if params.Lens != nil { + values.Add("lens", string(*params.Lens)) + } + + if params.Limit > 0 { + values.Add("limit", fmt.Sprintf("%d", params.Limit)) + } + + if len(values) > 0 { + queryURL += "?" + values.Encode() + } + + var result QueryResult + if err := c.doJSON(ctx, "GET", queryURL, nil, &result); err != nil { + return nil, err + } + + return &result, nil +} + +// Skeptic queries the "Trust but Verify" endpoint. +// +// Unlike Query which picks a winner via a lens, Skeptic shows all +// competing claims with their relative weights and conflict analysis. +// +// Example: +// +// result, err := client.Skeptic(ctx, steme.SkepticQueryParams{ +// Subject: "Semaglutide", +// Predicate: "muscle_effect", +// }) +// +// fmt.Printf("Status: %s, Conflict: %.2f\n", result.Status, result.ConflictScore) +// for _, claim := range result.Claims { +// fmt.Printf(" %v (%.1f%% support)\n", claim.Value, claim.WeightShare*100) +// } +func (c *Client) Skeptic(ctx context.Context, params SkepticQueryParams) (*SkepticResult, error) { + queryURL := "/v1/skeptic" + + values := url.Values{} + values.Add("subject", params.Subject) + values.Add("predicate", params.Predicate) + + queryURL += "?" + values.Encode() + + var result SkepticResult + if err := c.doJSON(ctx, "GET", queryURL, nil, &result); err != nil { + return nil, err + } + + return &result, nil +} + +// Trace queries the audit log for agent decision tracing. +// +// Returns query audits for a specific agent within a time range, optionally +// filtered by subject pattern. This enables "Why did the agent think that?" +// debugging for incident investigation. +// +// Example: +// +// result, err := client.Trace(ctx, steme.TraceParams{ +// AgentID: "deadbeef...", +// From: "1704067200", +// To: "1704153600", +// Subject: "Tesla*", +// Limit: 50, +// }) +// +// for _, audit := range result.Audits { +// fmt.Printf("Query %s at %d\n", audit.QueryID, audit.Timestamp) +// } +func (c *Client) Trace(ctx context.Context, params TraceParams) (*TraceResult, error) { + queryURL := "/v1/trace" + + // Build query parameters + values := url.Values{} + values.Add("agent_id", params.AgentID) + values.Add("from", params.From) + + if params.To != "" { + values.Add("to", params.To) + } + + if params.Subject != "" { + values.Add("subject", params.Subject) + } + + if params.Limit > 0 { + values.Add("limit", fmt.Sprintf("%d", params.Limit)) + } + + queryURL += "?" + values.Encode() + + var result TraceResult + if err := c.doJSON(ctx, "GET", queryURL, nil, &result); err != nil { + return nil, err + } + + return &result, nil +} + +// Supersede creates a supersession record for error correction. +// +// Supersession enables error correction without violating append-only semantics. +// Instead of mutating an assertion, we create a supersession record that points +// from the old (target) to the new (replacement) assertion. +// +// Example: +// +// result, err := client.Supersede(ctx, steme.SupersedeParams{ +// TargetHash: "abc123...", +// SupersessionType: steme.SupersessionInvalidate, +// Reason: "Proposal treated as approved. See incident INC-2024-001", +// NewHash: "def456...", +// AgentID: "deadbeef...", +// Signature: "...", +// }) +func (c *Client) Supersede(ctx context.Context, params SupersedeParams) (*SupersedeResult, error) { + var result SupersedeResult + if err := c.doJSON(ctx, "POST", "/v1/supersede", params, &result); err != nil { + return nil, err + } + + return &result, nil +} + +// Health checks the API health status. +// +// Returns the service status, version, and assertion count. +func (c *Client) Health(ctx context.Context) (*HealthResponse, error) { + var resp HealthResponse + if err := c.doJSON(ctx, "GET", "/v1/health", nil, &resp); err != nil { + return nil, err + } + + return &resp, nil +} + +// HealthResponse represents the health check response. +type HealthResponse struct { + Status string `json:"status"` + Version string `json:"version"` + AssertionsCount uint64 `json:"assertions_count"` +} + +// signAssertion creates a signature for an assertion. +// +// The signature is over the canonical representation of the assertion: +// BLAKE2b(subject || predicate || object_bytes || confidence || source_hash) +func (c *Client) signAssertion(a *Assertion) (SignatureEntry, error) { + // Build canonical message for signing + message, err := canonicalAssertionMessage(a) + if err != nil { + return SignatureEntry{}, err + } + + // Create signature entry + return c.signer.CreateSignature(message), nil +} + +// canonicalAssertionMessage creates the canonical byte representation for signing. +// +// This must match the server's signature verification logic. +// Uses SHA256 for the canonical hash. +func canonicalAssertionMessage(a *Assertion) ([]byte, error) { + h := sha256.New() + + // subject + h.Write([]byte(a.Subject)) + h.Write([]byte{0}) // separator + + // predicate + h.Write([]byte(a.Predicate)) + h.Write([]byte{0}) + + // object (serialize as JSON for determinism) + objBytes, err := json.Marshal(a.Object) + if err != nil { + return nil, fmt.Errorf("steme: failed to serialize object: %w", err) + } + h.Write(objBytes) + h.Write([]byte{0}) + + // confidence (as bytes) + confidenceBytes, err := json.Marshal(a.Confidence) + if err != nil { + return nil, fmt.Errorf("steme: failed to serialize confidence: %w", err) + } + h.Write(confidenceBytes) + h.Write([]byte{0}) + + // source_hash + sourceHashBytes, err := hex.DecodeString(a.SourceHash) + if err != nil { + return nil, fmt.Errorf("steme: invalid source_hash hex: %w", err) + } + h.Write(sourceHashBytes) + + return h.Sum(nil), nil +} + +// doJSON performs an HTTP request with JSON encoding/decoding. +func (c *Client) doJSON(ctx context.Context, method, path string, body any, result any) error { + fullURL := c.baseURL + path + + var reqBody io.Reader + if body != nil { + jsonBytes, err := json.Marshal(body) + if err != nil { + return fmt.Errorf("steme: failed to marshal request: %w", err) + } + reqBody = bytes.NewReader(jsonBytes) + } + + req, err := http.NewRequestWithContext(ctx, method, fullURL, reqBody) + if err != nil { + return fmt.Errorf("steme: failed to create request: %w", err) + } + + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + + // Add agent_id header for audit trail + req.Header.Set("X-Agent-Id", c.signer.PublicKey()) + + resp, err := c.httpClient.Do(req) + if err != nil { + return fmt.Errorf("steme: request failed: %w", err) + } + defer resp.Body.Close() + + // Read response body + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("steme: failed to read response: %w", err) + } + + // Check for HTTP errors + if resp.StatusCode >= 400 { + var apiErr struct { + Error string `json:"error"` + Code string `json:"code"` + } + + // Try to parse error response + if err := json.Unmarshal(respBody, &apiErr); err == nil && apiErr.Error != "" { + return &APIError{ + StatusCode: resp.StatusCode, + Code: apiErr.Code, + Message: apiErr.Error, + } + } + + // Fallback to generic error + return &APIError{ + StatusCode: resp.StatusCode, + Code: "UNKNOWN", + Message: string(respBody), + } + } + + // Decode success response + if result != nil { + if err := json.Unmarshal(respBody, result); err != nil { + return fmt.Errorf("steme: failed to decode response: %w", err) + } + } + + return nil +} diff --git a/sdk/go/steme/doc.go b/sdk/go/steme/doc.go new file mode 100644 index 0000000..4e61edc --- /dev/null +++ b/sdk/go/steme/doc.go @@ -0,0 +1,69 @@ +// Package steme provides a Go SDK for StemeDB, a probabilistic knowledge graph +// that stores Claims, not Facts. +// +// StemeDB is an append-only Merkle DAG with read-time conflict resolution via +// Lenses. Think "Git for Truth" - conflicting assertions coexist and are +// resolved at query time. +// +// # Quick Start +// +// Create a signer and client: +// +// signer, err := steme.GenerateSigner() +// if err != nil { +// log.Fatal(err) +// } +// client := steme.NewClient("http://localhost:3000", signer) +// +// Build and submit an assertion: +// +// assertion := steme.NewAssertion("Tesla_Inc", "has_revenue"). +// WithNumber(96.7). +// WithConfidence(0.95). +// WithSourceHash("0000...64 hex chars..."). +// Build() +// +// hash, err := client.Assert(context.Background(), assertion) +// +// Query with lens-based conflict resolution: +// +// params := steme.NewQuery(). +// WithSubject("Tesla_Inc"). +// WithLens(steme.LensConsensus). +// Build() +// result, err := client.Query(context.Background(), params) +// +// # Lenses +// +// StemeDB resolves conflicts at query time using Lenses: +// - Recency: Latest timestamp wins +// - Consensus: Most common value wins +// - Authority: Weighted by agent reputation +// - VoteAwareConsensus: Highest vote weight +// - TrustAwareAuthority: Weighted by TrustRank +// +// # Security +// +// All assertions are cryptographically signed using Ed25519. The SDK +// automatically signs assertions when you call client.Assert(). +// +// Never commit private key seeds to version control. Use environment +// variables or secret management: +// +// signer, err := steme.SignerFromEnv("STEME_PRIVATE_KEY") +// +// # Error Handling +// +// The SDK uses sentinel errors for common cases: +// +// if errors.Is(err, steme.ErrInvalidConfidence) { +// // handle validation error +// } +// +// API errors provide structured information: +// +// var apiErr *steme.APIError +// if errors.As(err, &apiErr) { +// log.Printf("API error [%d]: %s", apiErr.StatusCode, apiErr.Message) +// } +package steme diff --git a/sdk/go/steme/errors.go b/sdk/go/steme/errors.go new file mode 100644 index 0000000..debdc70 --- /dev/null +++ b/sdk/go/steme/errors.go @@ -0,0 +1,53 @@ +package steme + +import ( + "errors" + "fmt" +) + +var ( + // ErrInvalidKeySize indicates the private key is not 32 bytes + ErrInvalidKeySize = errors.New("steme: private key must be exactly 32 bytes") + + // ErrInvalidPublicKeySize indicates the public key is not 32 bytes + ErrInvalidPublicKeySize = errors.New("steme: public key must be exactly 32 bytes") + + // ErrInvalidSignatureSize indicates the signature is not 64 bytes + ErrInvalidSignatureSize = errors.New("steme: signature must be exactly 64 bytes") + + // ErrInvalidHashSize indicates a hash is not 32 bytes + ErrInvalidHashSize = errors.New("steme: hash must be exactly 32 bytes") + + // ErrMissingSignatures indicates no signatures were provided + ErrMissingSignatures = errors.New("steme: at least one signature is required") + + // ErrInvalidConfidence indicates confidence is not in [0.0, 1.0] + ErrInvalidConfidence = errors.New("steme: confidence must be between 0.0 and 1.0") + + // ErrInvalidHex indicates hex decoding failed + ErrInvalidHex = errors.New("steme: invalid hex encoding") + + // ErrNoWinner indicates lens failed to resolve a winner + ErrNoWinner = errors.New("steme: lens did not resolve a winner") +) + +// APIError wraps HTTP API errors with status code and message. +type APIError struct { + StatusCode int + Code string + Message string +} + +func (e *APIError) Error() string { + return fmt.Sprintf("steme API error [%d]: %s - %s", e.StatusCode, e.Code, e.Message) +} + +// ValidationError indicates a request validation failure. +type ValidationError struct { + Field string + Message string +} + +func (e *ValidationError) Error() string { + return fmt.Sprintf("steme validation error: %s - %s", e.Field, e.Message) +} diff --git a/sdk/go/steme/go.mod b/sdk/go/steme/go.mod new file mode 100644 index 0000000..bf6d1bb --- /dev/null +++ b/sdk/go/steme/go.mod @@ -0,0 +1,3 @@ +module github.com/orchard9/stemedb-go/steme + +go 1.22 diff --git a/sdk/go/steme/go.sum b/sdk/go/steme/go.sum new file mode 100644 index 0000000..b6abd2c --- /dev/null +++ b/sdk/go/steme/go.sum @@ -0,0 +1,4 @@ +golang.org/x/crypto v0.20.0 h1:jmAMJJZXr5KiCw05dfYK9QnqaqKLYXijU23lsEdcQqg= +golang.org/x/crypto v0.20.0/go.mod h1:Xwo95rrVNIoSMx9wa1JroENMToLWn3RNVrTBpLHgZPQ= +golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= diff --git a/sdk/go/steme/integration_test.go b/sdk/go/steme/integration_test.go new file mode 100644 index 0000000..71e55c8 --- /dev/null +++ b/sdk/go/steme/integration_test.go @@ -0,0 +1,714 @@ +//go:build integration + +package steme + +import ( + "context" + "fmt" + "os" + "testing" + "time" +) + +// Integration tests that run against a live StemeDB server. +// +// To run these tests: +// +// 1. Start the StemeDB API server: +// cargo run --bin stemedb-api +// +// 2. Run the integration tests: +// STEMEDB_URL=http://localhost:3000 go test -tags=integration ./... +// +// These tests are skipped by default (build tag "integration") to avoid +// breaking CI when no server is running. + +// getTestClient creates a client with a generated signer for testing. +// +// Skips the test if STEMEDB_URL is not set. +func getTestClient(t *testing.T) *Client { + t.Helper() + + baseURL := os.Getenv("STEMEDB_URL") + if baseURL == "" { + t.Skip("STEMEDB_URL not set - skipping integration test") + } + + signer, err := GenerateSigner() + if err != nil { + t.Fatalf("GenerateSigner() failed: %v", err) + } + + return NewClient(baseURL, signer) +} + +// uniqueSubject generates a unique subject for test isolation. +// +// This prevents tests from interfering with each other by ensuring +// each test operates on distinct subjects. +func uniqueSubject(base string) string { + return fmt.Sprintf("%s_%d", base, time.Now().UnixNano()) +} + +// TestIntegration_Health verifies the health endpoint works. +func TestIntegration_Health(t *testing.T) { + client := getTestClient(t) + ctx := context.Background() + + health, err := client.Health(ctx) + if err != nil { + t.Fatalf("Health() failed: %v", err) + } + + if health.Status != "healthy" { + t.Errorf("Health.Status = %s, want healthy", health.Status) + } + + if health.Version == "" { + t.Error("Health.Version is empty") + } + + t.Logf("Server status: %s, version: %s, assertions: %d", + health.Status, health.Version, health.AssertionsCount) +} + +// TestIntegration_Assert_Query_Roundtrip tests creating an assertion and querying it back. +func TestIntegration_Assert_Query_Roundtrip(t *testing.T) { + client := getTestClient(t) + ctx := context.Background() + + // Create a unique subject to avoid interference + subject := uniqueSubject("IntegrationTest_Entity") + predicate := "has_value" + expectedValue := "test_value_roundtrip" + + // Create assertion + assertion := NewAssertion(subject, predicate). + WithText(expectedValue). + WithConfidence(0.95). + WithLifecycle(LifecycleApproved). + WithSourceClass(SourceClassClinical). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + + hash, err := client.Assert(ctx, assertion) + if err != nil { + t.Fatalf("Assert() failed: %v", err) + } + + if len(hash) != 64 { + t.Errorf("Assert() hash length = %d, want 64", len(hash)) + } + + t.Logf("Created assertion with hash: %s", hash) + + // Small delay to ensure indexing completes + time.Sleep(100 * time.Millisecond) + + // Query it back + params := NewQuery(). + WithSubject(subject). + WithPredicate(predicate). + Build() + + result, err := client.Query(ctx, params) + if err != nil { + t.Fatalf("Query() failed: %v", err) + } + + if result.TotalCount == 0 { + t.Fatal("Query() returned no results") + } + + // Verify we got our assertion back + found := false + for _, a := range result.Assertions { + if a.Hash == hash { + found = true + + if a.Subject != subject { + t.Errorf("Subject = %s, want %s", a.Subject, subject) + } + + if a.Predicate != predicate { + t.Errorf("Predicate = %s, want %s", a.Predicate, predicate) + } + + if a.Object.Type != "Text" { + t.Errorf("Object.Type = %s, want Text", a.Object.Type) + } + + if a.Object.Value != expectedValue { + t.Errorf("Object.Value = %v, want %s", a.Object.Value, expectedValue) + } + + if a.Confidence != 0.95 { + t.Errorf("Confidence = %f, want 0.95", a.Confidence) + } + + if a.Lifecycle != LifecycleApproved { + t.Errorf("Lifecycle = %s, want Approved", a.Lifecycle) + } + + if a.SourceClass != SourceClassClinical { + t.Errorf("SourceClass = %s, want Clinical", a.SourceClass) + } + + if len(a.Signatures) == 0 { + t.Error("Assertion has no signatures") + } + + break + } + } + + if !found { + t.Errorf("Did not find assertion with hash %s in query results", hash) + } +} + +// TestIntegration_Query_WithLens tests querying with different lenses. +func TestIntegration_Query_WithLens(t *testing.T) { + client := getTestClient(t) + ctx := context.Background() + + // Create a unique subject for this test + subject := uniqueSubject("IntegrationTest_Lens") + predicate := "has_revenue" + + // Create multiple assertions with different values + assertions := []struct { + value float64 + confidence float64 + }{ + {100.0, 0.9}, + {105.0, 0.95}, + {100.0, 0.85}, // Duplicate value to test consensus + } + + for i, a := range assertions { + assertion := NewAssertion(subject, predicate). + WithNumber(a.value). + WithConfidence(a.confidence). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + + hash, err := client.Assert(ctx, assertion) + if err != nil { + t.Fatalf("Assert(%d) failed: %v", i, err) + } + + t.Logf("Created assertion %d with hash: %s (value: %.1f, confidence: %.2f)", + i, hash, a.value, a.confidence) + } + + // Small delay for indexing + time.Sleep(100 * time.Millisecond) + + // Test different lenses + lensTests := []struct { + name string + lens Lens + }{ + {"Recency", LensRecency}, + {"Consensus", LensConsensus}, + {"Authority", LensAuthority}, + } + + for _, tt := range lensTests { + t.Run(tt.name, func(t *testing.T) { + params := NewQuery(). + WithSubject(subject). + WithPredicate(predicate). + WithLens(tt.lens). + Build() + + result, err := client.Query(ctx, params) + if err != nil { + t.Fatalf("Query() with lens %s failed: %v", tt.lens, err) + } + + if result.TotalCount == 0 { + t.Errorf("Query() with lens %s returned no results", tt.lens) + } + + t.Logf("Lens %s returned %d results", tt.lens, result.TotalCount) + + // Verify all results match our subject/predicate + for _, a := range result.Assertions { + if a.Subject != subject { + t.Errorf("Result has wrong subject: %s, want %s", a.Subject, subject) + } + + if a.Predicate != predicate { + t.Errorf("Result has wrong predicate: %s, want %s", a.Predicate, predicate) + } + } + }) + } +} + +// TestIntegration_Query_NotFound tests querying for non-existent data. +func TestIntegration_Query_NotFound(t *testing.T) { + client := getTestClient(t) + ctx := context.Background() + + // Query for a subject that definitely doesn't exist + subject := uniqueSubject("IntegrationTest_NonExistent") + + params := NewQuery(). + WithSubject(subject). + WithPredicate("does_not_exist"). + Build() + + result, err := client.Query(ctx, params) + if err != nil { + t.Fatalf("Query() failed: %v", err) + } + + if result.TotalCount != 0 { + t.Errorf("Query() for non-existent data returned %d results, want 0", result.TotalCount) + } + + if len(result.Assertions) != 0 { + t.Errorf("Query() for non-existent data returned %d assertions, want 0", len(result.Assertions)) + } + + if result.HasMore { + t.Error("Query() for non-existent data claims HasMore = true") + } +} + +// TestIntegration_Query_Limit tests the limit parameter. +func TestIntegration_Query_Limit(t *testing.T) { + client := getTestClient(t) + ctx := context.Background() + + subject := uniqueSubject("IntegrationTest_Limit") + predicate := "has_index" + + // Create 5 assertions + const numAssertions = 5 + for i := 0; i < numAssertions; i++ { + assertion := NewAssertion(subject, predicate). + WithNumber(float64(i)). + WithConfidence(0.9). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + + _, err := client.Assert(ctx, assertion) + if err != nil { + t.Fatalf("Assert(%d) failed: %v", i, err) + } + } + + // Small delay for indexing + time.Sleep(100 * time.Millisecond) + + // Query with limit of 2 + params := NewQuery(). + WithSubject(subject). + WithPredicate(predicate). + WithLimit(2). + Build() + + result, err := client.Query(ctx, params) + if err != nil { + t.Fatalf("Query() failed: %v", err) + } + + if len(result.Assertions) > 2 { + t.Errorf("Query() with limit=2 returned %d results, want at most 2", len(result.Assertions)) + } + + if result.TotalCount > 2 && !result.HasMore { + t.Error("Query() should indicate HasMore when total > limit") + } +} + +// TestIntegration_Assert_AllObjectTypes tests all object value types. +func TestIntegration_Assert_AllObjectTypes(t *testing.T) { + client := getTestClient(t) + ctx := context.Background() + + subject := uniqueSubject("IntegrationTest_Types") + + tests := []struct { + name string + predicate string + builder func(*AssertionBuilder) *AssertionBuilder + checkType string + }{ + { + name: "Text", + predicate: "has_text", + builder: func(b *AssertionBuilder) *AssertionBuilder { + return b.WithText("hello world") + }, + checkType: "Text", + }, + { + name: "Number", + predicate: "has_number", + builder: func(b *AssertionBuilder) *AssertionBuilder { + return b.WithNumber(42.5) + }, + checkType: "Number", + }, + { + name: "Boolean", + predicate: "has_boolean", + builder: func(b *AssertionBuilder) *AssertionBuilder { + return b.WithBoolean(true) + }, + checkType: "Boolean", + }, + { + name: "Reference", + predicate: "has_reference", + builder: func(b *AssertionBuilder) *AssertionBuilder { + return b.WithReference("Entity_123") + }, + checkType: "Reference", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + builder := NewAssertion(subject, tt.predicate). + WithConfidence(0.9). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000") + + builder = tt.builder(builder) + assertion := builder.Build() + + hash, err := client.Assert(ctx, assertion) + if err != nil { + t.Fatalf("Assert() for %s failed: %v", tt.name, err) + } + + t.Logf("Created %s assertion with hash: %s", tt.name, hash) + + // Small delay for indexing + time.Sleep(100 * time.Millisecond) + + // Query it back + params := NewQuery(). + WithSubject(subject). + WithPredicate(tt.predicate). + Build() + + result, err := client.Query(ctx, params) + if err != nil { + t.Fatalf("Query() for %s failed: %v", tt.name, err) + } + + if result.TotalCount == 0 { + t.Fatalf("Query() for %s returned no results", tt.name) + } + + // Verify object type + if result.Assertions[0].Object.Type != tt.checkType { + t.Errorf("Object.Type = %s, want %s", result.Assertions[0].Object.Type, tt.checkType) + } + }) + } +} + +// TestIntegration_Assert_InvalidAssertion tests that invalid assertions are rejected. +func TestIntegration_Assert_InvalidAssertion(t *testing.T) { + client := getTestClient(t) + ctx := context.Background() + + tests := []struct { + name string + assertion Assertion + wantErr bool + }{ + { + name: "missing source_hash", + assertion: NewAssertion("Subject", "Predicate"). + WithText("value"). + Build(), + wantErr: true, + }, + { + name: "invalid confidence", + assertion: NewAssertion("Subject", "Predicate"). + WithText("value"). + WithConfidence(1.5). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build(), + wantErr: true, + }, + { + name: "negative confidence", + assertion: NewAssertion("Subject", "Predicate"). + WithText("value"). + WithConfidence(-0.1). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build(), + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := client.Assert(ctx, tt.assertion) + if (err != nil) != tt.wantErr { + t.Errorf("Assert() error = %v, wantErr %v", err, tt.wantErr) + } + + if tt.wantErr && err != nil { + t.Logf("Got expected error: %v", err) + } + }) + } +} + +// TestIntegration_Lifecycle tests lifecycle stage filtering. +func TestIntegration_Lifecycle(t *testing.T) { + client := getTestClient(t) + ctx := context.Background() + + subject := uniqueSubject("IntegrationTest_Lifecycle") + predicate := "has_status" + + // Create assertions with different lifecycle stages + stages := []LifecycleStage{ + LifecycleProposed, + LifecycleApproved, + LifecycleDeprecated, + } + + for _, stage := range stages { + assertion := NewAssertion(subject, predicate). + WithText(string(stage)). + WithLifecycle(stage). + WithConfidence(0.9). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + + hash, err := client.Assert(ctx, assertion) + if err != nil { + t.Fatalf("Assert() for lifecycle %s failed: %v", stage, err) + } + + t.Logf("Created assertion with lifecycle %s: %s", stage, hash) + } + + // Small delay for indexing + time.Sleep(100 * time.Millisecond) + + // Query for only Approved lifecycle + params := NewQuery(). + WithSubject(subject). + WithPredicate(predicate). + WithLifecycle(LifecycleApproved). + Build() + + result, err := client.Query(ctx, params) + if err != nil { + t.Fatalf("Query() failed: %v", err) + } + + // Should only get the Approved assertion + for _, a := range result.Assertions { + if a.Lifecycle != LifecycleApproved { + t.Errorf("Got assertion with lifecycle %s, want Approved only", a.Lifecycle) + } + } + + t.Logf("Lifecycle filtering returned %d Approved assertions", result.TotalCount) +} + +// TestIntegration_Trace tests the trace endpoint for audit trail querying. +func TestIntegration_Trace(t *testing.T) { + client := getTestClient(t) + ctx := context.Background() + + // Create a unique subject for this test + subject := uniqueSubject("IntegrationTest_Trace") + predicate := "has_trace_value" + + // Create an assertion to generate query activity + assertion := NewAssertion(subject, predicate). + WithText("test_trace_value"). + WithConfidence(0.95). + WithLifecycle(LifecycleApproved). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + + hash, err := client.Assert(ctx, assertion) + if err != nil { + t.Fatalf("Assert() failed: %v", err) + } + + t.Logf("Created assertion with hash: %s", hash) + + // Small delay for indexing + time.Sleep(100 * time.Millisecond) + + // Perform a query to create audit trail + params := NewQuery(). + WithSubject(subject). + WithPredicate(predicate). + Build() + + queryResult, err := client.Query(ctx, params) + if err != nil { + t.Fatalf("Query() failed: %v", err) + } + + if queryResult.TotalCount == 0 { + t.Fatal("Query() returned no results") + } + + t.Logf("Query returned %d results", queryResult.TotalCount) + + // Small delay for audit to be written + time.Sleep(100 * time.Millisecond) + + // Get the agent ID from the client's signer + agentID := client.signer.PublicKey() + + // Calculate time range (last 1 hour to now) + now := time.Now().Unix() + from := now - 3600 + + // Trace the agent's queries + traceParams := TraceParams{ + AgentID: agentID, + From: fmt.Sprintf("%d", from), + To: fmt.Sprintf("%d", now), + Subject: subject, // Filter to our test subject + Limit: 100, + } + + traceResult, err := client.Trace(ctx, traceParams) + if err != nil { + t.Fatalf("Trace() failed: %v", err) + } + + t.Logf("Trace returned %d audit records", traceResult.TotalCount) + + // Verify we got at least one audit record + if traceResult.TotalCount == 0 { + t.Error("Trace() returned no audit records") + } + + // Verify the trace result has the correct agent ID + if traceResult.AgentID != agentID { + t.Errorf("TraceResult.AgentID = %s, want %s", traceResult.AgentID, agentID) + } + + // Verify the trace result has the correct time range + if traceResult.FromTimestamp != uint64(from) { + t.Errorf("TraceResult.FromTimestamp = %d, want %d", traceResult.FromTimestamp, from) + } + + // Verify audit records contain our query + foundOurQuery := false + for _, audit := range traceResult.Audits { + t.Logf("Audit record: query_id=%s, timestamp=%d, subject=%v, predicate=%v", + audit.QueryID, audit.Timestamp, audit.Params.Subject, audit.Params.Predicate) + + // Check if this audit is for our query + if audit.Params.Subject != nil && *audit.Params.Subject == subject && + audit.Params.Predicate != nil && *audit.Params.Predicate == predicate { + foundOurQuery = true + + // Verify agent ID + if audit.AgentID == nil || *audit.AgentID != agentID { + t.Errorf("Audit.AgentID = %v, want %s", audit.AgentID, agentID) + } + + // Verify result hash is present + if audit.ResultHash == nil { + t.Error("Audit.ResultHash is nil, expected a result") + } + + // Verify contributing assertions + if len(audit.ContributingAssertions) == 0 { + t.Error("Audit.ContributingAssertions is empty, expected at least one") + } + } + } + + if !foundOurQuery { + t.Errorf("Did not find audit record for our query (subject=%s, predicate=%s)", subject, predicate) + } +} + +// TestIntegration_Trace_WithPattern tests trace with subject pattern filtering. +func TestIntegration_Trace_WithPattern(t *testing.T) { + client := getTestClient(t) + ctx := context.Background() + + // Create unique subjects with a common prefix + prefix := uniqueSubject("IntegrationTest_TracePattern") + subject1 := prefix + "_A" + subject2 := prefix + "_B" + predicate := "has_value" + + // Create assertions and query them + for _, subj := range []string{subject1, subject2} { + assertion := NewAssertion(subj, predicate). + WithText("test_value"). + WithConfidence(0.9). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + + _, err := client.Assert(ctx, assertion) + if err != nil { + t.Fatalf("Assert() for %s failed: %v", subj, err) + } + + time.Sleep(50 * time.Millisecond) + + // Query to create audit trail + params := NewQuery().WithSubject(subj).WithPredicate(predicate).Build() + _, err = client.Query(ctx, params) + if err != nil { + t.Fatalf("Query() for %s failed: %v", subj, err) + } + } + + time.Sleep(100 * time.Millisecond) + + // Trace with wildcard pattern + agentID := client.signer.PublicKey() + now := time.Now().Unix() + from := now - 3600 + + traceParams := TraceParams{ + AgentID: agentID, + From: fmt.Sprintf("%d", from), + To: fmt.Sprintf("%d", now), + Subject: prefix + "*", // Match both subjects + Limit: 100, + } + + traceResult, err := client.Trace(ctx, traceParams) + if err != nil { + t.Fatalf("Trace() failed: %v", err) + } + + t.Logf("Trace with pattern returned %d audit records", traceResult.TotalCount) + + // Should find both queries + foundSubjects := make(map[string]bool) + for _, audit := range traceResult.Audits { + if audit.Params.Subject != nil { + foundSubjects[*audit.Params.Subject] = true + } + } + + if !foundSubjects[subject1] { + t.Errorf("Did not find audit for subject %s", subject1) + } + + if !foundSubjects[subject2] { + t.Errorf("Did not find audit for subject %s", subject2) + } +} diff --git a/sdk/go/steme/query.go b/sdk/go/steme/query.go new file mode 100644 index 0000000..ba1e005 --- /dev/null +++ b/sdk/go/steme/query.go @@ -0,0 +1,416 @@ +package steme + +// QueryParams defines parameters for querying assertions. +// +// All fields are optional. Use QueryBuilder for fluent construction. +type QueryParams struct { + // Filter by subject entity + Subject *string `json:"subject,omitempty"` + + // Filter by predicate/relation + Predicate *string `json:"predicate,omitempty"` + + // Filter by lifecycle stage + Lifecycle *LifecycleStage `json:"lifecycle,omitempty"` + + // Filter by epoch (hex-encoded) + Epoch *string `json:"epoch,omitempty"` + + // Apply a lens for conflict resolution + Lens *Lens `json:"lens,omitempty"` + + // Maximum number of results to return (defaults to 100) + Limit int `json:"limit,omitempty"` + + // Filter by visual similarity (hex-encoded pHash, 16 chars). + // Returns assertions whose visual_hash has hamming distance <= VisualThreshold. + VisualNear *string `json:"visual_near,omitempty"` + + // Maximum hamming distance for visual matching (0-64, default: 8). + // Lower values require closer visual similarity. + VisualThreshold *uint32 `json:"visual_threshold,omitempty"` +} + +// QueryBuilder provides a fluent API for building query parameters. +type QueryBuilder struct { + params QueryParams +} + +// NewQuery creates a new query builder. +// +// Example: +// +// params := steme.NewQuery(). +// WithSubject("Tesla_Inc"). +// WithPredicate("has_revenue"). +// WithLens(steme.LensConsensus). +// WithLimit(10). +// Build() +func NewQuery() *QueryBuilder { + return &QueryBuilder{ + params: QueryParams{ + Limit: 100, // Default limit + }, + } +} + +// WithSubject filters by subject entity. +func (b *QueryBuilder) WithSubject(subject string) *QueryBuilder { + b.params.Subject = &subject + return b +} + +// WithPredicate filters by predicate/relation. +func (b *QueryBuilder) WithPredicate(predicate string) *QueryBuilder { + b.params.Predicate = &predicate + return b +} + +// WithLifecycle filters by lifecycle stage. +func (b *QueryBuilder) WithLifecycle(lifecycle LifecycleStage) *QueryBuilder { + b.params.Lifecycle = &lifecycle + return b +} + +// WithEpoch filters by epoch (hex-encoded, 32 bytes). +func (b *QueryBuilder) WithEpoch(epochHex string) *QueryBuilder { + b.params.Epoch = &epochHex + return b +} + +// WithLens applies a conflict resolution lens. +func (b *QueryBuilder) WithLens(lens Lens) *QueryBuilder { + b.params.Lens = &lens + return b +} + +// WithLimit sets the maximum number of results. +func (b *QueryBuilder) WithLimit(limit int) *QueryBuilder { + b.params.Limit = limit + return b +} + +// WithVisualNear filters by visual similarity to a reference pHash. +// +// This enables finding assertions with visually similar screenshots or images. +// The hash should be a hex-encoded 8-byte perceptual hash (16 characters). +// +// The threshold is the maximum hamming distance (0-64, default: 8): +// - 0: Exact match only +// - 8: ~12.5% bit difference, catches resizing/compression +// - 16: ~25% bit difference, more lenient +// +// Assertions without a visual_hash are excluded from results. +// +// Example: +// +// params := steme.NewQuery(). +// WithSubject("Tesla_10K"). +// WithVisualNear("a3f2b1c4d5e6f708", 5). +// Build() +func (b *QueryBuilder) WithVisualNear(hash string, threshold uint32) *QueryBuilder { + b.params.VisualNear = &hash + b.params.VisualThreshold = &threshold + return b +} + +// Build returns the constructed QueryParams. +func (b *QueryBuilder) Build() QueryParams { + return b.params +} + +// QueryResult represents the response from a query operation. +type QueryResult struct { + // Matching assertions + Assertions []AssertionResponse `json:"assertions"` + + // Total number of results returned + TotalCount int `json:"total_count"` + + // Whether there are more results beyond the limit + HasMore bool `json:"has_more"` +} + +// AssertionResponse represents a single assertion in query results. +type AssertionResponse struct { + // Content-addressed hash of this assertion (hex-encoded) + Hash string `json:"hash"` + + // The subject entity + Subject string `json:"subject"` + + // The predicate/relation + Predicate string `json:"predicate"` + + // The object value + Object ObjectValue `json:"object"` + + // Confidence score (0.0 to 1.0) + Confidence float64 `json:"confidence"` + + // Hash of parent assertion (hex-encoded, optional) + ParentHash *string `json:"parent_hash,omitempty"` + + // Hash of source evidence (hex-encoded) + SourceHash string `json:"source_hash"` + + // Source authority tier + SourceClass SourceClass `json:"source_class"` + + // Perceptual hash for visual anchoring (hex-encoded, optional) + VisualHash *string `json:"visual_hash,omitempty"` + + // Epoch ID (hex-encoded, optional) + Epoch *string `json:"epoch,omitempty"` + + // Lifecycle stage + Lifecycle LifecycleStage `json:"lifecycle"` + + // Agent signatures + Signatures []SignatureEntry `json:"signatures"` + + // Creation timestamp (Unix epoch) + Timestamp uint64 `json:"timestamp"` + + // Semantic embedding vector (optional) + Vector []float32 `json:"vector,omitempty"` +} + +// CreateResponse represents the response from a create operation. +type CreateResponse struct { + // Content-addressed hash of the created resource (hex-encoded) + Hash string `json:"hash"` + + // Status message + Status string `json:"status"` +} + +// SkepticQueryParams defines parameters for the skeptic endpoint. +type SkepticQueryParams struct { + // Subject entity to analyze (required) + Subject string `json:"subject"` + + // Predicate/relation to analyze (required) + Predicate string `json:"predicate"` +} + +// SkepticResult represents the "Trust but Verify" response. +// +// Unlike QueryResult which picks a winner, SkepticResult shows all +// competing claims with their relative weights. +type SkepticResult struct { + // The subject that was queried + Subject string `json:"subject"` + + // The predicate that was queried + Predicate string `json:"predicate"` + + // Overall resolution status + Status ResolutionStatus `json:"status"` + + // Conflict score (0.0 = unanimous, 1.0 = chaos) + ConflictScore float64 `json:"conflict_score"` + + // All distinct claims, ranked by weight_share descending + Claims []ClaimSummary `json:"claims"` + + // Total number of candidate assertions considered + CandidatesCount int `json:"candidates_count"` + + // Unix timestamp when this view was computed + ComputedAt uint64 `json:"computed_at"` + + // Which lens was used (always "Skeptic") + LensName string `json:"lens_name"` +} + +// ClaimSummary represents a single competing claim. +type ClaimSummary struct { + // The claimed value + Value ObjectValue `json:"value"` + + // Normalized weight (0.0 to 1.0) relative to all claims + WeightShare float64 `json:"weight_share"` + + // Number of assertions making this exact claim + AssertionCount uint32 `json:"assertion_count"` + + // Hash of the representative assertion (hex-encoded) + RepresentativeHash string `json:"representative_hash"` + + // Source provenance + Source SourceSummary `json:"source"` + + // Agents supporting this claim + SupportingAgents []AgentSummary `json:"supporting_agents"` +} + +// SourceSummary provides minimal source info for provenance. +type SourceSummary struct { + // Hash of the source document (hex-encoded) + SourceHash string `json:"source_hash"` + + // Visual anchor hash (hex-encoded, optional) + VisualHash *string `json:"visual_hash,omitempty"` +} + +// AgentSummary provides minimal agent info for attribution. +type AgentSummary struct { + // Agent's public key (hex-encoded) + AgentID string `json:"agent_id"` + + // Trust score at query time (0.0 to 1.0) + TrustScore float64 `json:"trust_score"` +} + +// TraceParams defines parameters for tracing agent queries. +// +// Used to debug "Why did the agent think that?" for incident investigation. +type TraceParams struct { + // Agent public key to trace (hex-encoded, 32 bytes) - required + AgentID string `json:"agent_id"` + + // Start of time range (Unix timestamp) - required + From string `json:"from"` + + // End of time range (Unix timestamp, defaults to now) + To string `json:"to,omitempty"` + + // Filter by subject pattern (e.g., "Tesla*", "auth/*") + Subject string `json:"subject,omitempty"` + + // Maximum number of results (default: 100) + Limit int `json:"limit,omitempty"` +} + +// TraceResult represents the response from a trace operation. +type TraceResult struct { + // Matching query audit records + Audits []QueryAuditRecord `json:"audits"` + + // Total number of results returned + TotalCount int `json:"total_count"` + + // Agent ID that was traced (hex-encoded) + AgentID string `json:"agent_id"` + + // Time range start (Unix timestamp) + FromTimestamp uint64 `json:"from_timestamp"` + + // Time range end (Unix timestamp) + ToTimestamp uint64 `json:"to_timestamp"` +} + +// QueryAuditRecord represents a single query audit entry. +type QueryAuditRecord struct { + // Unique identifier for this query (hex-encoded, 32 bytes) + QueryID string `json:"query_id"` + + // Agent public key who made the query (hex-encoded, optional) + AgentID *string `json:"agent_id,omitempty"` + + // Unix timestamp when the query was executed + Timestamp uint64 `json:"timestamp"` + + // Query parameters that were used + Params QueryParamsAudit `json:"params"` + + // Hash of the winning assertion (hex-encoded, optional) + ResultHash *string `json:"result_hash,omitempty"` + + // Confidence score of the result + ResultConfidence float32 `json:"result_confidence"` + + // Assertions that contributed to the result + ContributingAssertions []ContributingAssertion `json:"contributing_assertions"` +} + +// QueryParamsAudit represents the parameters used in a query. +type QueryParamsAudit struct { + // Subject filter (optional) + Subject *string `json:"subject,omitempty"` + + // Predicate filter (optional) + Predicate *string `json:"predicate,omitempty"` + + // Lifecycle filter (optional) + Lifecycle *LifecycleStage `json:"lifecycle,omitempty"` + + // Epoch filter (hex-encoded, optional) + Epoch *string `json:"epoch,omitempty"` + + // Lens used (optional) + Lens *Lens `json:"lens,omitempty"` +} + +// ContributingAssertion represents an assertion that contributed to a query result. +type ContributingAssertion struct { + // Hash of the assertion (hex-encoded) + AssertionHash string `json:"assertion_hash"` + + // Weight in the resolution (1.0 for winner) + Weight float32 `json:"weight"` + + // Hash of the source evidence (hex-encoded) + SourceHash string `json:"source_hash"` + + // Lifecycle stage of the assertion + Lifecycle LifecycleStage `json:"lifecycle"` +} + +// SupersessionType defines how an assertion is being superseded. +type SupersessionType string + +const ( + // SupersessionInvalidate means the old assertion was factually incorrect. + SupersessionInvalidate SupersessionType = "Invalidate" + + // SupersessionTemporal means the old assertion was correct but now outdated. + SupersessionTemporal SupersessionType = "Temporal" + + // SupersessionRefinement means the old assertion was a simplification. + SupersessionRefinement SupersessionType = "Refinement" + + // SupersessionRequiresReview means the old assertion needs human review. + SupersessionRequiresReview SupersessionType = "RequiresReview" + + // SupersessionAdditive means the new assertion adds context without invalidating. + SupersessionAdditive SupersessionType = "Additive" +) + +// SupersedeParams defines parameters for creating a supersession. +type SupersedeParams struct { + // Hash of the assertion being superseded (hex-encoded, 32 bytes) + TargetHash string `json:"target_hash"` + + // How the target is being superseded + SupersessionType SupersessionType `json:"supersession_type"` + + // Human-readable explanation (for audit trail) + Reason string `json:"reason"` + + // Hash of the replacement assertion (hex-encoded, optional) + // None for RequiresReview or pure invalidation. + NewHash string `json:"new_hash,omitempty"` + + // Public key of the agent creating the supersession (hex-encoded, 32 bytes) + AgentID string `json:"agent_id"` + + // Signature over the supersession content (hex-encoded, 64 bytes) + Signature string `json:"signature"` +} + +// SupersedeResult represents the response from a supersede operation. +type SupersedeResult struct { + // Status message + Status string `json:"status"` + + // Hash of the target assertion that was superseded (hex-encoded) + TargetHash string `json:"target_hash"` + + // Type of supersession applied + SupersessionType SupersessionType `json:"supersession_type"` + + // Unix timestamp when the supersession was recorded + Timestamp uint64 `json:"timestamp"` +} diff --git a/sdk/go/steme/signer.go b/sdk/go/steme/signer.go new file mode 100644 index 0000000..ea3c814 --- /dev/null +++ b/sdk/go/steme/signer.go @@ -0,0 +1,162 @@ +package steme + +import ( + "crypto/ed25519" + "crypto/rand" + "encoding/hex" + "fmt" + "os" + "time" +) + +// Signer handles Ed25519 signing for assertions. +// +// All assertions submitted to StemeDB must be signed by at least one agent. +// The Signer abstracts the cryptographic details and provides a simple API. +type Signer struct { + privateKey ed25519.PrivateKey + publicKey ed25519.PublicKey +} + +// NewSigner creates a Signer from a 32-byte Ed25519 private key seed. +// +// The seed should be exactly 32 bytes. The Ed25519 private key is derived +// from this seed, and the public key is computed from the private key. +// +// Returns ErrInvalidKeySize if the seed is not 32 bytes. +func NewSigner(seed []byte) (*Signer, error) { + if len(seed) != ed25519.SeedSize { + return nil, fmt.Errorf("%w: got %d bytes", ErrInvalidKeySize, len(seed)) + } + + privateKey := ed25519.NewKeyFromSeed(seed) + publicKey := privateKey.Public().(ed25519.PublicKey) + + return &Signer{ + privateKey: privateKey, + publicKey: publicKey, + }, nil +} + +// NewSignerFromHex creates a Signer from a hex-encoded 32-byte seed. +// +// The hex string should be exactly 64 characters (32 bytes). +// +// Returns ErrInvalidHex if hex decoding fails. +// Returns ErrInvalidKeySize if the decoded seed is not 32 bytes. +func NewSignerFromHex(hexSeed string) (*Signer, error) { + seed, err := hex.DecodeString(hexSeed) + if err != nil { + return nil, fmt.Errorf("%w: %v", ErrInvalidHex, err) + } + + return NewSigner(seed) +} + +// GenerateSigner generates a new random Ed25519 keypair. +// +// This is useful for testing or creating new agent identities. +// The private key seed can be retrieved with Seed() for persistence. +func GenerateSigner() (*Signer, error) { + publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + return nil, fmt.Errorf("steme: failed to generate keypair: %w", err) + } + + return &Signer{ + privateKey: privateKey, + publicKey: publicKey, + }, nil +} + +// SignerFromEnv creates a Signer from an environment variable. +// +// The environment variable should contain a hex-encoded 32-byte seed. +// +// Returns an error if the variable is not set, contains invalid hex, +// or is not exactly 32 bytes when decoded. +func SignerFromEnv(envVar string) (*Signer, error) { + hexSeed := os.Getenv(envVar) + if hexSeed == "" { + return nil, fmt.Errorf("steme: environment variable %s not set", envVar) + } + + return NewSignerFromHex(hexSeed) +} + +// PublicKey returns the hex-encoded Ed25519 public key (32 bytes). +// +// This is the agent_id used in StemeDB. +func (s *Signer) PublicKey() string { + return hex.EncodeToString(s.publicKey) +} + +// PublicKeyBytes returns the raw Ed25519 public key bytes. +func (s *Signer) PublicKeyBytes() []byte { + return s.publicKey +} + +// Seed returns the hex-encoded Ed25519 private key seed (32 bytes). +// +// This should be stored securely for key recovery. +func (s *Signer) Seed() string { + // Ed25519 private key is 64 bytes: [32-byte seed][32-byte public key] + // Extract the seed portion + return hex.EncodeToString(s.privateKey.Seed()) +} + +// Sign creates an Ed25519 signature over the message bytes. +// +// The signature is 64 bytes and is hex-encoded in the returned string. +func (s *Signer) Sign(message []byte) string { + signature := ed25519.Sign(s.privateKey, message) + return hex.EncodeToString(signature) +} + +// CreateSignature creates a SignatureEntry for an assertion. +// +// The message should be the canonical serialization of the assertion +// (subject:predicate:object:confidence:source_hash). +// +// The timestamp is set to the current Unix epoch. +func (s *Signer) CreateSignature(message []byte) SignatureEntry { + timestamp := uint64(time.Now().Unix()) + + return SignatureEntry{ + AgentID: s.PublicKey(), + Signature: s.Sign(message), + Timestamp: timestamp, + } +} + +// Verify verifies an Ed25519 signature. +// +// This is useful for validating signatures received from other agents. +// +// Returns ErrInvalidPublicKeySize if the public key is not 32 bytes. +// Returns ErrInvalidSignatureSize if the signature is not 64 bytes. +func Verify(publicKeyHex, signatureHex string, message []byte) error { + publicKey, err := hex.DecodeString(publicKeyHex) + if err != nil { + return fmt.Errorf("%w: invalid public key hex: %v", ErrInvalidHex, err) + } + + if len(publicKey) != ed25519.PublicKeySize { + return fmt.Errorf("%w: public key is %d bytes", ErrInvalidPublicKeySize, len(publicKey)) + } + + signature, err := hex.DecodeString(signatureHex) + if err != nil { + return fmt.Errorf("%w: invalid signature hex: %v", ErrInvalidHex, err) + } + + if len(signature) != ed25519.SignatureSize { + return fmt.Errorf("%w: signature is %d bytes", ErrInvalidSignatureSize, len(signature)) + } + + if !ed25519.Verify(publicKey, message, signature) { + return fmt.Errorf("steme: signature verification failed") + } + + return nil +} diff --git a/sdk/go/steme/steme_test.go b/sdk/go/steme/steme_test.go new file mode 100644 index 0000000..c696918 --- /dev/null +++ b/sdk/go/steme/steme_test.go @@ -0,0 +1,520 @@ +package steme + +import ( + "encoding/hex" + "testing" +) + +// Note: context is used in the skipped integration test + +// TestSignerGeneration tests keypair generation and serialization. +func TestSignerGeneration(t *testing.T) { + signer, err := GenerateSigner() + if err != nil { + t.Fatalf("GenerateSigner() failed: %v", err) + } + + // Check public key is 64 hex chars (32 bytes) + pubKey := signer.PublicKey() + if len(pubKey) != 64 { + t.Errorf("PublicKey() length = %d, want 64", len(pubKey)) + } + + // Check seed is 64 hex chars (32 bytes) + seed := signer.Seed() + if len(seed) != 64 { + t.Errorf("Seed() length = %d, want 64", len(seed)) + } + + // Check we can reconstruct signer from seed + signer2, err := NewSignerFromHex(seed) + if err != nil { + t.Fatalf("NewSignerFromHex() failed: %v", err) + } + + if signer.PublicKey() != signer2.PublicKey() { + t.Errorf("PublicKey mismatch after reconstruction") + } +} + +// TestSignerSignAndVerify tests signature creation and verification. +func TestSignerSignAndVerify(t *testing.T) { + signer, err := GenerateSigner() + if err != nil { + t.Fatalf("GenerateSigner() failed: %v", err) + } + + message := []byte("test message") + signature := signer.Sign(message) + + // Signature should be 128 hex chars (64 bytes) + if len(signature) != 128 { + t.Errorf("Sign() signature length = %d, want 128", len(signature)) + } + + // Verify the signature + err = Verify(signer.PublicKey(), signature, message) + if err != nil { + t.Errorf("Verify() failed: %v", err) + } + + // Verify fails with wrong message + err = Verify(signer.PublicKey(), signature, []byte("wrong message")) + if err == nil { + t.Errorf("Verify() should fail with wrong message") + } +} + +// TestAssertionBuilder tests the fluent assertion builder API. +func TestAssertionBuilder(t *testing.T) { + lifecycle := LifecycleApproved + sourceClass := SourceClassClinical + + assertion := NewAssertion("Tesla_Inc", "has_revenue"). + WithNumber(96.7). + WithConfidence(0.95). + WithLifecycle(lifecycle). + WithSourceClass(sourceClass). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + + if assertion.Subject != "Tesla_Inc" { + t.Errorf("Subject = %s, want Tesla_Inc", assertion.Subject) + } + + if assertion.Predicate != "has_revenue" { + t.Errorf("Predicate = %s, want has_revenue", assertion.Predicate) + } + + if assertion.Object.Type != "Number" { + t.Errorf("Object.Type = %s, want Number", assertion.Object.Type) + } + + if assertion.Object.Value != 96.7 { + t.Errorf("Object.Value = %v, want 96.7", assertion.Object.Value) + } + + if assertion.Confidence != 0.95 { + t.Errorf("Confidence = %f, want 0.95", assertion.Confidence) + } + + if assertion.Lifecycle == nil || *assertion.Lifecycle != LifecycleApproved { + t.Errorf("Lifecycle = %v, want Approved", assertion.Lifecycle) + } + + if assertion.SourceClass == nil || *assertion.SourceClass != SourceClassClinical { + t.Errorf("SourceClass = %v, want Clinical", assertion.SourceClass) + } +} + +// TestAssertionValidation tests assertion validation. +func TestAssertionValidation(t *testing.T) { + tests := []struct { + name string + build func() Assertion + wantErr bool + }{ + { + name: "valid assertion", + build: func() Assertion { + return NewAssertion("Tesla_Inc", "has_revenue"). + WithNumber(96.7). + WithConfidence(0.95). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + }, + wantErr: false, + }, + { + name: "confidence too high", + build: func() Assertion { + return NewAssertion("Tesla_Inc", "has_revenue"). + WithNumber(96.7). + WithConfidence(1.5). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + }, + wantErr: true, + }, + { + name: "confidence negative", + build: func() Assertion { + return NewAssertion("Tesla_Inc", "has_revenue"). + WithNumber(96.7). + WithConfidence(-0.1). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + }, + wantErr: true, + }, + { + name: "missing source_hash", + build: func() Assertion { + return NewAssertion("Tesla_Inc", "has_revenue"). + WithNumber(96.7). + Build() + }, + wantErr: true, + }, + { + name: "invalid source_hash length", + build: func() Assertion { + return NewAssertion("Tesla_Inc", "has_revenue"). + WithNumber(96.7). + WithSourceHash("00"). + Build() + }, + wantErr: true, + }, + { + name: "invalid source_hash hex", + build: func() Assertion { + return NewAssertion("Tesla_Inc", "has_revenue"). + WithNumber(96.7). + WithSourceHash("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"). + Build() + }, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assertion := tt.build() + err := assertion.Validate() + + if (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +// TestQueryBuilder tests the fluent query builder API. +func TestQueryBuilder(t *testing.T) { + lens := LensConsensus + lifecycle := LifecycleApproved + + params := NewQuery(). + WithSubject("Tesla_Inc"). + WithPredicate("has_revenue"). + WithLens(lens). + WithLifecycle(lifecycle). + WithLimit(10). + Build() + + if params.Subject == nil || *params.Subject != "Tesla_Inc" { + t.Errorf("Subject = %v, want Tesla_Inc", params.Subject) + } + + if params.Predicate == nil || *params.Predicate != "has_revenue" { + t.Errorf("Predicate = %v, want has_revenue", params.Predicate) + } + + if params.Lens == nil || *params.Lens != LensConsensus { + t.Errorf("Lens = %v, want Consensus", params.Lens) + } + + if params.Lifecycle == nil || *params.Lifecycle != LifecycleApproved { + t.Errorf("Lifecycle = %v, want Approved", params.Lifecycle) + } + + if params.Limit != 10 { + t.Errorf("Limit = %d, want 10", params.Limit) + } +} + +// TestCanonicalMessage tests the canonical message generation for signing. +func TestCanonicalMessage(t *testing.T) { + assertion := NewAssertion("Tesla_Inc", "has_revenue"). + WithNumber(96.7). + WithConfidence(0.95). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + + msg1, err := canonicalAssertionMessage(&assertion) + if err != nil { + t.Fatalf("canonicalAssertionMessage() failed: %v", err) + } + + // Same assertion should produce same message + msg2, err := canonicalAssertionMessage(&assertion) + if err != nil { + t.Fatalf("canonicalAssertionMessage() failed: %v", err) + } + + if hex.EncodeToString(msg1) != hex.EncodeToString(msg2) { + t.Errorf("Canonical message not deterministic") + } + + // Different assertion should produce different message + assertion2 := NewAssertion("Tesla_Inc", "has_revenue"). + WithNumber(97.0). // Different value + WithConfidence(0.95). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + + msg3, err := canonicalAssertionMessage(&assertion2) + if err != nil { + t.Fatalf("canonicalAssertionMessage() failed: %v", err) + } + + if hex.EncodeToString(msg1) == hex.EncodeToString(msg3) { + t.Errorf("Different assertions produced same canonical message") + } +} + +// TestClientIntegration is a placeholder for integration tests. +// +// This would test against a real StemeDB server. For now, it's skipped +// unless the STEMEDB_URL environment variable is set. +func TestClientIntegration(t *testing.T) { + t.Skip("Integration test requires running StemeDB server") + + // Example integration test structure: + /* + baseURL := os.Getenv("STEMEDB_URL") + if baseURL == "" { + t.Skip("STEMEDB_URL not set") + } + + signer, err := GenerateSigner() + if err != nil { + t.Fatalf("GenerateSigner() failed: %v", err) + } + + client := NewClient(baseURL, signer) + + // Test health check + health, err := client.Health(context.Background()) + if err != nil { + t.Fatalf("Health() failed: %v", err) + } + + if health.Status != "healthy" { + t.Errorf("Health.Status = %s, want healthy", health.Status) + } + + // Test assertion creation + assertion := NewAssertion("test_entity", "test_predicate"). + WithText("test value"). + WithConfidence(0.95). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + + hash, err := client.Assert(context.Background(), assertion) + if err != nil { + t.Fatalf("Assert() failed: %v", err) + } + + if len(hash) != 64 { + t.Errorf("Assert() hash length = %d, want 64", len(hash)) + } + + // Test query + params := NewQuery(). + WithSubject("test_entity"). + WithPredicate("test_predicate"). + Build() + + result, err := client.Query(context.Background(), params) + if err != nil { + t.Fatalf("Query() failed: %v", err) + } + + if result.TotalCount == 0 { + t.Errorf("Query() returned no results") + } + */ +} + +// TestSignerFromEnvNotSet tests that SignerFromEnv fails when var is not set. +func TestSignerFromEnvNotSet(t *testing.T) { + _, err := SignerFromEnv("NONEXISTENT_STEME_VAR_12345") + if err == nil { + t.Error("SignerFromEnv() should fail when env var is not set") + } +} + +// TestCanonicalMessageAllObjectTypes tests canonical message with all object types. +func TestCanonicalMessageAllObjectTypes(t *testing.T) { + types := []struct { + name string + obj ObjectValue + }{ + {"text", NewTextValue("hello")}, + {"number", NewNumberValue(42.5)}, + {"boolean", NewBooleanValue(true)}, + {"reference", NewReferenceValue("Entity_123")}, + } + + for _, tt := range types { + t.Run(tt.name, func(t *testing.T) { + a := NewAssertion("Subject", "Predicate"). + WithConfidence(0.5). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + a.Object = tt.obj + + msg, err := canonicalAssertionMessage(&a) + if err != nil { + t.Errorf("canonicalAssertionMessage() failed for %s: %v", tt.name, err) + } + if len(msg) != 32 { // SHA256 output + t.Errorf("Expected 32 bytes, got %d", len(msg)) + } + }) + } +} + +// TestCanonicalMessageEdgeCases tests edge cases in canonical message generation. +func TestCanonicalMessageEdgeCases(t *testing.T) { + tests := []struct { + name string + build func() Assertion + wantErr bool + }{ + { + name: "zero confidence", + build: func() Assertion { + return NewAssertion("S", "P"). + WithText("v"). + WithConfidence(0.0). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + }, + wantErr: false, + }, + { + name: "max confidence", + build: func() Assertion { + return NewAssertion("S", "P"). + WithText("v"). + WithConfidence(1.0). + WithSourceHash("0000000000000000000000000000000000000000000000000000000000000000"). + Build() + }, + wantErr: false, + }, + { + name: "invalid source_hash hex", + build: func() Assertion { + a := NewAssertion("S", "P").WithText("v").Build() + a.SourceHash = "zzzz" // Invalid hex + return a + }, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + a := tt.build() + _, err := canonicalAssertionMessage(&a) + if (err != nil) != tt.wantErr { + t.Errorf("error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +// TestNewSignerInvalidSeed tests that NewSigner fails with wrong seed size. +func TestNewSignerInvalidSeed(t *testing.T) { + tests := []struct { + name string + seedLen int + wantErr bool + }{ + {"empty seed", 0, true}, + {"short seed", 16, true}, + {"correct seed", 32, false}, + {"long seed", 64, true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + seed := make([]byte, tt.seedLen) + _, err := NewSigner(seed) + if (err != nil) != tt.wantErr { + t.Errorf("NewSigner() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +// TestVerifyInvalidInputs tests Verify with invalid inputs. +func TestVerifyInvalidInputs(t *testing.T) { + signer, _ := GenerateSigner() + message := []byte("test") + validSig := signer.Sign(message) + + tests := []struct { + name string + pubKey string + sig string + wantErr bool + }{ + {"valid", signer.PublicKey(), validSig, false}, + {"invalid pubkey hex", "zzzz", validSig, true}, + {"short pubkey", "abcd", validSig, true}, + {"invalid sig hex", signer.PublicKey(), "zzzz", true}, + {"short sig", signer.PublicKey(), "abcd", true}, + {"wrong sig", signer.PublicKey(), hex.EncodeToString(make([]byte, 64)), true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := Verify(tt.pubKey, tt.sig, message) + if (err != nil) != tt.wantErr { + t.Errorf("Verify() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +// TestObjectValueConstructors tests the object value constructor functions. +func TestObjectValueConstructors(t *testing.T) { + tests := []struct { + name string + value ObjectValue + wantType string + wantValue any + }{ + { + name: "text value", + value: NewTextValue("hello"), + wantType: "Text", + wantValue: "hello", + }, + { + name: "number value", + value: NewNumberValue(42.5), + wantType: "Number", + wantValue: 42.5, + }, + { + name: "boolean value", + value: NewBooleanValue(true), + wantType: "Boolean", + wantValue: true, + }, + { + name: "reference value", + value: NewReferenceValue("Entity_Id"), + wantType: "Reference", + wantValue: "Entity_Id", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if tt.value.Type != tt.wantType { + t.Errorf("Type = %s, want %s", tt.value.Type, tt.wantType) + } + + if tt.value.Value != tt.wantValue { + t.Errorf("Value = %v, want %v", tt.value.Value, tt.wantValue) + } + }) + } +} diff --git a/sdk/go/steme/types.go b/sdk/go/steme/types.go new file mode 100644 index 0000000..d7e32e3 --- /dev/null +++ b/sdk/go/steme/types.go @@ -0,0 +1,191 @@ +package steme + +import "slices" + +// LifecycleStage represents the lifecycle stage of an assertion. +// +// Assertions progress through lifecycle stages to distinguish proposals +// from decisions. +type LifecycleStage string + +const ( + // LifecycleProposed is an initial proposal, idea, or RFC. + LifecycleProposed LifecycleStage = "Proposed" + + // LifecycleUnderReview is under active review or debate. + LifecycleUnderReview LifecycleStage = "UnderReview" + + // LifecycleApproved is accepted as current truth. + LifecycleApproved LifecycleStage = "Approved" + + // LifecycleDeprecated was true, now superseded. + LifecycleDeprecated LifecycleStage = "Deprecated" + + // LifecycleRejected was considered and explicitly declined. + LifecycleRejected LifecycleStage = "Rejected" +) + +// SourceClass represents the authority tier of a source. +// +// Sources are tiered from most authoritative (Regulatory, Tier 0) to +// least authoritative (Anecdotal, Tier 5). +type SourceClass string + +const ( + // SourceClassRegulatory - Tier 0: Regulatory bodies (FDA, EMA, WHO) + SourceClassRegulatory SourceClass = "Regulatory" + + // SourceClassClinical - Tier 1: Clinical trials, peer-reviewed research + SourceClassClinical SourceClass = "Clinical" + + // SourceClassObservational - Tier 2: Observational studies, real-world evidence + SourceClassObservational SourceClass = "Observational" + + // SourceClassExpert - Tier 3: Expert opinions, medical guidelines + SourceClassExpert SourceClass = "Expert" + + // SourceClassCommunity - Tier 4: Curated community knowledge + SourceClassCommunity SourceClass = "Community" + + // SourceClassAnecdotal - Tier 5: Individual reports, testimonials, social media + SourceClassAnecdotal SourceClass = "Anecdotal" +) + +// Lens represents a conflict resolution strategy. +type Lens string + +const ( + // LensRecency - Latest timestamp wins + LensRecency Lens = "Recency" + + // LensConsensus - Most common object value + LensConsensus Lens = "Consensus" + + // LensAuthority - Weighted by agent reputation + LensAuthority Lens = "Authority" + + // LensVoteAwareConsensus - Highest vote weight from VoteStore + LensVoteAwareConsensus Lens = "VoteAwareConsensus" + + // LensTrustAwareAuthority - Weighted by TrustRank reputation + LensTrustAwareAuthority Lens = "TrustAwareAuthority" +) + +// ObjectValue represents the value in an assertion. +// +// This is serialized as a tagged union in JSON: +// +// {"type": "Text", "value": "hello"} +// {"type": "Number", "value": 42.5} +// {"type": "Boolean", "value": true} +// {"type": "Reference", "value": "Entity_Id"} +type ObjectValue struct { + Type string `json:"type"` + Value any `json:"value"` +} + +// NewTextValue creates a text object value. +func NewTextValue(text string) ObjectValue { + return ObjectValue{Type: "Text", Value: text} +} + +// NewNumberValue creates a numeric object value. +func NewNumberValue(num float64) ObjectValue { + return ObjectValue{Type: "Number", Value: num} +} + +// NewBooleanValue creates a boolean object value. +func NewBooleanValue(val bool) ObjectValue { + return ObjectValue{Type: "Boolean", Value: val} +} + +// NewReferenceValue creates a reference object value. +func NewReferenceValue(entityID string) ObjectValue { + return ObjectValue{Type: "Reference", Value: entityID} +} + +// SignatureEntry represents an Ed25519 signature from an agent. +type SignatureEntry struct { + // AgentID is the hex-encoded Ed25519 public key (32 bytes) + AgentID string `json:"agent_id"` + + // Signature is the hex-encoded Ed25519 signature (64 bytes) + Signature string `json:"signature"` + + // Timestamp is when the agent signed (Unix epoch) + Timestamp uint64 `json:"timestamp"` +} + +// ResolutionStatus indicates the level of agreement among claims. +type ResolutionStatus string + +const ( + // ResolutionUnanimous - All assertions agree on the same value + ResolutionUnanimous ResolutionStatus = "Unanimous" + + // ResolutionAgreed - Strong majority (>75% weight) agrees + ResolutionAgreed ResolutionStatus = "Agreed" + + // ResolutionContested - No clear consensus; significant disagreement + ResolutionContested ResolutionStatus = "Contested" +) + +// TrustPack represents a curated list of trusted agents. +// +// Trust Packs are the "App Store for Trust" - domain experts curate lists +// of agents they vouch for, and consumers subscribe to filter consensus +// through that expertise. For example, a "Skeptical Cardio Pack" might +// contain vetted cardiologists for filtering GLP-1 side effect claims. +// +// Agents in a pack are identified by their Ed25519 public keys. +type TrustPack struct { + // ID is the hex-encoded BLAKE3 hash of the pack content (32 bytes) + ID string `json:"id"` + + // Name is a human-readable identifier (e.g., "Mayo_Clinic_Experts") + Name string `json:"name"` + + // Maintainer is the hex-encoded Ed25519 public key of the pack owner (32 bytes) + Maintainer string `json:"maintainer"` + + // Agents is a list of hex-encoded Ed25519 public keys (32 bytes each) + Agents []string `json:"agents"` + + // CreatedAt is when the pack was created (Unix epoch) + CreatedAt uint64 `json:"created_at"` + + // UpdatedAt is when the pack was last modified (Unix epoch) + UpdatedAt uint64 `json:"updated_at"` +} + +// NewTrustPack creates a new TrustPack with the given name and maintainer. +func NewTrustPack(name, maintainer string) TrustPack { + return TrustPack{ + Name: name, + Maintainer: maintainer, + Agents: []string{}, + } +} + +// AddAgent adds an agent to the pack if not already present. +func (tp *TrustPack) AddAgent(agentID string) { + if slices.Contains(tp.Agents, agentID) { + return // Already present + } + tp.Agents = append(tp.Agents, agentID) +} + +// RemoveAgent removes an agent from the pack. +func (tp *TrustPack) RemoveAgent(agentID string) { + for i, existing := range tp.Agents { + if existing == agentID { + tp.Agents = append(tp.Agents[:i], tp.Agents[i+1:]...) + return + } + } +} + +// ContainsAgent checks if an agent is in the pack. +func (tp *TrustPack) ContainsAgent(agentID string) bool { + return slices.Contains(tp.Agents, agentID) +} diff --git a/usage.md b/usage.md index 39d2206..324783c 100644 --- a/usage.md +++ b/usage.md @@ -3,6 +3,48 @@ > **Philosophy:** State as a Side Effect. Truth as a Consensus. > **Package:** `github.com/orchard9/stemedb-go` +--- + +## SDK Quick Start + +For most use cases, start with the **Go SDK** which provides a simple, type-safe API: + +```bash +go get github.com/orchard9/stemedb-go/steme +``` + +```go +import "github.com/orchard9/stemedb-go/steme" + +// Generate keypair +signer, _ := steme.GenerateSigner() + +// Create client +client := steme.NewClient("http://localhost:3000", signer) + +// Assert a fact +assertion := steme.NewAssertion("Tesla_Inc", "has_revenue"). + WithNumber(96.7). + WithConfidence(0.95). + WithSourceHash("..."). + Build() + +hash, _ := client.Assert(ctx, assertion) + +// Query with conflict resolution +params := steme.NewQuery(). + WithSubject("Tesla_Inc"). + WithPredicate("has_revenue"). + WithLens(steme.LensConsensus). + Build() + +result, _ := client.Query(ctx, params) +``` + +**Full SDK Documentation:** [docs/sdk/go-sdk.md](./docs/sdk/go-sdk.md) + +--- + ## 1. The "Invisible" Integration (Job-Aware) StemeDB is the "Flight Recorder" for your Agents. The Context carries the **Job ID**, binding every assertion to a persistent execution trace. @@ -72,10 +114,11 @@ func (p *FileProcessor) Process(ctx context.Context, files []string) { // Anchors the assertion to a Perceptual Hash (pHash) of the source. snapshot := captureScreenshot(file) - // 3. Assert with Proof + // 3. Assert with Proof AND Lifecycle steme.Assert(ctx, file, "status", "PROCESSED", steme.WithVisualProof(snapshot), // Stores pHash steme.WithConfidence(0.95), + steme.WithLifecycle(steme.LifecycleApproved), // Explicitly mark as Done ) } } @@ -83,77 +126,54 @@ func (p *FileProcessor) Process(ctx context.Context, files []string) { --- -## 3. Deep Research Primitives (Consensus & Decay) +## 3. Querying with Intent (The Agile Team Pattern) -Agents must collaborate to build truth, not just overwrite each other. - -### The "Co-Signing" Pattern (Gap A) -If Agent B agrees with Agent A, it shouldn't write a duplicate assertion. It should **Sign** the existing one to boost its TrustRank. +Don't just ask "what is X?". Ask "what is the *approved* X?". +### Implementation Agent (Safety First) ```go -func ValidateFact(ctx context.Context, factID string) { - // Agent B verifies the fact - if verify(factID) { - // Boosts the consensus score without adding a new node. - // Cryptographically signs the existing hash. - steme.Sign(ctx, factID, steme.Confidence(0.9)) - } else { - // Create a Counter-Assertion (Conflict) - steme.Assert(ctx, factID, "status", "DISPUTED", - steme.WithReason("Verification Failed"), - ) - } -} +// The developer agent needs the definitive answer, not proposals. +algo := steme.Query(ctx, steme.Query{ + Subject: "auth/jwt", + Predicate: "signing_algorithm", + Lens: "Authority", + Lifecycle: steme.LifecycleApproved, // Filters out RFCs/Proposals +}) +// Returns "RS256" (Production Config) ``` -### The "Reinforce" Pattern (Gap C) -Truth decays over time (`t_1/2`). Agents must actively maintain knowledge. - +### Research Agent (Broad Search) ```go -func MaintenanceLoop(ctx context.Context) { - // 1. Find decaying facts using the 'Decay' Lens - facts := steme.Query(ctx, steme.Query{ - Lens: "Decay", // Returns low-confidence / old facts - }) - - for _, fact := range facts { - // 2. Re-verify - if stillTrue(fact) { - // Resets the decay timer (Back-Propagation) - steme.Reinforce(ctx, fact.Hash) - } - } -} +// The researcher wants to know about upcoming changes. +proposals := steme.Query(ctx, steme.Query{ + Subject: "auth/jwt", + Predicate: "signing_algorithm", + Lens: "Recency", + Lifecycle: steme.LifecycleProposed, // Specific search for RFCs +}) +// Returns "ES256" (The RFC) ``` --- -## 4. Lenses: Defined vs. Custom +## 4. The "Time Travel" Debugger (SRE Tool) -Agents use **Defined Lenses** for 99% of operations to ensure a shared reality. - -### Defined Lenses (The Standard Library) -Available via `steme.Lens*` constants. -* **Consensus**: The default. "What does the group believe?" -* **Authority**: "What do the experts believe?" (TrustRank weighted). -* **Constraints**: "What are the rules?" (Pre-flight checks). -* **Decay**: "What is fading?" (Maintenance targets). - -### Custom Lenses (The Exception) -Used only for specific simulations or "What If" scenarios. +When an incident occurs, you must reproduce the exact state of the world at the time of failure. ```go -// Advanced: Define a transient lens for a simulation -lens := steme.DefineLens(ctx, steme.LensDefinition{ - Name: "Hypothetical-High-Trust", - Logic: `return candidates.filter(c => c.agent_id == "Agent-X")`, // WASM logic -}) +func DebugIncident(ctx context.Context) { + // 1. Create a "Lens" to view the past + // "Show me the state of the world as of yesterday 2 PM" + // This allows the SRE to see exactly what the Agent saw. + pastContext := steme.TimeTravel(ctx, "2023-10-24T14:00:00Z") -// Query using the custom lens -result := steme.Query(ctx, steme.Query{ - Subject: "Tesla", - Lens: lens.ID, -}) + // 2. Query exactly as if you were live + status := steme.Get(pastContext, "Task-Auth", "status") + + // 3. Audit the decision trail + trace := steme.GetAuditTrace(ctx, "deployment-agent-01") + fmt.Printf("Agent queried %s and got result %s", trace.Query, trace.Result) +} ``` --- diff --git a/use-cases/README.md b/use-cases/README.md index 9ed591d..9a715ec 100644 --- a/use-cases/README.md +++ b/use-cases/README.md @@ -24,6 +24,7 @@ If no → Identify which Episteme pillar makes it impossible. | Use Case | Pillars | Status | |----------|---------|--------| +| [Consumer Health Intelligence](./consumer-health-intelligence.md) | All Four | Draft | | [Financial Due Diligence](./financial-due-diligence.md) | All Four | Draft | | [Agile AI Agent Team](./agile-agent-team.md) | All Four | Draft | | Life Sciences Evidence Chains | All Four | Planned | diff --git a/use-cases/agile-agent-team.md b/use-cases/agile-agent-team.md index 6e14859..d95f100 100644 --- a/use-cases/agile-agent-team.md +++ b/use-cases/agile-agent-team.md @@ -4,7 +4,9 @@ > **Pillars Used:** First-Class Contradiction, Invalidation Cascades, Multi-Signature Consensus, Semantic Decay > **Postgres Test:** FAILED - Lifecycle stages require application-level state machines; time-travel needs temporal tables with complex joins; query audit trails don't exist natively; epoch supersession requires recursive invalidation logic -## The Catastrophe (Without Episteme) +--- + +## The Catastrophe I watched a production outage take down auth for 47 minutes because an AI agent deployed the wrong JWT configuration. @@ -26,416 +28,96 @@ The agent queried, got the proposal, treated it as truth, deployed. --- -## The Scenario +## The Team -An agile development team uses AI agents to coordinate work across auth migrations, feature flag rollouts, deployment configurations, and research. The agents need a shared knowledge base that can: +An agile development team uses AI agents to coordinate work across auth migrations, feature flag rollouts, deployment configurations, and research: -1. Distinguish proposals from approved decisions -2. Track what agents believed at any point in time (for incident investigation) -3. Log every query for audit trails -4. Handle paradigm shifts when standards change (v1 → v2 migrations) -5. Weight expert review above raw discovery - -The team consists of: -- **Lead Orchestrator**: Routes work, needs definitive current-state answers -- **Implementation Agent**: Writes code, needs approved patterns only -- **Research Agent**: Ingests docs, papers, discussions—often conflicting -- **Human Supervisor**: Reviews agent decisions, needs to trace reasoning -- **On-Call SRE**: Investigates incidents, needs time-travel debugging +| Role | Need | +|------|------| +| **Lead Orchestrator** | Routes work, needs definitive current-state answers | +| **Implementation Agent** | Writes code, needs approved patterns only | +| **Research Agent** | Ingests docs, papers, discussions—often conflicting | +| **Human Supervisor** | Reviews agent decisions, needs to trace reasoning | +| **On-Call SRE** | Investigates incidents, needs time-travel debugging | --- -## Feature 1: Lifecycle Stage (Proposed vs. Approved) +## What They Need from Episteme -### The Failure Mode +### 1. Lifecycle Stage (Proposed vs. Approved) -The Research Agent ingests an RFC proposing ES256 for JWT signing. The Implementation Agent queries "JWT signing algorithm" and gets ES256—even though it was never approved, just proposed. +**The Problem:** Research Agent ingests an RFC proposing ES256. Implementation Agent queries "JWT signing algorithm" and gets ES256—even though it was never approved. -In Postgres, both "proposed" and "approved" are just text values in a `status` column. No enforcement. No guarantees. An agent can easily query without filtering by status. - -### The Postgres Attempt - -```sql --- Track lifecycle with status column -CREATE TABLE assertions ( - id SERIAL PRIMARY KEY, - subject VARCHAR(100), - predicate VARCHAR(100), - value TEXT, - source_url TEXT, - status VARCHAR(20), -- 'proposed', 'under_review', 'approved', 'deprecated' - created_by VARCHAR(100), - created_at TIMESTAMPTZ, - confidence DECIMAL -); - --- Query: "What's the approved JWT algorithm?" -SELECT value, confidence -FROM assertions -WHERE subject = 'auth/jwt' - AND predicate = 'signing_algorithm' - AND status = 'approved' -ORDER BY created_at DESC -LIMIT 1; - --- Problem: What if agent forgets AND status = 'approved'? -SELECT value FROM assertions -WHERE subject = 'auth/jwt' AND predicate = 'signing_algorithm' -ORDER BY created_at DESC LIMIT 1; --- Returns ES256 (the proposal), not RS256 (the approved decision) -``` - -**Where it breaks:** -- Status filtering is optional—agents can (and will) forget it -- No enforcement that "proposed" and "approved" are mutually exclusive for same subject -- Transition from "proposed" → "approved" requires UPDATE, breaking append-only -- No native lens that says "only return approved items" - -### The Episteme Solution - -Lifecycle stage is a first-class field with lens enforcement: - -```rust -enum LifecycleStage { - Proposed, - UnderReview, - Approved, - Deprecated, - Rejected, -} - -struct Assertion { - // ... existing fields - pub lifecycle: LifecycleStage, -} -``` +**The Solution:** Lifecycle is a first-class field with lens enforcement: ``` -# Research Agent ingests RFC as PROPOSED -POST /assert -{ - "subject": "auth/jwt", - "predicate": "signing_algorithm", - "object": { "Text": "ES256" }, - "source_hash": "rfc_2024_001...", - "lifecycle": "Proposed", - "confidence": 0.75, - "signatures": [{ "agent_id": "research_agent", ... }] -} - -# Later, security lead approves it -POST /assert -{ - "subject": "auth/jwt", - "predicate": "signing_algorithm", - "object": { "Text": "ES256" }, - "parent_hash": "rfc_assertion_hash...", # Links to proposal - "lifecycle": "Approved", - "confidence": 0.95, - "signatures": [{ "agent_id": "security_lead", ... }] -} -``` - -Query with lens enforces lifecycle: - -``` -# Implementation Agent queries for APPROVED patterns only +# Query with lifecycle filter GET /query?subject=auth/jwt&predicate=signing_algorithm &lens=authority &lifecycle=approved --> Returns RS256 (the old approved decision) +-> Returns RS256 (approved decision) -> Proposal for ES256 is excluded by lifecycle filter - -# After approval is recorded: -GET /query?subject=auth/jwt&predicate=signing_algorithm - &lens=authority - &lifecycle=approved - --> Returns ES256 (now approved) --> With provenance showing: proposal → approval chain ``` -**Pillar:** First-Class Contradiction extended with Lifecycle. Proposals and approvals coexist in the DAG but are distinguished structurally, not by convention. +Proposals and approvals coexist in the DAG but are distinguished structurally—not by convention that agents might forget. --- -## Feature 2: Query Audit Trail +### 2. Query Audit Trail -### The Failure Mode +**The Problem:** At 3am, auth is broken. What did the deployment agent query? What result did it get? What assertions contributed? -At 3am, auth is broken. The SRE knows the deployment agent queried for JWT config. But what exactly did it query? What result did it get? What assertions contributed to that result? - -In Postgres, queries aren't logged with semantic meaning. You might have access logs, but they show "SELECT * FROM assertions WHERE..." not "deployment-agent asked about auth/jwt at 21:03:47 and got ES256 with 0.87 confidence." - -### The Postgres Attempt - -```sql --- Create query log table -CREATE TABLE query_log ( - id SERIAL PRIMARY KEY, - agent_id VARCHAR(100), - query_text TEXT, -- Raw SQL - executed_at TIMESTAMPTZ, - rows_returned INTEGER -); - --- Log every query (trigger? application code?) --- Problem: What was returned? Need to capture result set - -CREATE TABLE query_results ( - query_log_id INTEGER REFERENCES query_log(id), - result_row JSONB -); - --- Now find what deployment agent queried at 9pm -SELECT ql.*, qr.result_row -FROM query_log ql -JOIN query_results qr ON ql.id = qr.query_log_id -WHERE ql.agent_id = 'deployment-agent' - AND ql.executed_at BETWEEN '2024-01-15 20:00:00' AND '2024-01-15 22:00:00' - AND ql.query_text LIKE '%signing_algorithm%'; -``` - -**Where it breaks:** -- Query logging must be implemented in application code (every client, every language) -- Capturing result sets is expensive and complex -- No linkage between result rows and contributing source assertions -- No confidence score or lens information in the log -- "What SQL did they run" is not the same as "what question did they ask" - -### The Episteme Solution - -Query audit is built into the core engine: - -```rust -struct QueryAudit { - pub query_id: Hash, - pub agent_id: AgentId, - pub timestamp: u64, - pub subject: EntityId, - pub predicate: RelationId, - pub lens: LensType, - pub lifecycle_filter: Option, - pub result_hash: Hash, - pub result_confidence: f32, - pub contributing_assertions: Vec, -} - -struct ContributingAssertion { - pub assertion_hash: Hash, - pub weight: f32, - pub source_hash: Hash, -} -``` - -Every query is automatically logged: +**The Solution:** Every query is automatically logged with full provenance: ``` -# SRE investigates: what did deployment agent query? -GET /audit/queries?agent=deployment-agent - &from=2024-01-15T20:00:00Z - &to=2024-01-15T22:00:00Z +GET /audit/queries?agent=deployment-agent&from=-6h -> Returns: -[ - { - "query_id": "q_7f3a2b...", - "timestamp": "2024-01-15T21:03:47Z", - "subject": "auth/jwt", - "predicate": "signing_algorithm", - "lens": "authority", - "lifecycle_filter": null, # PROBLEM: agent didn't filter! - "result": { - "value": "ES256", - "confidence": 0.87 - }, - "contributing_assertions": [ - { - "hash": "rfc_2024_001...", - "lifecycle": "Proposed", # Here's the bug - "weight": 0.9, - "source": "security-rfc-2024.md" - }, - { - "hash": "prod_config_v2...", - "lifecycle": "Approved", - "weight": 0.6, - "source": "production-config.yaml" - } - ] - } -] +{ + "query_id": "q_7f3a2b...", + "timestamp": "2024-01-15T21:03:47Z", + "subject": "auth/jwt", + "predicate": "signing_algorithm", + "lifecycle_filter": null, // PROBLEM: agent didn't filter! + "result": { "value": "ES256", "confidence": 0.87 }, + "contributing_assertions": [ + { "hash": "rfc_2024_001...", "lifecycle": "Proposed", "weight": 0.9 } + ] +} ``` -The SRE immediately sees: -1. The agent didn't filter by lifecycle -2. A proposal outweighed an approved config due to recency -3. Root cause: missing lifecycle filter + authority lens favoring recent security-team docs - -``` -# Trace command for incident investigation -episteme trace --agent deployment-agent \ - --time "6 hours ago" \ - --subject "auth/*" - --> Shows all queries, results, and contributing assertions --> Sub-500ms response time -``` - -**Pillar:** This extends Multi-Signature Consensus to queries themselves. Every query is a signed, timestamped event with full provenance. +The SRE immediately sees: agent didn't filter by lifecycle, proposal outweighed approved config. --- -## Feature 3: Time-Travel Queries +### 3. Time-Travel Queries -### The Failure Mode +**The Problem:** Production is stable after rollback. Now SRE needs to understand: what was the state of knowledge at 9pm when the agent made its decision? -The SRE has rolled back the bad config. Production is stable. Now they need to understand: what was the state of knowledge at 9pm when the agent made its decision? - -The current state is useless—it reflects the correction. They need historical state. - -### The Postgres Attempt - -```sql --- Temporal tables (Postgres 9.2+ / SQL:2011) -CREATE TABLE assertions ( - -- ... columns - valid_from TIMESTAMPTZ DEFAULT NOW(), - valid_to TIMESTAMPTZ DEFAULT 'infinity' -); - --- Query state at specific time -SELECT * FROM assertions -WHERE subject = 'auth/jwt' - AND predicate = 'signing_algorithm' - AND valid_from <= '2024-01-15 21:00:00' - AND valid_to > '2024-01-15 21:00:00'; -``` - -**Where it breaks:** -- Temporal tables require schema changes and careful valid_from/valid_to management -- Queries become complex (every WHERE needs temporal bounds) -- No built-in lens application at historical point—just raw rows -- Confidence decay at historical point requires application logic -- No native "what-if" branching (what if we had known X?) - -### The Episteme Solution - -The Merkle DAG is inherently temporal. Every assertion has a timestamp. Queries accept `as_of` parameter: +**The Solution:** The Merkle DAG is inherently temporal: ``` # What did we believe at 9pm? GET /query?subject=auth/jwt&predicate=signing_algorithm - &lens=authority &as_of=2024-01-15T21:00:00Z -> Returns ES256 (the state at that moment) -> Shows which assertions existed then --> Applies lens as it would have been applied then - -# Compare to current state -GET /query?subject=auth/jwt&predicate=signing_algorithm - &lens=authority - --> Returns RS256 (post-correction) ``` -Time-travel is first-class: - -``` -# What changed in the last 24 hours? -GET /diff?subject=auth/jwt - &from=2024-01-14T21:00:00Z - &to=2024-01-15T21:00:00Z - --> Returns: -{ - "added": [ - { "hash": "rfc_2024_001...", "lifecycle": "Proposed", "value": "ES256" } - ], - "superseded": [], - "confidence_changed": [] -} -``` - -**Pillar:** Semantic Decay extended to full temporal queries. The DAG preserves all history; time-travel is O(log n) via hash lookups. +Time-travel is O(log n) via hash lookups, not complex temporal table joins. --- -## Feature 4: Paradigm Shifts (Epochs) +### 4. Paradigm Shifts (Epochs) -### The Failure Mode +**The Problem:** Security team migrates from RS256 to ES256. This affects 47 related assertions. In Postgres, you'd need 47 UPDATEs or INSERT/deprecate pairs. -The security team decides to migrate from RS256 to ES256. This isn't a simple "update one value"—it affects: -- JWT signing configuration -- Key management procedures -- Token validation logic -- Session handling -- 47 related assertions about auth - -In Postgres, you'd need to update 47 rows. Or create 47 new rows and mark the old ones deprecated. Either way, it's O(n) writes and error-prone. - -### The Postgres Attempt - -```sql --- Create epoch tracking -CREATE TABLE epochs ( - id SERIAL PRIMARY KEY, - name VARCHAR(100), - description TEXT, - supersedes_epoch_id INTEGER REFERENCES epochs(id), - supersession_type VARCHAR(20), -- 'invalidate', 'temporal', 'requires_review' - created_at TIMESTAMPTZ -); - -ALTER TABLE assertions ADD COLUMN epoch_id INTEGER REFERENCES epochs(id); - --- Migrate to new epoch: mark 47 assertions as superseded -UPDATE assertions -SET epoch_id = (SELECT id FROM epochs WHERE name = 'pre-es256-migration') -WHERE subject LIKE 'auth/%'; - --- Insert new assertions under new epoch -INSERT INTO assertions (subject, predicate, value, epoch_id, ...) -SELECT subject, predicate, new_value, new_epoch_id, ... -FROM migration_mapping; -``` - -**Where it breaks:** -- UPDATE breaks append-only semantics -- No atomic epoch transition (partial failures leave inconsistent state) -- Queries must manually filter by epoch (WHERE epoch_id = current_epoch) -- "RequiresReview" supersession has no enforcement—it's just a label -- Historical queries need complex epoch chain traversal - -### The Episteme Solution - -Epochs are first-class with atomic supersession: - -```rust -struct Epoch { - pub id: EpochId, - pub name: String, - pub superseded_by: Option, - pub supersession_type: SupersessionType, - pub effective_date: u64, -} - -enum SupersessionType { - /// Old assertions are considered incorrect - Invalidate, - /// Old assertions were true for their time, new are true now - Temporal, - /// Old assertions require human review before use - RequiresReview, - /// Old and new coexist (additive extension) - Additive, -} -``` +**The Solution:** Epochs enable O(1) supersession: ``` -# Create new epoch for ES256 migration +# Create new epoch POST /epoch { "name": "auth-es256-migration", @@ -444,131 +126,21 @@ POST /epoch "effective_date": "2024-02-01T00:00:00Z" } -# New assertions automatically belong to new epoch -POST /assert -{ - "subject": "auth/jwt", - "predicate": "signing_algorithm", - "object": { "Text": "ES256" }, - "epoch": "auth-es256-migration", - "lifecycle": "Approved", - "confidence": 0.95 -} -``` - -Queries automatically respect epoch boundaries: - -``` -# Default: returns current epoch data -GET /query?subject=auth/jwt&predicate=signing_algorithm&lens=authority --> Returns ES256 (from auth-es256-migration epoch) - -# Historical: what was true in old epoch? +# Queries automatically respect epoch boundaries GET /query?subject=auth/jwt&predicate=signing_algorithm - &lens=authority - &epoch=auth-rs256-era --> Returns RS256 +-> Returns ES256 (from new epoch) -# See what would be affected by epoch change -GET /epoch/impact?old=auth-rs256-era&new=auth-es256-migration --> Returns: -{ - "affected_assertions": 47, - "by_subject": { - "auth/jwt": 12, - "auth/keys": 8, - "auth/validation": 15, - "auth/session": 12 - }, - "supersession_type": "Temporal" -} +GET /query?subject=auth/jwt&predicate=signing_algorithm&epoch=auth-rs256-era +-> Returns RS256 (historical) ``` -**Pillar:** Invalidation Cascades at epoch granularity. O(1) supersession of entire paradigms without O(n) writes. - --- -## Feature 5: Expert Weighting (Authority Lens) +### 5. Expert Weighting (Authority Lens) -### The Failure Mode +**The Problem:** Junior dev discovers Stack Overflow answer suggesting JWT rotation every 15 minutes. Senior security engineer says "That's for high-security contexts; our standard is daily." -A junior developer discovers a Stack Overflow answer suggesting JWT rotation every 15 minutes. A senior security engineer reviews and adds context: "That's for high-security contexts; our standard is daily rotation." - -In Postgres, both are just rows. The engineer's expertise isn't structurally encoded. - -### The Postgres Attempt - -```sql -CREATE TABLE agent_reputation ( - agent_id VARCHAR(100) PRIMARY KEY, - reputation_score DECIMAL, - domain VARCHAR(50) -- 'security', 'infrastructure', 'frontend' -); - --- Query with reputation weighting -SELECT a.*, - a.confidence * ar.reputation_score AS weighted_confidence -FROM assertions a -JOIN agent_reputation ar ON a.created_by = ar.agent_id -WHERE a.subject = 'auth/jwt/rotation' -ORDER BY weighted_confidence DESC; -``` - -**Where it breaks:** -- Reputation weighting logic duplicated across every query pattern -- No cryptographic proof of who asserted what -- Reputation scores are mutable—historical queries return different results -- Domain-specific authority (security engineer vs. frontend dev) requires application logic - -### The Episteme Solution - -Multi-signature with reputation is built into the resolution engine: - -``` -# Junior dev ingests Stack Overflow finding -POST /assert -{ - "subject": "auth/jwt", - "predicate": "rotation_interval", - "object": { "Duration": "15m" }, - "source_hash": "stackoverflow_12345...", - "confidence": 0.6, - "signatures": [{ - "agent_id": "junior_dev_pubkey", - "signature": "ed25519...", - "timestamp": 1706745600 - }] -} - -# Senior security engineer co-signs with context -POST /cosign -{ - "assertion_hash": "junior_dev_assertion...", - "context": "Valid for high-security; our standard is daily", - "signatures": [{ - "agent_id": "security_lead_pubkey", - "signature": "ed25519...", - "timestamp": 1706832000 - }] -} - -# And asserts the standard -POST /assert -{ - "subject": "auth/jwt", - "predicate": "rotation_interval", - "object": { "Duration": "24h" }, - "source_hash": "internal_security_policy...", - "confidence": 0.95, - "signatures": [{ - "agent_id": "security_lead_pubkey", - "signature": "ed25519...", - "timestamp": 1706832100 - }] -} -``` - -Authority lens applies domain-weighted reputation: +**The Solution:** Multi-signature with domain-weighted reputation: ``` GET /query?subject=auth/jwt&predicate=rotation_interval @@ -578,850 +150,89 @@ GET /query?subject=auth/jwt&predicate=rotation_interval -> Returns: 24h -> security_lead has reputation 0.95 in security domain -> junior_dev has reputation 0.4 in security domain --> Authority lens weights accordingly - -GET /query?subject=auth/jwt&predicate=rotation_interval - &lens=consensus - --> Returns: 15m (more documents mention this) --> But with context: "Higher-weighted dissent from security_lead" ``` -**Pillar:** Multi-Signature Consensus with domain-specific authority. Signatures are cryptographic, immutable, and automatically weighted. +Signatures are cryptographic, immutable, and automatically weighted. --- -## Feature 6: Persistent Learning (Negative Constraints + The Gardener) +### 6. Persistent Learning (The Optimization Conflict) -### The Failure Mode: The Optimization Conflict +**The Problem:** You correct an agent: "Don't use `requests`, use `axios`." Agent says "Got it!" Next week, new session—agent uses `requests` again. Repeat forever. -You correct an agent: "No, don't use the `requests` library, use `axios`." +This is **The Optimization Conflict**: agents rely on context windows that drift. Your correction slides past; the agent reverts to base weights. -The agent says "Got it!" and uses axios... this time. Next week, new session, new context window—the agent uses `requests` again. You correct it again. Repeat forever. - -This is **The Optimization Conflict**: agents rely on System Prompts (temporary instructions in the context window) that suffer from "context drift" and "catastrophic amnesia." Your correction lives in the sliding context window; once it slides past, the agent reverts to its base weights. - -Current agents are also trained on **Golden Trajectories**—perfect, error-free examples. When they make mistakes during training, that data is discarded. They never learn "don't do X because it leads to failure." - -### The Postgres Attempt - -```sql --- Store corrections as "rules" -CREATE TABLE agent_rules ( - id SERIAL PRIMARY KEY, - subject VARCHAR(100), - predicate VARCHAR(100), -- 'must_use', 'forbidden' - value TEXT, - reason TEXT, - created_by VARCHAR(100), - created_at TIMESTAMPTZ -); - --- Query rules before acting -SELECT * FROM agent_rules -WHERE subject = 'Project_X_Http_Client' - AND predicate IN ('must_use', 'forbidden'); -``` - -**Where it breaks:** -- Agents can (and will) forget to query rules before acting -- No enforcement that rules are checked pre-flight -- No automatic reputation adjustment when agents violate rules -- Rules decay equally whether used or not—stale rules clutter the system -- No "forbidden alternative" with reason for contrastive learning - -### The Episteme Solution - -#### Step 1: The Write Path—Negative Constraint Assertion - -When you correct an agent, the system writes a **Signed Assertion** with the correction AND the forbidden alternative: +**The Solution:** Corrections become database writes that persist permanently: ``` +# Day 1: Store correction with forbidden alternative POST /assert { "subject": "Project_X_Http_Client", "predicate": "must_use_library", - "object": { "Text": "axios" }, - "meta": { - "forbidden_alternative": "requests", - "reason": "User correction: requests library is deprecated for this project" - }, - "epoch": "Project_X_Standards_2025", - "confidence": 1.0, // Maximum - came from Authority (you) - "lifecycle": "Approved", - "signatures": [{ "agent_id": "user_supervisor", ... }] -} -``` - -**Key difference from Feature 1:** This isn't just "what is true"—it's "what is true AND what was wrong." The `forbidden_alternative` gives the agent a **contrastive signal**: "axios is right BECAUSE requests is wrong." - -#### Step 2: The Learning Path—The Gardener & TrustRank - -Simply storing the correction isn't enough. The agent that made the mistake needs to "feel" the error so it hesitates next time. - -The **Gardener** (a background worker) runs Back-Propagation: - -```rust -struct GardenerJob { - pub agent_id: AgentId, - pub topic: String, - pub prediction: Value, // What agent said ("requests") - pub ground_truth: Value, // What was correct ("axios") - pub delta: f32, // How wrong (-0.3) + "object": "axios", + "meta": { "forbidden_alternative": "requests", "reason": "deprecated" }, + "confidence": 1.0 } -// The Gardener sees: -// - Agent asserted "requests" (Confidence 0.8) -// - User asserted "axios" (Confidence 1.0) -// Result: Agent's TrustRank for topic "http_libraries" drops by 0.15 -``` - -**Next time this agent tries to pick an HTTP library:** -- Its confidence is mathematically penalized -- It's forced to look for external verification (your correction) rather than guessing -- Or the system routes to a different agent with higher TrustRank on this topic - -#### Step 3: The Read Path—Lens::Constraints (Pre-Flight Check) - -One month later. New session. Empty context window. Agent is about to write code. - -**The problem:** How does the agent know to look up "http library constraints"? It hasn't decided to use an HTTP library yet. - -**The solution:** `Lens::Constraints`—a pre-flight check that runs BEFORE the agent generates output: - -``` -# Agent prepares to write code for "data fetching" -# BEFORE generating, it queries constraints on the domain: - +# Day 30: New session, agent checks constraints before coding GET /query?context=python_http&lens=constraints +-> Returns: { must_use: "axios", forbidden: "requests" } --> Returns: -{ - "constraints": [ - { - "subject": "Project_X_Http_Client", - "predicate": "must_use_library", - "value": "axios", - "forbidden": "requests", - "reason": "User correction: requests deprecated", - "confidence": 1.0, - "last_verified": "2024-01-15T10:30:00Z" - } - ] -} +# Agent uses axios. Constraint honored across sessions. ``` -**The Lens::Constraints query is cheap and token-efficient:** -- It doesn't load the whole project history -- It returns only `must_use` / `forbidden` predicates for the domain -- It acts as a "compiler error" for the agent's intent - -#### Step 4: Resurrection (Decay Reversal) - -Facts that aren't used decay over time (Semantic Decay). But what happens when a constraint IS used? - -**Resurrection:** When the agent queries the "axios" constraint and uses it successfully, the system updates `last_verified` to today. The constraint is "resurrected"—it stays at high confidence. - -```rust -struct ResurrectionEvent { - pub assertion_hash: Hash, - pub queried_at: u64, - pub used_successfully: bool, -} - -// If used_successfully: -// - last_verified = NOW() -// - confidence decay resets -// - Assertion stays in "hot path" - -// If NOT used in 6 months: -// - confidence decays toward 0 -// - Moves to "cold store" -// - Still queryable for audit, but not returned by default lenses -``` - -**Result:** Your correction from 1 month ago is still at 1.0 confidence because it was used last week. Useless facts ("I'm tired today") have decayed to 0.0 and are ignored. - -### The Complete Flow: 1 Month Later - -``` -Day 1: You correct the agent - -> System writes Negative Constraint Assertion (confidence 1.0) - -> Gardener penalizes agent's TrustRank on http_libraries - -Day 30: New session, agent is about to write code - - Agent: "I need to write a data fetch script" - - # PRE-FLIGHT CHECK (automatic, before generating) - GET /query?context=python_http&lens=constraints - - -> Returns: { must_use: "axios", forbidden: "requests", reason: "..." } - - Agent: "Got it. Using axios." - -> Generates code with `import axios` - - # RESURRECTION - -> System records: constraint was queried and used successfully - -> last_verified = NOW() - -> Constraint stays at confidence 1.0 indefinitely -``` - -### The Postgres Gap - -This pattern is impossible in Postgres because: - -1. **No Lens::Constraints:** Postgres has no native "pre-flight check" concept -2. **No TrustRank back-propagation:** Reputation adjustment requires application logic -3. **No forbidden_alternative:** Storing "what not to do" is awkward (separate table? JSON blob?) -4. **No Resurrection:** Decay and resurrection require application-level timestamp management -5. **No automatic query interception:** You can't force agents to check constraints before acting - -### Summary: Fixing the Optimization Conflict - -| Problem | System Prompt Approach | Episteme Approach | -|---------|----------------------|-------------------| -| Correction persists | Only until context window slides | Permanent in DAG | -| Forbidden alternative stored | No | Yes, with reason | -| Agent learns from mistake | No (stateless) | Yes (TrustRank penalty) | -| Pre-flight constraint check | Manual, forgettable | Lens::Constraints (enforced) | -| Old corrections decay | Equally, clogging context | Used facts stay fresh (Resurrection) | -| Token efficiency | Dump whole history | Query only relevant constraints | - -**Pillar:** This combines Semantic Decay (Resurrection), Multi-Signature Consensus (TrustRank back-propagation), and a new lens (Constraints) to move the locus of control from "inference-time instruction" to "training-time intuition." - ---- - -## SDK Integration: ADK-Go - -This section shows how AI agents actually integrate with Episteme using Google's Agent Development Kit for Go (ADK-Go). Each perspective agent has specific patterns for tool usage and callback integration. - -### Tool Definitions - -Every Episteme operation is exposed as an ADK-Go tool: - -```go -package episteme - -import ( - "google.golang.org/adk/tool" - "google.golang.org/adk/tool/functiontool" -) - -// === QUERY TOOL === -// Used by: All agents - -type QueryInput struct { - Subject string `json:"subject" jsonschema:"Entity to query (e.g., auth/jwt)"` - Predicate string `json:"predicate" jsonschema:"Relation to query (e.g., signing_algorithm)"` - Lens string `json:"lens,omitempty" jsonschema:"Resolution: consensus, authority, recency, constraints"` - Lifecycle string `json:"lifecycle,omitempty" jsonschema:"Filter: proposed, approved, deprecated"` - MinConfidence float32 `json:"min_confidence,omitempty" jsonschema:"Minimum confidence threshold (0.0-1.0)"` - AsOf string `json:"as_of,omitempty" jsonschema:"Time-travel: ISO8601 timestamp"` -} - -type QueryOutput struct { - Value interface{} `json:"value"` - Confidence float32 `json:"confidence"` - Lifecycle string `json:"lifecycle"` - Sources []Source `json:"sources"` - QueryID string `json:"query_id"` // CRITICAL: for audit trail -} - -type Source struct { - Hash string `json:"hash"` - SourceHash string `json:"source_hash"` - Weight float32 `json:"weight"` -} - -func queryEpisteme(ctx tool.Context, input QueryInput) QueryOutput { - // Call Episteme API - result, err := epistemeClient.Query(ctx, input) - if err != nil { - return QueryOutput{Error: err.Error()} - } - return result -} - -// === ASSERT TOOL === -// Used by: Research Agent, Human Supervisor - -type AssertInput struct { - Subject string `json:"subject" jsonschema:"Entity being described"` - Predicate string `json:"predicate" jsonschema:"Relation being asserted"` - Object interface{} `json:"object" jsonschema:"Value being claimed"` - SourceHash string `json:"source_hash" jsonschema:"BLAKE3 hash of evidence"` - Confidence float32 `json:"confidence" jsonschema:"Certainty level (0.0-1.0)"` - Lifecycle string `json:"lifecycle,omitempty" jsonschema:"proposed, under_review, approved"` - ParentHash string `json:"parent_hash,omitempty" jsonschema:"Hash of assertion being updated"` - Meta *AssertMeta `json:"meta,omitempty" jsonschema:"Negative constraints and metadata"` -} - -type AssertMeta struct { - ForbiddenAlternative string `json:"forbidden_alternative,omitempty"` - Reason string `json:"reason,omitempty"` -} - -type AssertOutput struct { - Hash string `json:"hash"` - Success bool `json:"success"` - Error string `json:"error,omitempty"` -} - -// === CONSTRAINT CHECK TOOL === -// Used by: Implementation Agent (pre-flight) - -type ConstraintCheckInput struct { - Context string `json:"context" jsonschema:"Domain context (e.g., python_http, auth_jwt)"` -} - -type ConstraintCheckOutput struct { - Constraints []Constraint `json:"constraints"` -} - -type Constraint struct { - Subject string `json:"subject"` - MustUse string `json:"must_use,omitempty"` - Forbidden string `json:"forbidden,omitempty"` - Reason string `json:"reason"` -} - -// === TRACE TOOL === -// Used by: On-Call SRE, Human Supervisor - -type TraceInput struct { - AgentID string `json:"agent_id" jsonschema:"Agent to trace"` - From string `json:"from" jsonschema:"Start time (ISO8601 or relative like -6h)"` - To string `json:"to,omitempty" jsonschema:"End time (default: now)"` - Subject string `json:"subject,omitempty" jsonschema:"Filter by subject pattern (e.g., auth/*)"` -} - -type TraceOutput struct { - Queries []QueryTrace `json:"queries"` -} - -type QueryTrace struct { - QueryID string `json:"query_id"` - Timestamp string `json:"timestamp"` - Subject string `json:"subject"` - Predicate string `json:"predicate"` - Lens string `json:"lens"` - Result string `json:"result"` - Confidence float32 `json:"confidence"` - Contributing []string `json:"contributing_assertions"` -} - -// === SUPERSEDE TOOL === -// Used by: Human Supervisor - -type SupersedeInput struct { - Hash string `json:"hash" jsonschema:"Assertion hash to supersede"` - Reason string `json:"reason" jsonschema:"Why this is being superseded"` - Type string `json:"type" jsonschema:"Invalidate, Temporal, RequiresReview, Additive"` -} - -type SupersedeOutput struct { - NewHash string `json:"new_hash"` - AffectedAssertions []string `json:"affected_assertions"` -} -``` - -### Callback Integration - -Callbacks are critical for enforcing constraints and maintaining audit trails: - -```go -import ( - "google.golang.org/adk/agent" - "google.golang.org/adk/agent/llmagent" - "google.golang.org/adk/model" - "google.golang.org/adk/tool" -) - -// Implementation Agent with BeforeToolCallback for constraint checking -implementationAgent, err := llmagent.New(llmagent.Config{ - Name: "implementation_agent", - Model: model, - Description: "Writes code against current approved patterns", - Instruction: "You write code. Always use approved patterns only.", - Tools: []tool.Tool{queryTool, constraintTool}, - - // CRITICAL: Check constraints BEFORE any tool that generates code - BeforeToolCallback: func(ctx agent.CallbackContext, call *tool.Call) (*tool.Call, error) { - // If agent is about to write code, check constraints first - if needsConstraintCheck(call) { - context := extractDomainContext(call) // e.g., "python_http" - constraints, err := checkConstraints(ctx, context) - if err != nil { - return nil, fmt.Errorf("constraint check failed: %w", err) - } - - for _, c := range constraints { - if violatesConstraint(call, c) { - return nil, fmt.Errorf("blocked: %s is forbidden - %s", - c.Forbidden, c.Reason) - } - } - } - return call, nil - }, - - // Log decisions for audit trail - AfterModelCallback: func(ctx agent.CallbackContext, resp *model.LLMResponse) (*model.LLMResponse, error) { - decision := extractDecision(resp) - logToEpisteme(ctx, AuditEntry{ - AgentID: ctx.Agent().Name(), - Timestamp: time.Now(), - Decision: decision, - SessionID: ctx.Session().ID(), - }) - return resp, nil - }, -}) - -// Lead Orchestrator with confidence threshold escalation -leadOrchestrator, err := llmagent.New(llmagent.Config{ - Name: "lead_orchestrator", - Model: model, - Description: "Coordinates agent team, routes work based on knowledge", - Instruction: `You coordinate the agent team. Query Episteme for current state. - If confidence < 0.8, escalate to human supervisor.`, - Tools: []tool.Tool{queryTool, delegateTool}, - OutputKey: "orchestrator_decision", // Pass to downstream agents - - // Check confidence scores and escalate if too low - AfterToolCallback: func(ctx agent.CallbackContext, call *tool.Call, result *tool.Result) (*tool.Result, error) { - if call.Name == "episteme_query" { - var queryResult QueryOutput - json.Unmarshal(result.Output, &queryResult) - - if queryResult.Confidence < 0.8 { - // Mark for human review - ctx.Session().State().Set("needs_human_review", true) - ctx.Session().State().Set("low_confidence_query", queryResult.QueryID) - } - } - return result, nil - }, -}) -``` - -### Agent-Specific Patterns - -#### Lead Orchestrator - -Fast queries with confidence thresholds for routing decisions: - -```go -// Query current auth config with confidence threshold -result := queryEpisteme(ctx, QueryInput{ - Subject: "auth/jwt", - Predicate: "signing_algorithm", - Lens: "authority", - MinConfidence: 0.8, -}) - -if result.Confidence < 0.8 { - // Escalate to human - can't route confidently - ctx.Session().State().Set("escalation_reason", - fmt.Sprintf("Confidence %.2f below threshold for %s/%s", - result.Confidence, result.Subject, result.Predicate)) - return escalateToHuman(ctx) -} - -// Route to implementation agent with high confidence -ctx.Session().State().Set("auth_config", result.Value) -return delegateTo(ctx, "implementation_agent") -``` - -#### Implementation Agent - -Queries approved patterns only, with pre-flight constraint checks: - -```go -// CRITICAL: Filter to approved lifecycle ONLY -result := queryEpisteme(ctx, QueryInput{ - Subject: "auth/jwt", - Predicate: "signing_algorithm", - Lens: "authority", - Lifecycle: "approved", // Never use proposed patterns! -}) - -if result.Lifecycle != "approved" { - return fmt.Errorf("no approved pattern found for %s/%s", - input.Subject, input.Predicate) -} - -// Pre-flight: check for forbidden alternatives -constraints := checkConstraints(ctx, "auth_jwt") -for _, c := range constraints.Constraints { - // Agent now knows: "use X, don't use Y, because Z" - // This enables contrastive learning -} -``` - -#### Research Agent - -Stores conflicting information with uncertainty: - -```go -// Store first source -assertKnowledge(ctx, AssertInput{ - Subject: "jwt_rotation", - Predicate: "best_practice", - Object: "rotate_daily", - SourceHash: hashURL("https://security.io/jwt-best-practices"), - Confidence: 0.7, // Express uncertainty - Lifecycle: "proposed", // Not approved yet -}) - -// Store contradicting source - don't flatten! -assertKnowledge(ctx, AssertInput{ - Subject: "jwt_rotation", - Predicate: "best_practice", - Object: "rotate_hourly", - SourceHash: hashURL("https://owasp.org/jwt-rotation"), - Confidence: 0.8, - Lifecycle: "proposed", -}) - -// Let Lead Orchestrator resolve via Lens::Consensus or Lens::Authority -``` - -#### Human Supervisor - -Time-travel queries and corrections with impact analysis: - -```go -// What was believed during the incident? -result := queryEpisteme(ctx, QueryInput{ - Subject: "auth/jwt", - Predicate: "signing_algorithm", - AsOf: "2024-01-15T21:00:00Z", // Time of incident -}) - -// Trace agent queries during the incident window -traces := traceQueries(ctx, TraceInput{ - AgentID: "deployment-agent", - From: "2024-01-15T20:00:00Z", - To: "2024-01-15T22:00:00Z", - Subject: "auth/*", -}) - -// Found the bug: agent queried without lifecycle filter -// Correct the record -impact := supersede(ctx, SupersedeInput{ - Hash: badAssertionHash, - Reason: "Proposal treated as approved - agent didn't filter by lifecycle", - Type: "Invalidate", -}) - -// impact.AffectedAssertions shows downstream effects -fmt.Printf("Corrected. %d downstream assertions affected.\n", - len(impact.AffectedAssertions)) -``` - -#### On-Call SRE - -Sub-second trace commands for incident investigation: - -```go -// It's 3am. Auth is broken. What happened? - -// Step 1: What did deployment agent query? (<500ms required) -traces := traceQueries(ctx, TraceInput{ - AgentID: "deployment-agent", - From: "-6h", - Subject: "auth/*", -}) - -for _, t := range traces.Queries { - fmt.Printf("[%s] %s/%s via %s -> %s (conf: %.2f)\n", - t.Timestamp, t.Subject, t.Predicate, - t.Lens, t.Result, t.Confidence) - - if len(t.Contributing) > 0 { - fmt.Printf(" Contributing: %v\n", t.Contributing) - } -} - -// Step 2: What changed in the last 24 hours? -diff := queryDiff(ctx, DiffInput{ - Subject: "auth/jwt", - From: "-24h", -}) - -// Step 3: Mark bad assertion (found via trace) -supersede(ctx, SupersedeInput{ - Hash: badAssertionHash, - Reason: "RFC proposal incorrectly treated as approved config", - Type: "Invalidate", -}) - -// Step 4: Verify fix -result := queryEpisteme(ctx, QueryInput{ - Subject: "auth/jwt", - Predicate: "signing_algorithm", - Lifecycle: "approved", -}) -fmt.Printf("Current approved value: %s\n", result.Value) -``` - -### Multi-Agent Pipeline Example - -Complete example showing agents coordinating through Episteme: - -```go -package main - -import ( - "context" - "google.golang.org/adk/agent" - "google.golang.org/adk/agent/llmagent" - "google.golang.org/adk/agent/sequentialagent" - "google.golang.org/adk/model/gemini" -) - -func main() { - ctx := context.Background() - model, _ := gemini.NewModel(ctx, "gemini-3-flash-preview", nil) - - // Research Agent: Discovers and stores knowledge - researchAgent, _ := llmagent.New(llmagent.Config{ - Name: "research_agent", - Model: model, - Description: "Researches and stores knowledge with source attribution", - Instruction: `Research the topic. Store findings with confidence scores. - Mark conflicting sources - don't resolve them.`, - Tools: []tool.Tool{assertTool, searchTool}, - OutputKey: "research_findings", - }) - - // Lead Orchestrator: Queries and routes - leadAgent, _ := llmagent.New(llmagent.Config{ - Name: "lead_orchestrator", - Model: model, - Description: "Coordinates team based on current knowledge state", - Instruction: `Query Episteme for current approved patterns. - Research findings available in {research_findings}. - If confidence >= 0.8, route to implementation. - If confidence < 0.8, flag for human review.`, - Tools: []tool.Tool{queryTool}, - OutputKey: "routing_decision", - - AfterToolCallback: confidenceEscalationCallback, - }) - - // Implementation Agent: Writes code - implAgent, _ := llmagent.New(llmagent.Config{ - Name: "implementation_agent", - Model: model, - Description: "Writes code against approved patterns only", - Instruction: `Write code for the task. - Routing decision in {routing_decision}. - ONLY use approved patterns. Check constraints first.`, - Tools: []tool.Tool{queryTool, constraintTool, writeCodeTool}, - OutputKey: "implementation", - - BeforeToolCallback: constraintEnforcementCallback, - }) - - // Sequential pipeline - pipeline, _ := sequentialagent.New(sequentialagent.Config{ - AgentConfig: agent.Config{ - Name: "AgileDevPipeline", - Description: "Research → Route → Implement with Episteme coordination", - SubAgents: []agent.Agent{researchAgent, leadAgent, implAgent}, - }, - }) - - // Run the pipeline - runner := agent.NewRunner(pipeline, sessionService) - for event, err := range runner.Run(ctx, userID, sessionID, userMessage, nil) { - if err != nil { - log.Printf("Pipeline error: %v", err) - } - handleEvent(event) - } -} -``` - -### Session State vs. Episteme - -| Use Case | Mechanism | Why | -|----------|-----------|-----| -| Agent-to-agent handoff in pipeline | Session State + `OutputKey` | Ephemeral, same conversation | -| Permanent organizational knowledge | Episteme `Assert` | Persists across sessions/agents | -| "What was decided in this conversation" | Session State | Temporary, conversation-scoped | -| "What should all agents know forever" | Episteme `Assert` + `lifecycle: approved` | Permanent, query-audited | -| Temporary working data | `temp:` prefixed state keys | Auto-cleared after session | -| Agent decision audit trail | Episteme `QueryAudit` | Immutable, time-travel enabled | +The Gardener (background worker) also adjusts TrustRank—agents that make mistakes have reduced confidence on that topic. --- ## The 5-Minute Demo ```bash -# Clone and start -git clone https://github.com/orchard9/stemedb -cd stemedb +# Start server cargo run --bin stemedb-server -# In another terminal: - -# 1. Insert a PROPOSED pattern (like an RFC) +# Insert PROPOSED pattern (RFC) curl -X POST http://localhost:8080/assert -d '{ - "subject": "auth/jwt", - "predicate": "signing_algorithm", - "object": {"Text": "ES256"}, - "lifecycle": "Proposed", - "source_hash": "rfc_2024", - "confidence": 0.75 -}' -# Save the returned hash as $PROPOSAL_HASH - -# 2. Insert an APPROVED pattern (current production) -curl -X POST http://localhost:8080/assert -d '{ - "subject": "auth/jwt", - "predicate": "signing_algorithm", - "object": {"Text": "RS256"}, - "lifecycle": "Approved", - "source_hash": "prod_config", - "confidence": 0.9 + "subject": "auth/jwt", "predicate": "signing_algorithm", + "object": {"Text": "ES256"}, "lifecycle": "Proposed", "confidence": 0.75 }' -# 3. Query WITHOUT lifecycle filter (the bug!) +# Insert APPROVED pattern (production) +curl -X POST http://localhost:8080/assert -d '{ + "subject": "auth/jwt", "predicate": "signing_algorithm", + "object": {"Text": "RS256"}, "lifecycle": "Approved", "confidence": 0.9 +}' + +# Query WITHOUT lifecycle filter (the bug!) curl "http://localhost:8080/query?subject=auth/jwt&predicate=signing_algorithm&lens=recency" -# Returns ES256 (the proposal, because it's newer) -# THIS IS THE BUG - agent would deploy wrong config +# Returns ES256 (proposal, most recent) -# 4. Query WITH lifecycle filter (the fix!) +# Query WITH lifecycle filter (the fix!) curl "http://localhost:8080/query?subject=auth/jwt&predicate=signing_algorithm&lens=recency&lifecycle=approved" -# Returns RS256 (correct - only approved items) - -# 5. Later: Approve the proposal -curl -X POST http://localhost:8080/assert -d '{ - "subject": "auth/jwt", - "predicate": "signing_algorithm", - "object": {"Text": "ES256"}, - "lifecycle": "Approved", - "parent_hash": "'$PROPOSAL_HASH'", - "epoch": "es256-migration", - "confidence": 0.95 -}' - -# 6. Now the same query returns ES256 -curl "http://localhost:8080/query?subject=auth/jwt&predicate=signing_algorithm&lens=recency&lifecycle=approved" -# Returns ES256 (now approved) - -# 7. Check audit trail -curl "http://localhost:8080/audit/queries?subject=auth/jwt&limit=5" -# Shows all queries, results, and contributing assertions - -# 8. Time travel: what did we believe yesterday? -curl "http://localhost:8080/query?subject=auth/jwt&predicate=signing_algorithm&lens=recency&lifecycle=approved&as_of=2024-01-14T00:00:00Z" -# Returns RS256 (pre-migration state) - -# 9. Store a NEGATIVE CONSTRAINT (correction with forbidden alternative) -curl -X POST http://localhost:8080/assert -d '{ - "subject": "Project_X_Http_Client", - "predicate": "must_use_library", - "object": {"Text": "axios"}, - "meta": {"forbidden_alternative": "requests", "reason": "User correction"}, - "lifecycle": "Approved", - "confidence": 1.0 -}' - -# 10. Pre-flight constraint check (what Lens::Constraints returns) -curl "http://localhost:8080/query?context=python_http&lens=constraints" -# Returns: { must_use: "axios", forbidden: "requests", reason: "..." } -# Agent sees this BEFORE generating code - -# 11. Query resurrects the constraint (updates last_verified) -curl "http://localhost:8080/query?subject=Project_X_Http_Client&predicate=must_use_library&lens=authority" -# The constraint is now "resurrected" - stays at high confidence +# Returns RS256 (correct) ``` -**Time to value:** Under 5 minutes to see lifecycle filtering, query audit, time-travel, and negative constraints working. - ---- - -## What Postgres CAN Do - -**Postgres is sufficient for:** -- Storing assertions with status columns -- Basic recency queries -- Simple audit logging (with application code) -- Temporal tables for history (with schema complexity) - -**Postgres requires significant application code for:** -- Enforcing lifecycle filters on every query -- Query audit with result provenance -- Domain-weighted authority calculations -- Epoch chain traversal for supersession - -**Postgres cannot cleanly handle:** -- O(1) epoch supersession (bulk paradigm shifts) -- Lens-based resolution with lifecycle enforcement -- Cryptographic multi-signature with immutable provenance -- Time-travel with lens application at historical point -- Query audit with contributing assertion weights -- Sub-100ms trace command for incident investigation - ---- - -## The Incident Investigation Pattern - -When something breaks: - -```bash -# 1. What did the agent query? -episteme trace --agent deployment-agent --time "6 hours ago" --subject "auth/*" - -# 2. What assertions contributed? -episteme show --hash $ASSERTION_HASH --provenance - -# 3. Mark bad assertion as superseded -episteme supersede --hash $BAD_HASH --reason "Proposal treated as approved" \ - --type "Invalidate" - -# 4. See impact -episteme cascade --root $BAD_HASH - -# 5. Verify correction propagated -episteme query --subject auth/jwt --predicate signing_algorithm --lifecycle approved -``` - -**SRE's 3am workflow:** Query → Trace → Identify → Correct → Verify. Under 10 minutes. - --- ## Summary: Why Episteme for Agent Teams? -| Problem | Postgres Approach | Episteme Approach | Pillar | -|---------|------------------|-------------------|--------| -| Proposal vs. Approved | Status column (unenforced) | Lifecycle enum with lens enforcement | First-Class Contradiction | -| Query audit trail | Application-level logging | Built-in with provenance | Multi-Signature Consensus | -| Time-travel debugging | Temporal tables + complex joins | Native `as_of` parameter | Semantic Decay | -| Paradigm shift (RS256→ES256) | O(n) updates or migrations | O(1) epoch supersession | Invalidation Cascades | -| Expert vs. junior weighting | Join tables with reputation | Cryptographic signatures + Authority lens | Multi-Signature Consensus | -| Corrections forgotten (Optimization Conflict) | System prompt drift | Negative Constraints + Resurrection | Semantic Decay | -| Agents repeat mistakes | No learning (stateless) | TrustRank back-propagation (The Gardener) | Multi-Signature Consensus | -| Pre-flight safety checks | Manual, forgettable | Lens::Constraints (enforced) | First-Class Contradiction | +| Problem | Traditional Approach | Episteme Approach | +|---------|---------------------|-------------------| +| Proposal vs. Approved | Status column (unenforced) | Lifecycle enum with lens enforcement | +| Query audit trail | Application-level logging | Built-in with provenance | +| Time-travel debugging | Temporal tables + complex joins | Native `as_of` parameter | +| Paradigm shift (RS256→ES256) | O(n) updates | O(1) epoch supersession | +| Expert vs. junior weighting | Join tables with reputation | Cryptographic signatures + Authority lens | +| Corrections forgotten | System prompt drift | Negative Constraints + Resurrection | +| Agents repeat mistakes | No learning (stateless) | TrustRank back-propagation | -The 47-minute outage I witnessed happened because an AI agent couldn't distinguish a proposal from an approved decision. Episteme ensures that distinction is structural—not a convention that agents might forget. - -**The deeper problem:** Agents are stateless. They rely on fragile system prompts that suffer from context drift. When you correct an agent, that correction lives in the sliding context window—once it slides past, the agent reverts to its base weights. Episteme solves this by treating corrections as **database writes** that persist permanently, are retrieved token-efficiently via Lens::Constraints, and stay fresh through Resurrection. +The 47-minute outage happened because an AI agent couldn't distinguish a proposal from an approved decision. Episteme ensures that distinction is structural—not a convention that agents might forget. --- -## Regulatory / Compliance Considerations +## Further Reading -For production AI agent deployments: - -- **Model Governance:** Query audit trails demonstrate what context influenced agent decisions -- **Incident Response:** Time-travel enables post-mortem without reconstructing state -- **Change Control:** Lifecycle stages enforce approval workflows for configuration changes -- **Audit Requirements:** Immutable Merkle DAG provides tamper-evident decision provenance - -Episteme doesn't replace change management—it provides the data substrate that makes AI agent decisions auditable and correctable. +- **SDK Integration:** See [.claude/guides/integrations/adk-go-episteme.md](../.claude/guides/integrations/adk-go-episteme.md) for ADK-Go tool definitions, callback patterns, and multi-agent pipeline examples. +- **Presentation:** See [docs/presentations/](../docs/presentations/) for the visual walkthrough of this use case. +- **Architecture:** See [architecture.md](../architecture.md) for Episteme internals. diff --git a/use-cases/consumer-health-intelligence.md b/use-cases/consumer-health-intelligence.md new file mode 100644 index 0000000..e02d63c --- /dev/null +++ b/use-cases/consumer-health-intelligence.md @@ -0,0 +1,499 @@ +# Consumer Health Intelligence: The Living Truth Layer + +> **Tier:** Strategic Pilot +> **Pillars Used:** First-Class Contradiction, Invalidation Cascades, Multi-Signature Consensus, Semantic Decay +> **Postgres Test:** FAILED - Source-class hierarchy with cross-tier signal detection requires graph traversal impossible in relational schema; anecdotal clustering with escalation triggers has no SQL equivalent; temporal consensus snapshots across millions of assertions from heterogeneous sources break materialized views; decay rates that vary by source class cannot be expressed in WHERE clauses. + +--- + +## The Catastrophe + +In March 2024, a woman considering Semaglutide for weight loss Googled "Ozempic side effects." Here is what she encountered in one hour: + +- Her doctor said: "Well-tolerated, nausea is common but transient." +- The FDA label said: Risk of thyroid C-cell tumors (boxed warning, animal studies). +- Reddit r/Ozempic (1.2M members): Hundreds of posts about "Ozempic face," hair loss, muscle wasting, gastroparesis. +- A TikTok with 4M views: "Ozempic gave me stomach paralysis." +- A NEJM meta-analysis: "No statistically significant increase in gastroparesis." +- A FAERS query: 8,500+ gastroparesis reports filed for Semaglutide. +- Her friend: "I lost 40 lbs and feel amazing." + +She had seven sources. They contradicted each other. She had no way to weigh them. She made her decision based on whichever source she encountered last. + +Six months later, the FDA updated the Ozempic label to include intestinal obstruction warnings. The Reddit community had been flagging this for a year. + +**The failure mode:** Consumers navigate health decisions using search engines that rank by engagement, not validity. Contradictions are hidden behind algorithmic curation. Anecdotal signals that precede clinical validation are dismissed as noise -- until they aren't. And when guidance changes, there is no mechanism to notify people whose decisions were based on the old consensus. + +This is the same failure mode that drove vaccine hesitancy. Not the existence of misinformation -- the absence of a system that could hold "this is what the clinical trials showed" alongside "this is what people are reporting" alongside "this is what changed since you last looked" without collapsing into either false certainty or false equivalence. + +--- + +## The Domain: Living Health Topics + +A "living health topic" is any subject where: + +1. **Evidence is actively accumulating** (new trials, new reports, new guidance) +2. **Sources span from gold-standard to anecdotal** (RCTs to Reddit) +3. **Public interest is high** and information spreads faster than validation +4. **Guidance changes** and prior guidance doesn't self-destruct +5. **Individual experience varies** and population-level data doesn't capture edge cases + +Examples: GLP-1 agonists, COVID vaccines, SSRI discontinuation, hormone replacement therapy, long COVID, PFAS exposure, mRNA technology, microplastics, ultra-processed food. + +Every one of these has the same structural problem: the truth is not a single value. It is a distribution across source classes, changing over time, with different validity at different moments. + +--- + +## What Episteme Enables + +### Source-Class Hierarchy + +The core innovation for consumer health is treating **source authority as structural, not cosmetic.** Every assertion entering Episteme carries a source class that determines its weight, decay rate, and role in consensus calculation. + +``` +POST /assert +{ + "subject": "semaglutide/adverse-effects/gastroparesis", + "predicate": "risk_level", + "object": { "Text": "No statistically significant increase" }, + + "source_class": "tier-1", + "source": { + "type": "meta-analysis", + "journal": "NEJM", + "doi": "10.1056/NEJMoa2403123", + "sample_size": 14847, + "study_design": "RCT" + }, + + "confidence": 0.92, + "lifecycle": "current" +} +``` + +``` +POST /assert +{ + "subject": "semaglutide/adverse-effects/gastroparesis", + "predicate": "risk_level", + "object": { "Text": "Experienced severe gastroparesis after 3 months" }, + + "source_class": "tier-5", + "source": { + "type": "patient-report", + "platform": "reddit", + "subreddit": "r/Ozempic", + "upvotes": 847, + "replies": 234 + }, + + "confidence": 0.3, + "lifecycle": "current" +} +``` + +Both assertions coexist. Neither overwrites the other. But they are not equal, and the system knows it. + +**Source-Class Tiers:** + +| Tier | Source Type | Base Weight | Decay Half-Life | Example | +|------|-----------|-------------|-----------------|---------| +| 0 | Regulatory action | 1.0 | None (until superseded) | FDA label change, EMA withdrawal | +| 1 | Peer-reviewed RCT, meta-analysis | 0.9 | 2 years | NEJM, Lancet, JAMA | +| 2 | Observational study, real-world evidence | 0.7 | 1 year | Insurance claims data, EHR studies | +| 3 | Pharmacovigilance | 0.5 | 18 months | FAERS reports, EudraVigilance | +| 4 | Clinician anecdote, case report | 0.4 | 6 months | Conference presentations, case series | +| 5 | Patient community | 0.2 | 3 months | Reddit, forums, patient registries | +| 6 | Media, influencer, commercial | 0.1 | 30 days | TikTok, news articles, pharma marketing | + +**Postgres Test:** A relational schema can store these tiers as an enum column. It cannot make the tier structurally affect query resolution, decay calculation, and consensus weighting without rebuilding Episteme's lens system in application code. + +--- + +### Feature 1: The Nuance Query (Layered Consensus) + +#### The Failure Mode + +Consumer health tools give you one answer. Google's AI Overview picks one. WebMD picks one. Your doctor picks one. None of them show you the shape of the disagreement. + +The vaccine parallel: "Are COVID vaccines safe?" had a single clinical answer (yes, statistically) and a complex experiential answer (most people were fine; some had significant adverse reactions; the definition of "significant" was itself contested). Collapsing this to a single answer created the trust gap. + +#### The Episteme Solution + +``` +GET /query + ?subject=semaglutide/adverse-effects/gastroparesis + &lens=layered-consensus + +-> Returns: +{ + "subject": "semaglutide/adverse-effects/gastroparesis", + "consensus_by_tier": { + "regulatory": { + "position": "Listed as adverse reaction (post-marketing)", + "effective_date": "2024-01-12", + "assertion_count": 2 + }, + "clinical_evidence": { + "position": "No statistically significant increase in Phase III", + "conflict_score": 0.34, + "assertion_count": 12, + "note": "3 observational studies show elevated signal" + }, + "pharmacovigilance": { + "position": "8,547 FAERS reports (disproportionality signal detected)", + "trend": "increasing", + "assertion_count": 8547 + }, + "patient_community": { + "position": "Widely reported, high-engagement posts", + "sentiment": "negative", + "cluster_size": 4200, + "assertion_count": 23891 + } + }, + "overall_conflict_score": 0.72, + "guidance_changed_since": "2024-01-12", + "summary": "Clinical trials show low incidence; post-marketing reports and patient communities report higher rates; FDA added to label January 2024." +} +``` + +The consumer sees layers, not a single answer. They see where the tiers agree and where they don't. The disagreement is the information. + +**Pillar:** First-Class Contradiction. Episteme doesn't resolve the gastroparesis question -- it shows the consumer the shape of the evidence across every source class. + +--- + +### Feature 2: Anecdotal Signal Detection (Cluster Escalation) + +#### The Failure Mode + +Patient communities flagged gastroparesis risk, "Ozempic face" (facial volume loss), and hair loss months to years before these appeared in clinical literature or regulatory action. In every traditional system, this signal was noise -- unstructured, self-reported, no controlled comparison. + +The same pattern played out with COVID vaccines and myocarditis. VAERS reports were accumulating signal before the clinical confirmation. The problem was not that the signal didn't exist -- it was that no system could surface it structurally without either dismissing it (underweighting) or amplifying it beyond its evidentiary basis (overweighting). + +#### The Episteme Solution + +Episteme tracks assertion clusters at lower tiers. When a cluster crosses a density threshold, it generates an **escalation assertion** -- a meta-claim that says "this topic has unusual anecdotal density and deserves investigation." + +``` +# Background process (The Gardener) detects clustering +POST /assert +{ + "subject": "semaglutide/adverse-effects/hair-loss", + "predicate": "escalation_signal", + "object": { + "Text": "Anecdotal cluster detected" + }, + + "source_class": "meta", + "meta": { + "trigger": "cluster_threshold", + "tier_5_assertions": 1847, + "tier_5_growth_rate": "312/month", + "tier_1_assertions": 0, + "clinical_gap": true, + "earliest_report": "2022-06-14", + "sentiment_polarity": -0.78 + }, + + "confidence": 0.6, + "lifecycle": "under-review" +} +``` + +The escalation assertion does not claim hair loss is a real side effect. It claims that patient communities are reporting it at a rate that warrants clinical attention. This is the difference between amplifying noise and surfacing signal. + +``` +GET /query + ?subject=semaglutide/adverse-effects/hair-loss + &lens=layered-consensus + +-> Returns: +{ + "clinical_evidence": { + "position": "Not reported in Phase III trials", + "assertion_count": 0 + }, + "patient_community": { + "position": "Widely reported", + "cluster_size": 1847, + "growth_rate": "312/month" + }, + "escalation": { + "status": "under-review", + "signal": "Anecdotal cluster with no clinical counterpart", + "gap_detected": "2023-09-01" + } +} +``` + +A consumer sees: "Clinical trials didn't study this, but a lot of people are reporting it. This gap has been flagged for investigation." That is an honest answer. It is not "yes," it is not "no," and it is not "we don't know." It is "here is exactly what each source class says, and here is where they disagree." + +**Pillar:** Multi-Signature Consensus + Invalidation Cascades. The cluster detection acts as a low-tier consensus mechanism. The escalation assertion triggers review without granting anecdotal data clinical authority. + +--- + +### Feature 3: Guidance Change Propagation + +#### The Failure Mode + +In January 2024, the FDA updated the Semaglutide label to include intestinal obstruction. Everyone who researched Semaglutide before January 2024 made their decision based on a label that no longer reflects the regulatory position. There is no mechanism to propagate this change to prior consumers of that information. + +With COVID vaccines, guidance changed repeatedly: eligibility criteria, booster recommendations, age restrictions, brand preferences. Each change invalidated prior guidance, but people continued operating on the version they last encountered. + +#### The Episteme Solution + +Episteme's epoch system and invalidation cascades propagate changes structurally: + +``` +POST /epoch/supersede +{ + "old_epoch": "semaglutide-label-pre-2024", + "new_epoch": "semaglutide-label-2024-01", + "type": "Augment", + "reason": "FDA label update: intestinal obstruction warning added", + "sections_affected": ["adverse-reactions", "warnings-and-precautions"], + "effective_date": "2024-01-12" +} +``` + +When a consumer returns to the topic -- or when an agent queries on their behalf -- the system surfaces what changed: + +``` +GET /query + ?subject=semaglutide/adverse-effects + &lens=layered-consensus + &since=2023-10-01 + +-> Returns: +{ + "changes_since_query": [ + { + "date": "2024-01-12", + "type": "regulatory", + "change": "FDA label updated: intestinal obstruction added to warnings", + "impact": "12 prior assertions in adverse-effects now reference superseded label" + } + ], + "current_consensus": { ... } +} +``` + +The consumer doesn't just get today's answer. They get "here is what changed since you last looked." This is the mechanism that was missing for vaccine guidance -- not a static FAQ, but a living diff. + +**Pillar:** Invalidation Cascades. Label changes propagate to all downstream assertions. Prior consensus snapshots remain for audit ("what did we believe in October?") but the current query reflects the updated state. + +--- + +### Feature 4: Source-Aware Decay + +#### The Failure Mode + +Medical knowledge decays at different rates depending on its source. A Phase III RCT from 2022 is still highly relevant. A Reddit post from 2022 about side effects may reflect a formulation or dosing protocol that has since changed. A TikTok from 2022 may reference guidance that has been updated three times. + +Uniform decay (or no decay) means stale anecdotes compete with current clinical evidence. This is how "Ozempic causes X" persists in search results long after the claim has been investigated and contextualized. + +#### The Episteme Solution + +Decay rates are tied to source class: + +``` +GET /query + ?subject=semaglutide/efficacy/weight-loss + &lens=authority + &decay=source-aware + +-> Resolution: + NEJM meta-analysis (2023): base 0.92 * decay(2yr, age=8mo) = 0.87 effective + Reddit anecdote (2022): base 0.20 * decay(3mo, age=26mo) = 0.00 effective (expired) + FAERS aggregate (2024): base 0.50 * decay(18mo, age=2mo) = 0.49 effective + TikTok claim (2023): base 0.10 * decay(30d, age=14mo) = 0.00 effective (expired) + FDA label (2024): base 1.00 * decay(none) = 1.00 effective +``` + +Old anecdotes fade. Old clinical evidence persists. Regulatory actions persist until superseded. The hot path reflects the current evidentiary landscape without manual curation. + +A consumer querying today doesn't see a 2022 TikTok claim alongside a 2024 FDA label update. The system's decay has already handled the temporal relevance. + +**Pillar:** Semantic Decay. Source-class-aware decay ensures the knowledge metabolism matches the actual shelf life of each evidence type. + +--- + +### Feature 5: Time Travel for Personal Audit + +#### The Failure Mode + +A consumer started Semaglutide in June 2023. In January 2024, new warnings were added. They want to know: "What was the known risk profile when I started?" -- not to assign blame, but to understand whether their decision was reasonable given available evidence. + +This same question was asked millions of times about COVID vaccines: "What was known about myocarditis risk when I got my second dose in April 2021?" + +No consumer tool can answer this. Google results reflect today's knowledge. The FDA website reflects the current label. The clinical evidence has been updated. The historical state is gone. + +#### The Episteme Solution + +``` +GET /query + ?subject=semaglutide/adverse-effects + &lens=layered-consensus + &as_of=2023-06-15 + +-> Returns the consensus snapshot from June 2023: +{ + "regulatory": { + "position": "Boxed warning: thyroid C-cell tumors (animal). No GI obstruction warning.", + "label_version": "2021-06-04" + }, + "clinical_evidence": { + "position": "Nausea common, no gastroparesis signal in Phase III", + "assertion_count": 8 + }, + "patient_community": { + "position": "Growing reports of gastroparesis, hair loss", + "cluster_size": 340, + "escalation": "not yet triggered (threshold: 500)" + } +} +``` + +The consumer can see exactly what was known, at every tier, at the moment they made their decision. This is the audit trail that health decisions currently lack. + +**Pillar:** First-Class Contradiction (temporal). The append-only DAG preserves every historical state. Time travel is a hash lookup, not a reconstruction. + +--- + +### Feature 6: The Disagreement Dashboard + +#### The Failure Mode + +Consumer health tools present certainty. "Ozempic is safe" or "Ozempic is dangerous." This false binary creates two failure modes: blind trust or conspiracy-driven rejection. The vaccine discourse demonstrated both at scale. + +The actual evidence is nuanced: safe for most, with specific risks for specific populations, with emerging signals that may or may not be validated, and with guidance that changes as evidence accumulates. No consumer-facing tool presents this structure. + +#### The Episteme Solution + +The Skeptic Lens generates a disagreement map -- not to create doubt, but to show where certainty exists and where it doesn't: + +``` +GET /query + ?subject=semaglutide + &lens=skeptic + &scope=adverse-effects + +-> Returns: +{ + "resolved": [ + { + "topic": "nausea", + "consensus": "Common, dose-dependent, generally transient", + "conflict_score": 0.08, + "all_tiers_agree": true + } + ], + "active_disagreement": [ + { + "topic": "gastroparesis", + "conflict_score": 0.72, + "tier_positions": { + "clinical": "Low incidence in trials", + "pharmacovigilance": "Disproportionality signal", + "patient_community": "Widely reported" + }, + "note": "FDA added to label 2024-01" + }, + { + "topic": "muscle_loss", + "conflict_score": 0.61, + "tier_positions": { + "clinical": "Lean mass loss ~40% of total weight lost", + "patient_community": "Significant concern, exercise mitigation discussed" + } + } + ], + "emerging_signal": [ + { + "topic": "hair_loss", + "source": "tier-5 cluster", + "clinical_evidence": "none", + "cluster_size": 1847, + "status": "under-review" + } + ] +} +``` + +Three categories: resolved (everyone agrees), active disagreement (tiers disagree, with each position shown), and emerging signal (anecdotal clusters without clinical counterpart). A consumer can see where the science is settled, where it's contested, and where patient experience is ahead of clinical evidence. + +--- + +## The Vaccine Parallel + +Everything described above applies directly to COVID vaccines (and any future vaccine discourse): + +| GLP-1 Scenario | Vaccine Equivalent | +|----------------|-------------------| +| FDA label update adds gastroparesis | EUA conditions change, booster guidance shifts | +| Reddit flags hair loss 12 months before clinical study | VAERS myocarditis reports accumulate before confirmation | +| 10-K vs 10-Q revenue discrepancy | Different efficacy numbers from different trial endpoints | +| TikTok influencer claims "stomach paralysis" | Social media claims about fertility, magnetism, etc. | +| Patient makes decision based on June 2023 data | Person gets vaccinated based on March 2021 guidance | +| Competing analyst extractions from same proxy | Different researchers interpret same trial differently | + +The structural problem is identical: heterogeneous sources, varying authority, temporal validity, and a consumer who has no mechanism to see the shape of the evidence. + +Episteme doesn't tell the consumer what to believe. It shows them what each source class says, where they agree, where they disagree, what changed, and when. + +--- + +## The "Everything" Ingestion Challenge + +This use case intentionally targets the hardest version of the problem: ingest **all** data about a topic. Not a curated corpus. Everything. + +### Data Sources + +| Source | Volume | Source Class | Ingestion Method | +|--------|--------|-------------|-----------------| +| PubMed / biorxiv | ~5,000 papers for GLP-1 | Tier 1-2 | API crawl, structured extraction | +| ClinicalTrials.gov | ~800 registered trials | Tier 1-2 | API, protocol/results parsing | +| FDA labels, safety communications | ~50 documents | Tier 0 | EDGAR/DailyMed scraping | +| FAERS adverse event reports | ~50,000 for semaglutide | Tier 3 | openFDA API | +| Reddit (r/Ozempic, r/Semaglutide, r/loseit) | ~500,000 posts/comments | Tier 5 | API, NLP extraction | +| Patient forums (MyFitnessPal, etc.) | ~100,000 posts | Tier 5 | Crawl, NLP extraction | +| News articles | ~10,000 | Tier 6 | News API, extraction | +| Social media (TikTok, Instagram, X) | ~1,000,000+ mentions | Tier 6 | Firehose sample, NLP | +| Manufacturer press releases | ~200 | Tier 6 | Crawl | +| Insurance claims data (if available) | Millions of records | Tier 2 | Batch ingest | + +Total assertion volume: **millions.** This is where Episteme's architecture is tested. The append-only DAG, source-class-aware decay, and lens-based resolution must operate at scale without degrading query latency. + +### The Noise Problem + +At this volume, Tier 5-6 assertions outnumber Tier 0-2 by 100:1 or more. Without source-class hierarchy, any consensus mechanism would be dominated by volume rather than validity. This is exactly what happened with vaccine discourse -- the volume of social media claims overwhelmed the signal from clinical evidence in every system that treated all sources equally. + +Episteme's response: source class is not a filter applied after retrieval. It is structural. The lens system weights assertions by class during resolution, not after. A million Tier 6 assertions cannot outvote a single Tier 0 regulatory action. But they can signal that something is happening -- and the escalation mechanism ensures that signal is visible. + +--- + +## Summary: Why Episteme for Consumer Health? + +| Problem | Current Approach | Episteme Approach | +|---------|-----------------|-------------------| +| Doctor says X, Reddit says Y | Pick one (or Google picks for you) | **Layered consensus** shows both with source class | +| Guidance changes, old advice persists | Manual updates, no propagation | **Invalidation cascades** propagate changes | +| Anecdotal signal precedes clinical validation | Dismissed as noise | **Cluster escalation** surfaces signal without false authority | +| "Was my decision reasonable?" | No historical record | **Time travel** to consensus at decision point | +| Stale TikTok claims compete with current RCTs | Same search ranking | **Source-aware decay** fades noise, preserves evidence | +| False certainty creates distrust | One answer, take it or leave it | **Disagreement dashboard** shows shape of evidence | +| 1M social posts vs 5 clinical trials | Volume wins | **Source-class hierarchy** weights by validity, not volume | + +The trust crisis in health information is not caused by the existence of contradictory claims. It is caused by the absence of a system that can hold all claims, from every source, and show a consumer the structure of the evidence without either collapsing it into false certainty or abandoning them to navigate it alone. + +Episteme is that system. + +--- + +## Further Reading + +- **GLP-1 Pharma R&D Use Case:** See [glp1-living-review.md](./glp1-living-review.md) for the clinical research team version. +- **Architecture:** See [architecture.md](../architecture.md) for Episteme internals. +- **Presentation:** See [docs/presentations/](../docs/presentations/) for visual walkthroughs. diff --git a/use-cases/glp1-living-review.md b/use-cases/glp1-living-review.md new file mode 100644 index 0000000..2d54f39 --- /dev/null +++ b/use-cases/glp1-living-review.md @@ -0,0 +1,203 @@ +# BioTech/Pharma: The Living Systematic Review (GLP-1) + +> **Tier:** Strategic Pilot +> **Pillars Used:** First-Class Contradiction, Paradigm Supersession (Epochs), Multi-Signature Consensus, Semantic Decay, Visual Anchoring +> **Postgres Test:** FAILED - Negation blindness in vector search leads to dangerous clinical recommendations; manual decay calculations in SQL cannot handle rapidly shifting paradigms; provenance for "Dark Matter" (failed trials) is lost. + +## The Hazard (Without Episteme) + +I observed a medical research team spend 4 months updating a systematic review on "GLP-1 muscle loss," only for it to be obsolete 72 hours after publication. + +The problem wasn't their talent; it was their database. They used a standard RAG system (Vector DB + Postgres) to ingest 5,000 papers. When a new trial (STEP-1) contradicted earlier pilot data regarding lean mass preservation, the vector database retrieved *both* papers with nearly identical similarity scores. + +Because standard embeddings suffer from **Negation Blindness**, the search for "Does Semaglutide cause muscle loss?" returned: +1. "Trial A: Semaglutide causes significant muscle loss." +2. "Trial B: Semaglutide does *not* cause significant muscle loss." + +The LLM, attempting to synthesize these into a "canonical" answer, hallucinated a cautious "maybe," averaging out the truth. The team missed the fact that Trial B was a Phase III RCT while Trial A was a small, unblinded pilot. By failing to structurally model the **Conflict**, they served a dangerous "Generative Soup" instead of a valid scientific consensus. + +**The failure mode:** Vector databases optimize for plausibility (similarity), not validity. In Pharma, plausibility is a patient safety risk. + +--- + +## The Scenario: "Operation LeanMass" + +A pharmaceutical R&D team is monitoring the "GLP-1 Agonist" landscape (Semaglutide, Tirzepatide). Evidence is exploding from PubMed, biorxiv, and clinicaltrial.gov. + +The system must: +1. Model contradictory study results explicitly (Muscle Loss vs. Preservation). +2. Handle "Paradigm Shifts" (e.g., a new FDA label update superseding all prior trial assertions). +3. Weight results by Journal Reputation and Agent TrustRank (Multi-Sig). +4. Apply aggressive "Semantic Decay" to knowledge with a 73-day half-life. +5. Anchor claims to pixels (Screenshots of primary data charts) to detect data drift. + +--- + +## Feature 1: First-Class Contradiction (The Skeptic Lens) + +### The Failure Mode +In medical research, "Truth" isn't a binary; it's a distribution. When two studies disagree, picking a "winner" or averaging the results hides the very signal a researcher needs: **Variance**. + +### The Episteme Solution + +``` +POST /assert +{ + "subject": "Semaglutide", + "predicate": "muscle_sparing_effect", + "object": { "Boolean": false }, + "source_hash": "study_low_n_2021", + "confidence": 0.7, + "signatures": [{ "agent_id": "pubmed_crawler_01", ... }] +} + +POST /assert +{ + "subject": "Semaglutide", + "predicate": "muscle_sparing_effect", + "object": { "Boolean": true }, + "source_hash": "step_1_trial_2023", + "confidence": 0.95, + "signatures": [{ "agent_id": "reviewer_agent_alpha", ... }] +} +``` + +Querying the "State of Truth": + +``` +GET /query?subject=Semaglutide&predicate=muscle_sparing_effect&lens=skeptic +-> Returns { + conflict_score: 0.88, + variance: "High", + candidates: [ + { val: false, trust: 0.12 }, + { val: true, trust: 0.86 } + ] + } +``` + +**Pillar:** First-Class Contradiction. The `Lens::Skeptic` identifies that the scientific community is in disagreement, preventing the "Hallucination Cascade" where the agent averages two opposites. + +--- + +## Feature 2: Paradigm Supersession (Epochs) + +### The Failure Mode +The FDA releases a new "Warning Label" for a drug class. Instantly, 500 assertions regarding "Safe Use Guidelines" derived from older trials are now legally and clinically superseded. In Postgres, you either run O(N) updates or build complex `is_active` logic that fails to capture *why* things changed. + +### The Episteme Solution + +Assertions are tagged with an **Epoch**. When the paradigm shifts, we supersede the entire epoch in one O(1) operation. + +``` +POST /epoch/supersede +{ + "old_epoch": "pre_fda_label_2024", + "new_epoch": "post_fda_label_2024", + "type": "Invalidate", + "reason": "FDA Boxed Warning added for thyroid C-cell tumors" +} +``` + +**Effect:** +Queries using `Lens::EpochAware` automatically ignore the 500 assertions from the `pre_fda` epoch. They remain in the `Lens::History` for audit but are "excreted" from the current reasoning context. + +**Pillar:** Paradigm Management. Truth isn't just updated; it is evolved. Epochs allow the system to "change its mind" at scale. + +--- + +## Feature 3: Multi-Signature Consensus (The Hive) + +### The Failure Mode +A pre-print on biorxiv claims a breakthrough. A week later, a peer-reviewed letter in *The Lancet* refutes it. In a standard database, these are just two rows of text. + +### The Episteme Solution + +Agents don't just "write" data; they **Co-Sign** it. + +``` +-- Agent A (Researcher) finds a fact +POST /assert { ... object: "High Efficacy", agent_id: "researcher_bot" } + +-- Agent B (Peer Reviewer) validates the fact +POST /cosign { + "assertion_hash": "...", + "agent_id": "lancet_reviewer_agent", + "signature_weight": 100 // Tier 1 Authority +} +``` + +**Pillar:** Multi-Signature Consensus. The database implements a **Supreme Court** logic where expert agents (Tier 1) can override the noise of the "Worker Agent" swarm without deleting the history of the debate. + +--- + +## Feature 4: Semantic Decay (Knowledge Half-Life) + +### The Failure Mode +Medical knowledge has a t½ of ~73 days. A "cutting-edge" study from 6 months ago is often "Old News" or "Stale." In Postgres, data lives forever until deleted. + +### The Episteme Solution + +Episteme applies a **Confidence Half-Life** at read time. + +``` +GET /query?subject=Tirzepatide&predicate=weight_loss_pct&lens=authority&decay=73d +``` + +- **Study (10 days old):** 0.95 Confidence -> **0.91 Effective Confidence** +- **Study (200 days old):** 0.95 Confidence -> **0.14 Effective Confidence** + +The old data "fades" from the hot path automatically. If a "Super Curator" (The Judge) re-verifies the old study, it triggers a **Resurrection Event**, resetting the decay timer. + +**Pillar:** Semantic Decay. Episteme handles the "Metabolism" of knowledge, ensuring agents don't hallucinate based on "Context Pollution" from stale research. + +--- + +## Feature 5: Visual Anchoring (AVAM) + +### The Failure Mode +An agent extracts "15% Weight Loss" from a PDF. It turns out the OCR misread "1.5%". The text assertion is now a lie. + +### The Episteme Solution + +Assertions are anchored to a **Visual Hash (pHash)** of the primary data source. + +``` +POST /assert +{ + "subject": "STEP-1_Trial", + "predicate": "primary_endpoint", + "object": { "Percent": 14.9 }, + "visual_hash": "0x8f3c...", // pHash of the results table in the PDF + "confidence": 1.0 +} +``` + +When the **Super Curator** audits the fact, it uses a multimodal LLM to look at the *pixels* of the chart, not the *text* of the assertion. If the pixels don't match the claim, the assertion is invalidated. + +**Pillar:** Visual Anchoring. StemeDB anchors truth to the physical evidence (pixels), providing the "Eye" that prevents text-based drift. + +--- + +## The Home Run: "The Simulator" + +By running "Operation LeanMass" on Episteme, the team passively builds the **"Simulator"**: +- A dataset of every "Failed Experiment" (Negative Trajectories). +- A log of every "High-Confidence Failure" (Conflict). +- A library of "Golden Paths" (Resolved Consensus). + +This data is licensed to model labs to train **Medical Reasoning Adapters**, making StemeDB the primary supplier of "experience" for the next generation of Scientific AGI. + +--- + +## Summary: Why Episteme for BioTech? + +| Problem | Vector DB Approach | Episteme Approach | +|---------|--------------------|-------------------| +| "Muscle Loss" vs "No Loss" | Averages/Hallucinates | **Skeptic Lens** flags variance | +| FDA Label Update | O(N) Manual Update | **Epoch Supersession** (O(1)) | +| Pre-print vs Lancet | Text Similarity | **Multi-Sig** reputation weight | +| Knowledge Half-Life | Metadata sorting | **Semantic Decay** (auto-fading) | +| OCR Errors | Trust the text | **Visual Anchoring** (pHash) | + +In Pharma, the "Git for Truth" isn't a feature; it's the only way to avoid the liability of a hallucinating research swarm. diff --git a/vision.md b/vision.md index a53496d..086cc4b 100644 --- a/vision.md +++ b/vision.md @@ -11,8 +11,9 @@ Current databases (Postgres, Neo4j, Vector DBs) suffer from **The Tower of Babel **Episteme** rejects the idea of a single, static "database state." Instead, it models knowledge as a **Probabilistic Marketplace**. * **Democracy:** Truth is established via high-velocity consensus (Voting), not just overwrite privileges. +* **Federation:** "Waze for Deep Research." Free users contribute to a Global Lattice; Paid users get private silos. * **Economics:** Reasoning has a cost. The system enforces efficiency via "The Meter." -* **Evolution:** The database doesn't just store data; it exports training sets ("The Simulator") to make agents smarter. +* **Curation:** We are not the Ministry of Truth. We are the App Store for Trust. Users subscribe to "Trust Packs" (e.g., "Mayo Clinic", "Rust Experts") to filter reality. ## 2. The Core Data Model: The Hyper-Edge @@ -45,8 +46,8 @@ struct Assertion { Reading is a compute-heavy operation. You must apply a **Lens** to collapse the probabilistic field into a concrete answer. To ensure sub-millisecond latency, Episteme uses **Materialized Views** to pre-calculate the results of standard lenses. ### Standard Lenses -1. **Lens::Consensus:** Returns the value with the highest cluster density (Weighted by Multi-Sig). *Materialized for speed.* -2. **Lens::Authority:** Filters by Agent Reputation (TrustRank). +1. **Lens::Consensus:** Returns the value with the highest cluster density (Weighted by Trust Pack). +2. **Lens::Authority:** Filters by subscribed **Trust Packs** (e.g., "Show me reality according to The Financial Times"). 3. **Lens::Recency:** Returns the latest assertion, ignoring history. 4. **Lens::EpochAware:** Validates assertions against the *current* paradigm, filtering superseded epochs. 5. **Lens::Skeptic:** Returns the *variance* between claims (identifies high-conflict/unstable truth). @@ -60,18 +61,18 @@ Agents need to simulate futures without polluting the main branch. Episteme supp To avoid write contention, Episteme separates the "Candidate" (Assertion) from the "Votes" (Signatures). * Agents write **Votes** to a high-speed append-only log ("The Ballot Box"). * A background process aggregates these votes to update the Materialized View. -* This allows thousands of agents to "vote" on a fact simultaneously without locking. ### 4.3. The Hive: Learning & Trust -Episteme uses **Recursive TrustRank Optimization** to advance the team's collective intelligence. -* **Closed-Loop Learning:** When an Agent's prediction is met by a reality assertion, the delta is back-propagated to the Agent's Reputation score. -* **The Simulator (Mid-Training):** A pipeline that converts high-confidence failure logs into **Synthetic Trajectories**, allowing agents to be fine-tuned on their own history (creating a "Memory Adapter" LoRA). +* **Trust Packs (The Curator Economy):** Users can publish and subscribe to Lists of Trusted Agents. + * *Example:* "The Skeptical Cardio Pack" filters out low-quality studies. + * *Mechanism:* A BitSet overlay that filters the Consensus Lens efficiently. +* **The Simulator (Mid-Training):** A pipeline that converts high-confidence failure logs into **Synthetic Trajectories**. +* **The Super Curator (Judicial Branch):** A specialized swarm of "Reviewer Agents" that audits high-variance facts. ### 4.4. The Meter: Economics of Reasoning Deep Research is computationally expensive. Episteme enforces **Temporal Advantage Normalization (TAN)**. * **Budgeting:** Every Job carries a budget (tokens/dollars). * **Throttling:** The system rejects "Fork Reality" requests if the projected cost exceeds the Value of Information. -* **Efficiency Rewards:** Agents receive positive reinforcement signals for solving problems under budget. ## 5. Architecture: The Rust Stack