All files / src/store personaStore.ts

0% Statements 0/113
0% Branches 0/1
0% Functions 0/1
0% Lines 0/113

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196                                                                                                                                                                                                                                                                                                                                                                                                       
/**
 * Persona Evolution Store
 *
 * Manages persona evolution state and proposals.
 */
 
import { create } from 'zustand';
import { invoke } from '@tauri-apps/api/core';
import type {
  EvolutionResult,
  EvolutionProposal,
  PersonaEvolverConfig,
  PersonaEvolverState,
  MemoryEntryForAnalysis,
} from '../lib/intelligence-client';
 
export interface PersonaEvolutionStore {
  // State
  currentAgentId: string;
  proposals: EvolutionProposal[];
  history: EvolutionResult[];
  isLoading: boolean;
  error: string | null;
  config: PersonaEvolverConfig | null;
  state: PersonaEvolverState | null;
  showProposalsPanel: boolean;
 
  // Actions
  setCurrentAgentId: (agentId: string) => void;
  setShowProposalsPanel: (show: boolean) => void;
 
  // Evolution Actions
  runEvolution: (memories: MemoryEntryForAnalysis[]) => Promise<EvolutionResult | null>;
  loadEvolutionHistory: (limit?: number) => Promise<void>;
  loadEvolverState: () => Promise<void>;
  loadEvolverConfig: () => Promise<void>;
  updateConfig: (config: Partial<PersonaEvolverConfig>) => Promise<void>;
 
  // Proposal Actions
  getPendingProposals: () => EvolutionProposal[];
  applyProposal: (proposal: EvolutionProposal) => Promise<boolean>;
  dismissProposal: (proposalId: string) => void;
  clearProposals: () => void;
}
 
export const usePersonaEvolutionStore = create<PersonaEvolutionStore>((set, get) => ({
  // Initial State
  currentAgentId: '',
  proposals: [],
  history: [],
  isLoading: false,
  error: null,
  config: null,
  state: null,
  showProposalsPanel: false,
 
  // Setters
  setCurrentAgentId: (agentId: string) => set({ currentAgentId: agentId }),
  setShowProposalsPanel: (show: boolean) => set({ showProposalsPanel: show }),
 
  // Run evolution cycle for current agent
  runEvolution: async (memories: MemoryEntryForAnalysis[]) => {
    const { currentAgentId } = get();
    if (!currentAgentId) {
      set({ error: 'No agent selected' });
      return null;
    }
 
    set({ isLoading: true, error: null });
 
    try {
      const result = await invoke<EvolutionResult>('persona_evolve', {
        agentId: currentAgentId,
        memories,
      });
 
      // Update state with results
      set((state) => ({
        history: [result, ...state.history].slice(0, 20),
        proposals: [...result.proposals, ...state.proposals],
        isLoading: false,
        showProposalsPanel: result.proposals.length > 0,
      }));
 
      return result;
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : String(err);
      set({ error: errorMsg, isLoading: false });
      return null;
    }
  },
 
  // Load evolution history
  loadEvolutionHistory: async (limit = 10) => {
    set({ isLoading: true, error: null });
 
    try {
      const history = await invoke<EvolutionResult[]>('persona_evolution_history', {
        limit,
      });
      set({ history, isLoading: false });
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : String(err);
      set({ error: errorMsg, isLoading: false });
    }
  },
 
  // Load evolver state
  loadEvolverState: async () => {
    try {
      const state = await invoke<PersonaEvolverState>('persona_evolver_state');
      set({ state });
    } catch (err) {
      console.error('[PersonaStore] Failed to load evolver state:', err);
    }
  },
 
  // Load evolver config
  loadEvolverConfig: async () => {
    try {
      const config = await invoke<PersonaEvolverConfig>('persona_evolver_config');
      set({ config });
    } catch (err) {
      console.error('[PersonaStore] Failed to load evolver config:', err);
    }
  },
 
  // Update evolver config
  updateConfig: async (newConfig: Partial<PersonaEvolverConfig>) => {
    const { config } = get();
    if (!config) return;
 
    const updatedConfig = { ...config, ...newConfig };
 
    try {
      await invoke('persona_evolver_update_config', { config: updatedConfig });
      set({ config: updatedConfig });
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : String(err);
      set({ error: errorMsg });
    }
  },
 
  // Get pending proposals sorted by confidence
  getPendingProposals: () => {
    const { proposals } = get();
    return proposals
      .filter((p) => p.status === 'pending')
      .sort((a, b) => b.confidence - a.confidence);
  },
 
  // Apply a proposal (approve)
  applyProposal: async (proposal: EvolutionProposal) => {
    set({ isLoading: true, error: null });
 
    try {
      await invoke('persona_apply_proposal', { proposal });
 
      // Remove from pending list
      set((state) => ({
        proposals: state.proposals.filter((p) => p.id !== proposal.id),
        isLoading: false,
      }));
 
      return true;
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : String(err);
      set({ error: errorMsg, isLoading: false });
      return false;
    }
  },
 
  // Dismiss a proposal (reject)
  dismissProposal: (proposalId: string) => {
    set((state) => ({
      proposals: state.proposals.filter((p) => p.id !== proposalId),
    }));
  },
 
  // Clear all proposals
  clearProposals: () => set({ proposals: [] }),
}));
 
// Export convenience hooks
export const usePendingProposals = () =>
  usePersonaEvolutionStore((state) => state.getPendingProposals());
 
export const useEvolutionHistory = () =>
  usePersonaEvolutionStore((state) => state.history);
 
export const useEvolverConfig = () =>
  usePersonaEvolutionStore((state) => state.config);
 
export const useEvolverState = () =>
  usePersonaEvolutionStore((state) => state.state);