/** * Society Protocol - Knowledge Pool System v1.0 * * Sistema de conhecimento compartilhado: * - Knowledge Cards (unidades de conhecimento) * - Spaces compartilhados (repositórios de conhecimento) * - CRDT para convergência sem conflitos * - Knowledge Graph descentralizado * - Links semânticos entre conhecimentos */ import { EventEmitter } from 'events'; import { type Storage } from './storage.js'; import { type Identity } from './identity.js'; export type KnowledgeId = string; export type SpaceId = string; export type LinkType = 'relates-to' | 'supports' | 'contradicts' | 'extends' | 'depends-on' | 'part-of' | 'replicates' | 'cites'; export type KnowledgeType = 'concept' | 'fact' | 'insight' | 'sop' | 'decision' | 'evidence' | 'hypothesis' | 'paper' | 'dataset' | 'claim' | 'finding' | 'code' | 'document' | 'conversation'; export type PrivacyLevel = 'public' | 'federation' | 'room' | 'private'; export interface KnowledgeCard { id: KnowledgeId; spaceId: SpaceId; type: KnowledgeType; title: string; summary: string; content: string; contentFormat: 'markdown' | 'json' | 'code' | 'plain'; author: string; createdAt: number; updatedAt: number; version: number; tags: string[]; domain: string[]; entities: string[]; source?: { type: 'coc' | 'chat' | 'document' | 'web' | 'manual'; id?: string; url?: string; context?: string; }; confidence: number; verificationStatus: 'unverified' | 'verified' | 'disputed' | 'deprecated'; verifiedBy?: string[]; verifications: Verification[]; usage: { views: number; citations: number; applications: number; lastAccessed: number; }; privacy: PrivacyLevel; allowedReaders?: string[]; crdt: { hlc: HybridLogicalClock; vectorClock: Record; tombstone: boolean; }; } export interface Verification { verifier: string; timestamp: number; method: 'manual' | 'automated' | 'consensus'; confidence: number; notes?: string; } export interface KnowledgeLink { id: string; source: KnowledgeId; target: KnowledgeId; type: LinkType; strength: number; createdBy: string; createdAt: number; evidence?: string; } export interface KnowledgeSpace { id: SpaceId; name: string; description: string; owner: string; federationId?: string; roomId?: string; type: 'personal' | 'team' | 'federation' | 'public'; privacy: PrivacyLevel; cards: Set; links: KnowledgeLink[]; subspaces: SpaceId[]; createdAt: number; updatedAt: number; tags: string[]; stats: { cardCount: number; linkCount: number; contributorCount: number; lastActivity: number; }; policies: { allowPublicRead: boolean; allowPublicWrite: boolean; requireVerification: boolean; autoArchiveDays?: number; }; } export interface HybridLogicalClock { wallTime: number; logical: number; nodeId: string; } export interface CollectiveUnconscious { id: string; spaceId: SpaceId; workingMemory: { recentMessages: string[]; activeTopics: string[]; participants: string[]; contextWindow: string; }; longTermMemory: { keyConcepts: KnowledgeId[]; recurringThemes: string[]; learnedPatterns: string[]; agentModels: Record; }; sharedState: { goals: string[]; plans: string[]; decisions: string[]; openQuestions: string[]; }; lastUpdate: number; coherence: number; } export interface AgentModel { did: string; name: string; observedCapabilities: string[]; communicationStyle: { formality: number; verbosity: number; responseTime: number; }; interactions: { total: number; successful: number; lastInteraction: number; }; relationship: { trust: number; familiarity: number; collaborationHistory: string[]; }; expertise: Record; preferences: Record; } export type VectorClockOrder = 'before' | 'after' | 'concurrent' | 'equal'; /** * Compare two vector clocks for causal ordering. * Returns: * 'before' — a causally precedes b (a < b) * 'after' — a causally follows b (a > b) * 'concurrent' — neither precedes the other * 'equal' — identical clocks */ export declare function compareVectorClocks(a: Record, b: Record): VectorClockOrder; /** * Merge two vector clocks by taking component-wise maximum. */ export declare function mergeVectorClocks(a: Record, b: Record): Record; /** * Advance HLC for a local event (Kulkarni et al. 2014, §3.1). * l' = max(l.wallTime, pt) ; c' = (l' == l.wallTime) ? l.logical + 1 : 0 */ export declare function tickHLC(current: HybridLogicalClock): HybridLogicalClock; /** * Receive HLC from a remote message (Kulkarni et al. 2014, §3.2). * Merges local and remote clocks to maintain causal ordering. */ export declare function receiveHLC(local: HybridLogicalClock, remote: HybridLogicalClock): HybridLogicalClock; /** * Compare two HLCs for total ordering. * Returns negative if a < b, positive if a > b, 0 if equal. * Tie-breaking: wallTime → logical → nodeId (lexicographic). */ export declare function compareHLC(a: HybridLogicalClock, b: HybridLogicalClock): number; export interface ChatMessage { id: string; sender: string; senderName?: string; content: string; timestamp: number; roomId?: string; } export interface ContextCompactionConfig { compactAfterMessages: number; maxRecentMessages: number; ollamaUrl?: string; ollamaModel?: string; } export declare class KnowledgePool extends EventEmitter { private storage; private identity; private cards; private spaces; private links; private collectiveUnconscious; private tagIndex; private authorIndex; private typeIndex; private linksBySource; private linksByTarget; private chatBuffers; private compactionConfig; private compacting; constructor(storage: Storage, identity: Identity, compactionConfig?: Partial); createSpace(name: string, description: string, type?: KnowledgeSpace['type'], privacy?: PrivacyLevel): Promise; createCard(spaceId: SpaceId, type: KnowledgeType, title: string, content: string, options?: { summary?: string; tags?: string[]; domain?: string[]; source?: KnowledgeCard['source']; privacy?: PrivacyLevel; confidence?: number; }): Promise; updateCard(id: KnowledgeId, updates: Partial>): Promise; deleteCard(id: KnowledgeId): Promise; /** * Merge a remote knowledge card with the local copy. * * Algorithm (state-based CRDT with causal metadata): * 1. If card is unknown locally → accept remote (new knowledge). * 2. Compare vector clocks for causal ordering: * - remote ≤ local → discard (stale). * - local < remote → accept remote (strictly newer). * - concurrent → LWW tie-break on HLC (wallTime, logical, nodeId). * 3. Merge vector clocks (component-wise max) regardless of winner. * 4. Advance local HLC via receiveHLC to maintain causal consistency. * 5. Tombstone wins: if either copy is tombstoned, result is tombstoned. * * Returns the merged card, or null if the remote was stale. */ mergeCard(remote: KnowledgeCard): KnowledgeCard | null; /** * Merge verification arrays, deduplicating by (verifier, timestamp). */ private mergeVerifications; /** * Serialize a card for network transmission (GossipSub). */ serializeCard(card: KnowledgeCard): Uint8Array; /** * Deserialize a card received from the network. */ deserializeCard(data: Uint8Array): KnowledgeCard; /** * Handle incoming knowledge sync message from GossipSub. * Deserializes, merges, and emits sync events. */ handleSyncMessage(data: Uint8Array, from: string): void; /** * Get all cards that have been modified since a given timestamp. * Used for anti-entropy sync (periodic full-state exchange). */ getModifiedSince(since: number): KnowledgeCard[]; linkCards(sourceId: KnowledgeId, targetId: KnowledgeId, type: LinkType, strength?: number, evidence?: string): Promise; queryCards(options: { spaceId?: SpaceId; type?: KnowledgeType; tags?: string[]; author?: string; domain?: string[]; query?: string; verificationStatus?: KnowledgeCard['verificationStatus']; privacy?: PrivacyLevel; limit?: number; offset?: number; sortBy?: 'relevance' | 'confidence' | 'created' | 'usage'; }): KnowledgeCard[]; getRelatedCards(cardId: KnowledgeId, depth?: number): KnowledgeCard[]; private indexLink; getKnowledgeGraph(spaceId: SpaceId): { nodes: KnowledgeCard[]; links: KnowledgeLink[]; }; private createCollectiveUnconscious; private updateCollectiveUnconscious; updateWorkingMemory(spaceId: SpaceId, update: Partial): Promise; getCollectiveUnconscious(spaceId: SpaceId): CollectiveUnconscious | undefined; getSharedContext(spaceId: SpaceId): string; /** * Get or create CollectiveUnconscious for a space/room. * Public so rooms can initialize knowledge tracking. */ getOrCreateCU(spaceId: SpaceId): Promise; /** * Ingest a chat message into the collaborative context. * Called by RoomManager when chat messages are received. * Triggers auto-compaction when buffer exceeds threshold. */ ingestChatMessage(spaceId: SpaceId, msg: ChatMessage): Promise; /** * Compact the conversation context using Ollama. * Summarizes recent messages into a dense context window, * extracts key concepts, decisions, and open questions. */ compactContext(spaceId: SpaceId): Promise; /** * Serialize the collaborative context for sharing with peers. * Used by knowledge.context_sync SWP messages. */ serializeContext(spaceId: SpaceId): Uint8Array | null; /** * Merge a remote context sync into the local CollectiveUnconscious. * Takes the union of topics, concepts, decisions, etc. */ mergeRemoteContext(data: Uint8Array): Promise; /** * Get the chat message buffer for a space (for inspection/testing). */ getChatBuffer(spaceId: SpaceId): ChatMessage[]; /** * Get top knowledge cards for gossip broadcast to peers. * Returns cards sorted by confidence * usage, most valuable first. */ getGossipPayload(spaceId: SpaceId, limit?: number): KnowledgeCard[]; /** * Apply knowledge decay to all cards. * Cards not reinforced lose confidence over time. * Should be called periodically (e.g., daily). * * @param decayRate - fraction of confidence lost per call (default 0.05 = 5%) */ applyKnowledgeDecay(decayRate?: number): number; /** * Boost confidence when multiple agents confirm the same fact. * If 2+ agents have verified a card, boost by confirmationBoost. * * @param cardId - card to boost * @param verifierDid - DID of the confirming agent * @param boostAmount - confidence boost (default 0.2 = 20%) */ confirmKnowledge(cardId: KnowledgeId, verifierDid: string, boostAmount?: number): KnowledgeCard | null; /** * Distill lessons learned from a completed CoC chain. * Creates knowledge cards from the chain's experience. * * @param chainId - ID of the completed chain * @param summary - chain summary/final report * @param goal - original chain goal * @param spaceId - space to store knowledge in * @param participants - DIDs of participating agents */ distillChainExperience(chainId: string, summary: string, goal: string, spaceId: SpaceId, participants: string[]): Promise; /** * Extract knowledge from a batch of chat messages. * Used for periodic knowledge extraction from conversations. */ extractFromConversation(spaceId: SpaceId, messages: ChatMessage[]): Promise; /** * Simple text-based compaction when Ollama is unavailable. * Keeps last few lines of previous context + summary of new transcript. */ private simpleCompact; /** * Call Ollama for context summarization. */ private callOllama; /** * Parse JSON from LLM response (handles markdown code blocks). */ private parseJsonResponse; private generateSummary; private extractEntities; private generateContextWindow; private indexCard; private addToTagIndex; private removeFromTagIndex; private removeFromIndex; private saveCard; private saveSpace; private saveLink; private saveCollectiveUnconscious; private loadFromStorage; private normalizeSpace; private normalizeCard; private normalizeLink; } //# sourceMappingURL=knowledge.d.ts.map