export declare const SCHEMA_SQL = "-- ============================================================================\n-- AgentDB State-of-the-Art Memory Schema\n-- ============================================================================\n-- Implements 5 cutting-edge memory patterns for autonomous agents:\n-- 1. Reflexion-style episodic replay\n-- 2. Skill library from trajectories\n-- 3. Structured mixed memory (facts + summaries)\n-- 4. Episodic segmentation and consolidation\n-- 5. Graph-aware recall\n-- ============================================================================\n\n-- Enable foreign keys\nPRAGMA foreign_keys = ON;\n\n-- ============================================================================\n-- Pattern 1: Reflexion-Style Episodic Replay\n-- ============================================================================\n-- Store self-critique and outcomes after each attempt.\n-- Retrieve nearest failures and fixes before the next run.\n\nCREATE TABLE IF NOT EXISTS episodes (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n ts INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n session_id TEXT NOT NULL,\n task TEXT NOT NULL,\n input TEXT,\n output TEXT,\n critique TEXT,\n reward REAL DEFAULT 0.0,\n success BOOLEAN DEFAULT 0,\n latency_ms INTEGER,\n tokens_used INTEGER,\n tags TEXT, -- JSON array of tags\n metadata JSON,\n created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))\n);\n\nCREATE INDEX IF NOT EXISTS idx_episodes_ts ON episodes(ts DESC);\nCREATE INDEX IF NOT EXISTS idx_episodes_session ON episodes(session_id);\nCREATE INDEX IF NOT EXISTS idx_episodes_reward ON episodes(reward DESC);\nCREATE INDEX IF NOT EXISTS idx_episodes_task ON episodes(task);\n\n-- Vector embeddings for episodes (384-dim for all-MiniLM-L6-v2)\n-- Will use sqlite-vec when available, fallback to JSON storage\nCREATE TABLE IF NOT EXISTS episode_embeddings (\n episode_id INTEGER PRIMARY KEY,\n embedding BLOB NOT NULL, -- Float32Array as BLOB\n embedding_model TEXT DEFAULT 'all-MiniLM-L6-v2',\n FOREIGN KEY(episode_id) REFERENCES episodes(id) ON DELETE CASCADE\n);\n\n-- ============================================================================\n-- Pattern 2: Skill Library from Trajectories\n-- ============================================================================\n-- Promote high-reward traces into reusable \"skills\" with typed IO.\n\nCREATE TABLE IF NOT EXISTS skills (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT UNIQUE NOT NULL,\n description TEXT,\n signature JSON NOT NULL, -- {inputs: {...}, outputs: {...}}\n code TEXT, -- Tool call manifest or code template\n success_rate REAL DEFAULT 0.0,\n uses INTEGER DEFAULT 0,\n avg_reward REAL DEFAULT 0.0,\n avg_latency_ms INTEGER DEFAULT 0,\n created_from_episode INTEGER, -- Source episode ID\n created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n last_used_at INTEGER,\n metadata JSON,\n FOREIGN KEY(created_from_episode) REFERENCES episodes(id)\n);\n\nCREATE INDEX IF NOT EXISTS idx_skills_success ON skills(success_rate DESC);\nCREATE INDEX IF NOT EXISTS idx_skills_uses ON skills(uses DESC);\nCREATE INDEX IF NOT EXISTS idx_skills_name ON skills(name);\n\n-- Skill relationships and composition\nCREATE TABLE IF NOT EXISTS skill_links (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n parent_skill_id INTEGER NOT NULL,\n child_skill_id INTEGER NOT NULL,\n relationship TEXT NOT NULL, -- 'prerequisite', 'alternative', 'refinement', 'composition'\n weight REAL DEFAULT 1.0,\n metadata JSON,\n FOREIGN KEY(parent_skill_id) REFERENCES skills(id) ON DELETE CASCADE,\n FOREIGN KEY(child_skill_id) REFERENCES skills(id) ON DELETE CASCADE,\n UNIQUE(parent_skill_id, child_skill_id, relationship)\n);\n\nCREATE INDEX IF NOT EXISTS idx_skill_links_parent ON skill_links(parent_skill_id);\nCREATE INDEX IF NOT EXISTS idx_skill_links_child ON skill_links(child_skill_id);\n\n-- Skill embeddings for semantic search\nCREATE TABLE IF NOT EXISTS skill_embeddings (\n skill_id INTEGER PRIMARY KEY,\n embedding BLOB NOT NULL,\n embedding_model TEXT DEFAULT 'all-MiniLM-L6-v2',\n FOREIGN KEY(skill_id) REFERENCES skills(id) ON DELETE CASCADE\n);\n\n-- ============================================================================\n-- Pattern 3: Structured Mixed Memory (Facts + Summaries)\n-- ============================================================================\n-- Combine facts, summaries, and vectors to avoid over-embedding.\n\n-- Atomic facts as triples (subject-predicate-object)\nCREATE TABLE IF NOT EXISTS facts (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n subject TEXT NOT NULL,\n predicate TEXT NOT NULL,\n object TEXT NOT NULL,\n source_type TEXT, -- 'episode', 'skill', 'external', 'inferred'\n source_id INTEGER,\n confidence REAL DEFAULT 1.0,\n created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n expires_at INTEGER, -- TTL for temporal facts\n metadata JSON\n);\n\nCREATE INDEX IF NOT EXISTS idx_facts_subject ON facts(subject);\nCREATE INDEX IF NOT EXISTS idx_facts_predicate ON facts(predicate);\nCREATE INDEX IF NOT EXISTS idx_facts_object ON facts(object);\nCREATE INDEX IF NOT EXISTS idx_facts_source ON facts(source_type, source_id);\nCREATE INDEX IF NOT EXISTS idx_facts_expires ON facts(expires_at) WHERE expires_at IS NOT NULL;\n\n-- Notes and summaries with semantic embeddings\nCREATE TABLE IF NOT EXISTS notes (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n title TEXT,\n text TEXT NOT NULL,\n summary TEXT, -- Condensed version for context\n note_type TEXT DEFAULT 'general', -- 'insight', 'constraint', 'goal', 'observation'\n importance REAL DEFAULT 0.5,\n access_count INTEGER DEFAULT 0,\n last_accessed_at INTEGER,\n created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n metadata JSON\n);\n\nCREATE INDEX IF NOT EXISTS idx_notes_type ON notes(note_type);\nCREATE INDEX IF NOT EXISTS idx_notes_importance ON notes(importance DESC);\nCREATE INDEX IF NOT EXISTS idx_notes_accessed ON notes(last_accessed_at DESC);\n\n-- Note embeddings (only for summaries to reduce storage)\nCREATE TABLE IF NOT EXISTS note_embeddings (\n note_id INTEGER PRIMARY KEY,\n embedding BLOB NOT NULL,\n embedding_model TEXT DEFAULT 'all-MiniLM-L6-v2',\n FOREIGN KEY(note_id) REFERENCES notes(id) ON DELETE CASCADE\n);\n\n-- ============================================================================\n-- Pattern 4: Episodic Segmentation and Consolidation\n-- ============================================================================\n-- Segment long tasks into events and consolidate into compact memories.\n\nCREATE TABLE IF NOT EXISTS events (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n episode_id INTEGER, -- Link to parent episode\n step INTEGER NOT NULL,\n phase TEXT, -- 'planning', 'execution', 'reflection', 'learning'\n role TEXT, -- 'user', 'assistant', 'system', 'tool'\n content TEXT NOT NULL,\n features JSON, -- Extracted features for learning\n tool_calls JSON, -- Tool invocations in this event\n created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n FOREIGN KEY(episode_id) REFERENCES episodes(id) ON DELETE CASCADE\n);\n\nCREATE INDEX IF NOT EXISTS idx_events_session ON events(session_id, step);\nCREATE INDEX IF NOT EXISTS idx_events_phase ON events(phase);\nCREATE INDEX IF NOT EXISTS idx_events_episode ON events(episode_id);\n\n-- Consolidated memories from event windows\nCREATE TABLE IF NOT EXISTS consolidated_memories (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n start_event_id INTEGER NOT NULL,\n end_event_id INTEGER NOT NULL,\n phase TEXT,\n summary TEXT NOT NULL,\n key_insights JSON, -- Extracted learnings\n success_patterns JSON, -- What worked\n failure_patterns JSON, -- What didn't work\n quality_score REAL DEFAULT 0.5,\n created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n FOREIGN KEY(start_event_id) REFERENCES events(id),\n FOREIGN KEY(end_event_id) REFERENCES events(id)\n);\n\nCREATE INDEX IF NOT EXISTS idx_consolidated_session ON consolidated_memories(session_id);\nCREATE INDEX IF NOT EXISTS idx_consolidated_quality ON consolidated_memories(quality_score DESC);\n\n-- ============================================================================\n-- Pattern 5: Graph-Aware Recall (Lightweight GraphRAG)\n-- ============================================================================\n-- Build a lightweight GraphRAG overlay for experiences.\n\nCREATE TABLE IF NOT EXISTS exp_nodes (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n kind TEXT NOT NULL, -- 'task', 'skill', 'concept', 'tool', 'outcome'\n label TEXT NOT NULL,\n payload JSON,\n centrality REAL DEFAULT 0.0, -- Graph importance metric\n created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))\n);\n\nCREATE INDEX IF NOT EXISTS idx_exp_nodes_kind ON exp_nodes(kind);\nCREATE INDEX IF NOT EXISTS idx_exp_nodes_label ON exp_nodes(label);\nCREATE INDEX IF NOT EXISTS idx_exp_nodes_centrality ON exp_nodes(centrality DESC);\n\nCREATE TABLE IF NOT EXISTS exp_edges (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n src_node_id INTEGER NOT NULL,\n dst_node_id INTEGER NOT NULL,\n relationship TEXT NOT NULL, -- 'requires', 'produces', 'similar_to', 'refines', 'part_of'\n weight REAL DEFAULT 1.0,\n metadata JSON,\n created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n FOREIGN KEY(src_node_id) REFERENCES exp_nodes(id) ON DELETE CASCADE,\n FOREIGN KEY(dst_node_id) REFERENCES exp_nodes(id) ON DELETE CASCADE,\n UNIQUE(src_node_id, dst_node_id, relationship)\n);\n\nCREATE INDEX IF NOT EXISTS idx_exp_edges_src ON exp_edges(src_node_id);\nCREATE INDEX IF NOT EXISTS idx_exp_edges_dst ON exp_edges(dst_node_id);\nCREATE INDEX IF NOT EXISTS idx_exp_edges_rel ON exp_edges(relationship);\n\n-- Node embeddings for graph-augmented retrieval\nCREATE TABLE IF NOT EXISTS exp_node_embeddings (\n node_id INTEGER PRIMARY KEY,\n embedding BLOB NOT NULL,\n embedding_model TEXT DEFAULT 'all-MiniLM-L6-v2',\n FOREIGN KEY(node_id) REFERENCES exp_nodes(id) ON DELETE CASCADE\n);\n\n-- ============================================================================\n-- Memory Management and Scoring\n-- ============================================================================\n\n-- Track memory quality scores and usage statistics\nCREATE TABLE IF NOT EXISTS memory_scores (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n memory_type TEXT NOT NULL, -- 'episode', 'skill', 'note', 'consolidated'\n memory_id INTEGER NOT NULL,\n quality_score REAL NOT NULL,\n novelty_score REAL,\n relevance_score REAL,\n utility_score REAL,\n computed_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n metadata JSON\n);\n\nCREATE INDEX IF NOT EXISTS idx_memory_scores_type ON memory_scores(memory_type, memory_id);\nCREATE INDEX IF NOT EXISTS idx_memory_scores_quality ON memory_scores(quality_score DESC);\n\n-- Memory access patterns for adaptive retrieval\nCREATE TABLE IF NOT EXISTS memory_access_log (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n memory_type TEXT NOT NULL,\n memory_id INTEGER NOT NULL,\n query TEXT,\n relevance_score REAL,\n was_useful BOOLEAN,\n feedback JSON,\n accessed_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))\n);\n\nCREATE INDEX IF NOT EXISTS idx_access_log_type ON memory_access_log(memory_type, memory_id);\nCREATE INDEX IF NOT EXISTS idx_access_log_time ON memory_access_log(accessed_at DESC);\n\n-- ============================================================================\n-- Consolidation and Maintenance\n-- ============================================================================\n\n-- Track consolidation jobs and their results\nCREATE TABLE IF NOT EXISTS consolidation_runs (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n job_type TEXT NOT NULL, -- 'episode_to_skill', 'event_to_memory', 'deduplication', 'pruning'\n records_processed INTEGER DEFAULT 0,\n records_created INTEGER DEFAULT 0,\n records_deleted INTEGER DEFAULT 0,\n duration_ms INTEGER,\n status TEXT DEFAULT 'pending', -- 'pending', 'running', 'completed', 'failed'\n error TEXT,\n started_at INTEGER,\n completed_at INTEGER,\n metadata JSON\n);\n\nCREATE INDEX IF NOT EXISTS idx_consolidation_status ON consolidation_runs(status);\nCREATE INDEX IF NOT EXISTS idx_consolidation_type ON consolidation_runs(job_type);\n\n-- ============================================================================\n-- Views for Common Queries\n-- ============================================================================\n\n-- High-value episodes for skill creation\nCREATE VIEW IF NOT EXISTS skill_candidates AS\nSELECT\n task,\n COUNT(*) as attempt_count,\n AVG(reward) as avg_reward,\n AVG(success) as success_rate,\n MAX(id) as latest_episode_id,\n GROUP_CONCAT(id) as episode_ids\nFROM episodes\nWHERE ts > strftime('%s', 'now') - 86400 * 7 -- Last 7 days\nGROUP BY task\nHAVING attempt_count >= 3 AND avg_reward >= 0.7;\n\n-- Top performing skills\nCREATE VIEW IF NOT EXISTS top_skills AS\nSELECT\n s.*,\n COALESCE(s.success_rate, 0) * 0.4 +\n COALESCE(s.uses, 0) * 0.0001 +\n COALESCE(s.avg_reward, 0) * 0.6 as composite_score\nFROM skills s\nORDER BY composite_score DESC;\n\n-- Recent high-quality memories\nCREATE VIEW IF NOT EXISTS recent_quality_memories AS\nSELECT\n 'episode' as type, id, task as title, critique as content, reward as score, created_at\nFROM episodes\nWHERE reward >= 0.7 AND ts > strftime('%s', 'now') - 86400 * 3\nUNION ALL\nSELECT\n 'note' as type, id, title, summary as content, importance as score, created_at\nFROM notes\nWHERE importance >= 0.7 AND created_at > strftime('%s', 'now') - 86400 * 3\nUNION ALL\nSELECT\n 'consolidated' as type, id, session_id as title, summary as content, quality_score as score, created_at\nFROM consolidated_memories\nWHERE quality_score >= 0.7 AND created_at > strftime('%s', 'now') - 86400 * 3\nORDER BY created_at DESC;\n\n-- ============================================================================\n-- Triggers for Auto-Maintenance\n-- ============================================================================\n\n-- Update skill usage statistics\nCREATE TRIGGER IF NOT EXISTS update_skill_last_used\nAFTER UPDATE OF uses ON skills\nBEGIN\n UPDATE skills SET last_used_at = strftime('%s', 'now') WHERE id = NEW.id;\nEND;\n\n-- Update note access tracking\nCREATE TRIGGER IF NOT EXISTS update_note_access\nAFTER UPDATE OF access_count ON notes\nBEGIN\n UPDATE notes SET last_accessed_at = strftime('%s', 'now') WHERE id = NEW.id;\nEND;\n\n-- Auto-update timestamps\nCREATE TRIGGER IF NOT EXISTS update_skill_timestamp\nAFTER UPDATE ON skills\nBEGIN\n UPDATE skills SET updated_at = strftime('%s', 'now') WHERE id = NEW.id;\nEND;\n\nCREATE TRIGGER IF NOT EXISTS update_note_timestamp\nAFTER UPDATE ON notes\nBEGIN\n UPDATE notes SET updated_at = strftime('%s', 'now') WHERE id = NEW.id;\nEND;\n\n-- ============================================================================\n-- Initialization Complete\n-- ============================================================================\n-- Schema version: 1.0.0\n-- Compatible with: SQLite 3.35+, sqlite-vec (optional), sqlite-vss (optional)\n-- WASM compatible: Yes (via SQLite-WASM + OPFS)\n--\n-- Performance Optimization:\n-- For production deployments, apply composite index migration for 30-50% query speedup:\n-- - Migration file: db/migrations/003_composite_indexes.sql\n-- - Adds 40+ composite indexes for common query patterns\n-- - Trade-off: 2x slower writes, +15-20% storage (acceptable for read-heavy workloads)\n-- - See: db/migrations/README.md for details\n-- ============================================================================\n"; export declare const FRONTIER_SCHEMA_SQL = "-- ============================================================================\n-- AgentDB Frontier Features Schema Extension\n-- ============================================================================\n-- Implements cutting-edge memory features:\n-- 1. Causal Memory Graph - Store edges with causal strength, not just similarity\n-- 2. Explainable Recall Certificates - Provenance and justification tracking\n-- ============================================================================\n\n-- ============================================================================\n-- FEATURE 1: Causal Memory Graph\n-- ============================================================================\n\n-- Causal edges between memories with intervention effects\nCREATE TABLE IF NOT EXISTS causal_edges (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n from_memory_id INTEGER NOT NULL,\n from_memory_type TEXT NOT NULL, -- 'episode', 'skill', 'note', 'fact'\n to_memory_id INTEGER NOT NULL,\n to_memory_type TEXT NOT NULL,\n\n -- Traditional similarity\n similarity REAL NOT NULL DEFAULT 0.0,\n\n -- Causal metrics\n uplift REAL, -- E[y|do(x)] - E[y]\n confidence REAL DEFAULT 0.5, -- Confidence in causal claim\n sample_size INTEGER, -- Number of observations\n\n -- Evidence and provenance\n evidence_ids TEXT, -- JSON array of proof IDs\n experiment_ids TEXT, -- JSON array of A/B test IDs\n confounder_score REAL, -- Likelihood of confounding\n\n -- Metadata\n mechanism TEXT, -- Hypothesized causal mechanism\n created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n last_validated_at INTEGER,\n\n metadata JSON\n\n -- Note: Foreign keys removed to allow flexible causal edges between any concepts\n -- from_memory_id and to_memory_id can be 0 for abstract causal relationships\n);\n\nCREATE INDEX IF NOT EXISTS idx_causal_edges_from ON causal_edges(from_memory_id, from_memory_type);\nCREATE INDEX IF NOT EXISTS idx_causal_edges_to ON causal_edges(to_memory_id, to_memory_type);\nCREATE INDEX IF NOT EXISTS idx_causal_edges_uplift ON causal_edges(uplift DESC);\nCREATE INDEX IF NOT EXISTS idx_causal_edges_confidence ON causal_edges(confidence DESC);\n\n-- Causal experiments (A/B tests for uplift estimation)\nCREATE TABLE IF NOT EXISTS causal_experiments (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT NOT NULL,\n hypothesis TEXT NOT NULL,\n treatment_id INTEGER NOT NULL, -- Memory used as treatment\n treatment_type TEXT NOT NULL,\n control_id INTEGER, -- Optional control memory\n\n -- Experiment design\n start_time INTEGER NOT NULL,\n end_time INTEGER,\n sample_size INTEGER DEFAULT 0,\n\n -- Results\n treatment_mean REAL,\n control_mean REAL,\n uplift REAL, -- treatment_mean - control_mean\n p_value REAL,\n confidence_interval_low REAL,\n confidence_interval_high REAL,\n\n -- Status\n status TEXT DEFAULT 'running', -- 'running', 'completed', 'failed'\n\n metadata JSON,\n created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))\n);\n\nCREATE INDEX IF NOT EXISTS idx_causal_experiments_status ON causal_experiments(status);\nCREATE INDEX IF NOT EXISTS idx_causal_experiments_treatment ON causal_experiments(treatment_id, treatment_type);\n\n-- Causal observations (individual data points)\nCREATE TABLE IF NOT EXISTS causal_observations (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n experiment_id INTEGER NOT NULL,\n episode_id INTEGER NOT NULL,\n\n -- Treatment assignment\n is_treatment BOOLEAN NOT NULL,\n\n -- Outcome\n outcome_value REAL NOT NULL,\n outcome_type TEXT, -- 'reward', 'success', 'latency'\n\n -- Context\n context JSON,\n observed_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n\n FOREIGN KEY(experiment_id) REFERENCES causal_experiments(id) ON DELETE CASCADE,\n FOREIGN KEY(episode_id) REFERENCES episodes(id) ON DELETE CASCADE\n);\n\nCREATE INDEX IF NOT EXISTS idx_causal_observations_experiment ON causal_observations(experiment_id);\nCREATE INDEX IF NOT EXISTS idx_causal_observations_treatment ON causal_observations(is_treatment);\n\n-- ============================================================================\n-- FEATURE 2: Explainable Recall Certificates\n-- ============================================================================\n\n-- Recall certificates for provenance and justification\nCREATE TABLE IF NOT EXISTS recall_certificates (\n id TEXT PRIMARY KEY, -- UUID or hash\n query_id TEXT NOT NULL,\n query_text TEXT NOT NULL,\n\n -- Retrieved chunks\n chunk_ids TEXT NOT NULL, -- JSON array\n chunk_types TEXT NOT NULL, -- JSON array matching chunk_ids\n\n -- Minimal hitting set (justification)\n minimal_why TEXT, -- JSON array of chunk IDs that justify the answer\n redundancy_ratio REAL, -- len(chunk_ids) / len(minimal_why)\n completeness_score REAL, -- Fraction of query requirements met\n\n -- Provenance chain\n merkle_root TEXT NOT NULL,\n source_hashes TEXT, -- JSON array of source hashes\n proof_chain TEXT, -- JSON Merkle proof\n\n -- Policy compliance\n policy_proof TEXT, -- Proof of policy adherence\n policy_version TEXT,\n access_level TEXT, -- 'public', 'internal', 'confidential', 'restricted'\n\n -- Metadata\n created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n latency_ms INTEGER,\n\n metadata JSON\n);\n\nCREATE INDEX IF NOT EXISTS idx_recall_certificates_query ON recall_certificates(query_id);\nCREATE INDEX IF NOT EXISTS idx_recall_certificates_created ON recall_certificates(created_at DESC);\n\n-- Provenance sources (for Merkle tree construction)\nCREATE TABLE IF NOT EXISTS provenance_sources (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n source_type TEXT NOT NULL, -- 'episode', 'skill', 'note', 'fact', 'external'\n source_id INTEGER NOT NULL,\n\n -- Content hash\n content_hash TEXT NOT NULL UNIQUE,\n\n -- Lineage\n parent_hash TEXT, -- Previous version\n derived_from TEXT, -- JSON array of parent hashes\n\n -- Metadata\n created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n creator TEXT, -- User or system identifier\n\n metadata JSON\n);\n\nCREATE INDEX IF NOT EXISTS idx_provenance_sources_type ON provenance_sources(source_type, source_id);\nCREATE INDEX IF NOT EXISTS idx_provenance_sources_hash ON provenance_sources(content_hash);\nCREATE INDEX IF NOT EXISTS idx_provenance_sources_parent ON provenance_sources(parent_hash);\n\n-- Justification paths (why a chunk was included)\nCREATE TABLE IF NOT EXISTS justification_paths (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n certificate_id TEXT NOT NULL,\n chunk_id TEXT NOT NULL,\n chunk_type TEXT NOT NULL,\n\n -- Justification\n reason TEXT NOT NULL, -- 'semantic_match', 'causal_link', 'prerequisite', 'constraint'\n necessity_score REAL NOT NULL, -- How essential is this chunk (0-1)\n\n -- Path to query satisfaction\n path_elements TEXT, -- JSON array describing reasoning path\n\n FOREIGN KEY(certificate_id) REFERENCES recall_certificates(id) ON DELETE CASCADE\n);\n\nCREATE INDEX IF NOT EXISTS idx_justification_paths_cert ON justification_paths(certificate_id);\nCREATE INDEX IF NOT EXISTS idx_justification_paths_chunk ON justification_paths(chunk_id, chunk_type);\n\n-- ============================================================================\n-- Views for Causal Analysis\n-- ============================================================================\n\n-- High-confidence causal relationships\nCREATE VIEW IF NOT EXISTS strong_causal_edges AS\nSELECT\n ce.*,\n CASE\n WHEN ce.uplift > 0 THEN 'positive'\n WHEN ce.uplift < 0 THEN 'negative'\n ELSE 'neutral'\n END as effect_direction,\n ce.uplift * ce.confidence as causal_impact\nFROM causal_edges ce\nWHERE ce.confidence >= 0.7\n AND ce.uplift IS NOT NULL\n AND ABS(ce.uplift) >= 0.1\nORDER BY ABS(ce.uplift) * ce.confidence DESC;\n\n-- Causal chains (multi-hop reasoning)\nCREATE VIEW IF NOT EXISTS causal_chains AS\nWITH RECURSIVE chain(from_id, to_id, depth, path, total_uplift) AS (\n SELECT from_memory_id, to_memory_id, 1,\n from_memory_id || '->' || to_memory_id,\n uplift\n FROM causal_edges\n WHERE confidence >= 0.6\n\n UNION ALL\n\n SELECT chain.from_id, ce.to_memory_id, chain.depth + 1,\n chain.path || '->' || ce.to_memory_id,\n chain.total_uplift + ce.uplift\n FROM chain\n JOIN causal_edges ce ON chain.to_id = ce.from_memory_id\n WHERE chain.depth < 5\n AND ce.confidence >= 0.6\n AND chain.path NOT LIKE '%' || ce.to_memory_id || '%'\n)\nSELECT * FROM chain\nWHERE depth >= 2\nORDER BY total_uplift DESC, depth ASC;\n\n-- ============================================================================\n-- Views for Explainability\n-- ============================================================================\n\n-- Certificate quality metrics\nCREATE VIEW IF NOT EXISTS certificate_quality AS\nSELECT\n rc.id,\n rc.query_id,\n rc.completeness_score,\n rc.redundancy_ratio,\n COUNT(jp.id) as justification_count,\n AVG(jp.necessity_score) as avg_necessity,\n rc.latency_ms\nFROM recall_certificates rc\nLEFT JOIN justification_paths jp ON rc.id = jp.certificate_id\nGROUP BY rc.id;\n\n-- Provenance lineage depth\nCREATE VIEW IF NOT EXISTS provenance_depth AS\nWITH RECURSIVE lineage(hash, depth) AS (\n SELECT content_hash, 0\n FROM provenance_sources\n WHERE parent_hash IS NULL\n\n UNION ALL\n\n SELECT ps.content_hash, lineage.depth + 1\n FROM lineage\n JOIN provenance_sources ps ON lineage.hash = ps.parent_hash\n)\nSELECT\n ps.id,\n ps.source_type,\n ps.source_id,\n ps.content_hash,\n COALESCE(l.depth, 0) as lineage_depth\nFROM provenance_sources ps\nLEFT JOIN lineage l ON ps.content_hash = l.hash;\n\n-- ============================================================================\n-- Triggers for Automatic Maintenance\n-- ============================================================================\n\n-- Update causal edge timestamp\nCREATE TRIGGER IF NOT EXISTS update_causal_edge_timestamp\nAFTER UPDATE ON causal_edges\nBEGIN\n UPDATE causal_edges\n SET updated_at = strftime('%s', 'now')\n WHERE id = NEW.id;\nEND;\n\n-- Validate causal confidence bounds\nCREATE TRIGGER IF NOT EXISTS validate_causal_confidence\nBEFORE INSERT ON causal_edges\nBEGIN\n SELECT CASE\n WHEN NEW.confidence < 0 OR NEW.confidence > 1 THEN\n RAISE(ABORT, 'Confidence must be between 0 and 1')\n END;\nEND;\n\n-- ============================================================================\n-- Functions for Causal Inference (as SQL helpers)\n-- ============================================================================\n\n-- These would typically be implemented in TypeScript, but we provide\n-- SQL views that can assist with common causal queries\n\n-- Instrumental variables (potential instruments for causal inference)\nCREATE VIEW IF NOT EXISTS causal_instruments AS\nSELECT\n e1.id as instrument_id,\n e1.task as instrument,\n e2.id as treatment_id,\n e2.task as treatment,\n e3.id as outcome_id,\n e3.task as outcome\nFROM episodes e1\nCROSS JOIN episodes e2\nCROSS JOIN episodes e3\nWHERE e1.id != e2.id AND e2.id != e3.id AND e1.id != e3.id\n -- Instrument affects treatment\n AND EXISTS (\n SELECT 1 FROM causal_edges\n WHERE from_memory_id = e1.id AND to_memory_id = e2.id\n AND ABS(uplift) > 0.1\n )\n -- Treatment affects outcome\n AND EXISTS (\n SELECT 1 FROM causal_edges\n WHERE from_memory_id = e2.id AND to_memory_id = e3.id\n AND ABS(uplift) > 0.1\n )\n -- Instrument doesn't directly affect outcome (exclusion restriction)\n AND NOT EXISTS (\n SELECT 1 FROM causal_edges\n WHERE from_memory_id = e1.id AND to_memory_id = e3.id\n );\n\n-- ============================================================================\n-- Schema Version\n-- ============================================================================\n-- Version: 2.0.0 (Frontier Features)\n-- Features: Causal Memory Graph, Explainable Recall Certificates\n-- Compatible with: AgentDB 1.x\n--\n-- Performance Optimization:\n-- Apply composite index migration (003_composite_indexes.sql) for:\n-- - 30-50% faster causal edge queries\n-- - Optimized causal chain traversal (multi-hop reasoning)\n-- - Faster experiment analysis and A/B testing\n-- - See: db/migrations/README.md for details\n-- ============================================================================\n\n-- ============================================================================\n-- FEATURE 3: Reinforcement Learning Experiences\n-- ============================================================================\n\n-- Learning experiences for RL training\nCREATE TABLE IF NOT EXISTS learning_experiences (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n state TEXT NOT NULL,\n action TEXT NOT NULL,\n reward REAL NOT NULL,\n next_state TEXT,\n success INTEGER NOT NULL DEFAULT 0,\n timestamp INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n metadata JSON\n);\n\nCREATE INDEX IF NOT EXISTS idx_learning_experiences_session ON learning_experiences(session_id);\nCREATE INDEX IF NOT EXISTS idx_learning_experiences_timestamp ON learning_experiences(timestamp DESC);\nCREATE INDEX IF NOT EXISTS idx_learning_experiences_reward ON learning_experiences(reward DESC);\n\n-- Learning sessions table for RL session management\nCREATE TABLE IF NOT EXISTS learning_sessions (\n id TEXT PRIMARY KEY,\n user_id TEXT NOT NULL,\n session_type TEXT NOT NULL,\n config JSON NOT NULL,\n start_time INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n end_time INTEGER,\n status TEXT NOT NULL DEFAULT 'active',\n metadata JSON\n);\n\nCREATE INDEX IF NOT EXISTS idx_learning_sessions_user ON learning_sessions(user_id);\nCREATE INDEX IF NOT EXISTS idx_learning_sessions_status ON learning_sessions(status);\nCREATE INDEX IF NOT EXISTS idx_learning_sessions_start ON learning_sessions(start_time DESC);\n"; //# sourceMappingURL=inline.d.ts.map