|
| 1 | +package io.sentrius.sso.core.services.agents; |
| 2 | + |
| 3 | +import io.sentrius.sso.core.model.agents.AgentContext; |
| 4 | +import io.sentrius.sso.core.repository.AgentContextRepository; |
| 5 | +import io.sentrius.sso.core.services.abac.EvaluationContext; |
| 6 | +import io.sentrius.sso.core.services.abac.PolicyDecision; |
| 7 | +import io.sentrius.sso.core.services.abac.PolicyEvaluator; |
| 8 | +import io.sentrius.sso.provenance.ProvenanceEvent; |
| 9 | +import io.sentrius.sso.provenance.ProvenanceLogger; |
| 10 | +import lombok.extern.slf4j.Slf4j; |
| 11 | +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; |
| 12 | +import org.springframework.stereotype.Service; |
| 13 | +import org.springframework.transaction.annotation.Transactional; |
| 14 | + |
| 15 | +import java.time.Instant; |
| 16 | +import java.util.UUID; |
| 17 | + |
| 18 | +/** |
| 19 | + * Sentrius GenerationManager: spawn next agent generation from parent under ATPL policy. |
| 20 | + * Clone memory, decay trust, and record lineage. |
| 21 | + */ |
| 22 | +@Slf4j |
| 23 | +@Service |
| 24 | +@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) |
| 25 | +public class GenerationManager { |
| 26 | + |
| 27 | + private final AgentContextRepository agentContextRepository; |
| 28 | + private final LearningService learningService; |
| 29 | + private final PolicyEvaluator policyEvaluator; |
| 30 | + private final ProvenanceLogger provenanceLogger; |
| 31 | + private final VectorAgentMemoryStore vectorMemoryStore; |
| 32 | + |
| 33 | + // Trust and memory decay constants |
| 34 | + private static final double TRUST_DECAY_FACTOR = 0.95; |
| 35 | + private static final double MEMORY_RELEVANCE_DECAY = 0.9; |
| 36 | + private static final double MIN_TRUST_SCORE_FOR_GENERATION = 0.8; |
| 37 | + private static final double DEFAULT_TRUST_SCORE = 0.5; |
| 38 | + |
| 39 | + public GenerationManager( |
| 40 | + AgentContextRepository agentContextRepository, |
| 41 | + LearningService learningService, |
| 42 | + PolicyEvaluator policyEvaluator, |
| 43 | + ProvenanceLogger provenanceLogger, |
| 44 | + VectorAgentMemoryStore vectorMemoryStore) { |
| 45 | + this.agentContextRepository = agentContextRepository; |
| 46 | + this.learningService = learningService; |
| 47 | + this.policyEvaluator = policyEvaluator; |
| 48 | + this.provenanceLogger = provenanceLogger; |
| 49 | + this.vectorMemoryStore = vectorMemoryStore; |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Creates a new agent generation from a parent agent. |
| 54 | + * Validates policy authorization, decays trust and memory, and initializes the new generation. |
| 55 | + * |
| 56 | + * @param parentId The ID of the parent agent |
| 57 | + * @param requestingUserId The ID of the user requesting the generation |
| 58 | + * @return The newly created agent generation |
| 59 | + * @throws IllegalStateException if generation creation is not authorized |
| 60 | + */ |
| 61 | + @Transactional |
| 62 | + public AgentContext createNextGeneration(UUID parentId, String requestingUserId) { |
| 63 | + log.info("Creating next generation from parent: {}, requestedBy: {}", parentId, requestingUserId); |
| 64 | + |
| 65 | + // Load parent agent |
| 66 | + AgentContext parent = agentContextRepository.findById(parentId) |
| 67 | + .orElseThrow(() -> new IllegalArgumentException("Parent agent not found: " + parentId)); |
| 68 | + |
| 69 | + // Validate policy authorization for GENERATION_CREATE |
| 70 | + validateGenerationCreationPolicy(parent, requestingUserId); |
| 71 | + |
| 72 | + // Create child agent with incremented generation |
| 73 | + AgentContext child = createChildAgent(parent); |
| 74 | + |
| 75 | + // Decay trust score |
| 76 | + double childTrustScore = calculateDecayedTrustScore(parent.getTrustScore()); |
| 77 | + child.setTrustScore(childTrustScore); |
| 78 | + |
| 79 | + // Save child agent |
| 80 | + child = agentContextRepository.save(child); |
| 81 | + log.info("Created new agent generation: id={}, generation={}, trustScore={}", |
| 82 | + child.getId(), child.getGeneration(), child.getTrustScore()); |
| 83 | + |
| 84 | + // Bootstrap memory from parent |
| 85 | + learningService.bootstrapFromParent(parent, child, MEMORY_RELEVANCE_DECAY); |
| 86 | + |
| 87 | + // Log provenance event |
| 88 | + logGenerationCreation(parent, child, requestingUserId); |
| 89 | + |
| 90 | + return child; |
| 91 | + } |
| 92 | + |
| 93 | + /** |
| 94 | + * Validates that the parent agent meets policy requirements for creating a new generation. |
| 95 | + */ |
| 96 | + private void validateGenerationCreationPolicy(AgentContext parent, String requestingUserId) { |
| 97 | + log.debug("Validating GENERATION_CREATE policy for parent: {}", parent.getId()); |
| 98 | + |
| 99 | + // Check minimum trust score |
| 100 | + if (parent.getTrustScore() < MIN_TRUST_SCORE_FOR_GENERATION) { |
| 101 | + String message = String.format( |
| 102 | + "Parent trust score %.2f is below minimum %.2f required for generation", |
| 103 | + parent.getTrustScore(), MIN_TRUST_SCORE_FOR_GENERATION); |
| 104 | + log.warn(message); |
| 105 | + throw new IllegalStateException(message); |
| 106 | + } |
| 107 | + |
| 108 | + // Evaluate ABAC policy for GENERATION_CREATE action |
| 109 | + EvaluationContext context = policyEvaluator.buildContext(requestingUserId, parent.getId().toString()); |
| 110 | + context.addResourceAttribute("parent_trust_score", String.valueOf(parent.getTrustScore())); |
| 111 | + context.addResourceAttribute("parent_generation", String.valueOf(parent.getGeneration())); |
| 112 | + context.addResourceAttribute("parent_policy_id", parent.getPolicyId()); |
| 113 | + context.addResourceAttribute("resource_type", "agent_generation"); |
| 114 | + |
| 115 | + PolicyDecision decision = policyEvaluator.evaluate(context, parent.getId().toString(), "GENERATION_CREATE"); |
| 116 | + |
| 117 | + if (decision.getEffect() != PolicyDecision.Effect.ALLOW) { |
| 118 | + String message = "Policy denied generation creation: " + decision.getReason(); |
| 119 | + log.warn(message); |
| 120 | + throw new IllegalStateException(message); |
| 121 | + } |
| 122 | + |
| 123 | + log.info("GENERATION_CREATE policy validated successfully for parent: {}", parent.getId()); |
| 124 | + } |
| 125 | + |
| 126 | + /** |
| 127 | + * Creates a child agent from the parent with incremented generation. |
| 128 | + */ |
| 129 | + private AgentContext createChildAgent(AgentContext parent) { |
| 130 | + AgentContext child = new AgentContext(); |
| 131 | + child.setId(UUID.randomUUID()); |
| 132 | + child.setName(parent.getName()); |
| 133 | + child.setDescription("Generation " + (parent.getGeneration() + 1) + " of " + parent.getName()); |
| 134 | + child.setContext(parent.getContext()); // Copy context configuration |
| 135 | + child.setGeneration(parent.getGeneration() + 1); |
| 136 | + child.setParentId(parent.getId()); |
| 137 | + child.setPolicyId(parent.getPolicyId()); // Inherit policy |
| 138 | + |
| 139 | + // Create new memory namespace for this generation |
| 140 | + child.setMemoryNamespace("agents/" + parent.getName() + "_v" + child.getGeneration()); |
| 141 | + |
| 142 | + return child; |
| 143 | + } |
| 144 | + |
| 145 | + /** |
| 146 | + * Calculates the decayed trust score for the child generation. |
| 147 | + */ |
| 148 | + private double calculateDecayedTrustScore(Double parentTrustScore) { |
| 149 | + if (parentTrustScore == null) { |
| 150 | + return DEFAULT_TRUST_SCORE; |
| 151 | + } |
| 152 | + double decayed = parentTrustScore * TRUST_DECAY_FACTOR; |
| 153 | + // Ensure trust score stays within bounds [0.0, 1.0] |
| 154 | + return Math.max(0.0, Math.min(1.0, decayed)); |
| 155 | + } |
| 156 | + |
| 157 | + /** |
| 158 | + * Logs provenance event for generation creation. |
| 159 | + */ |
| 160 | + private void logGenerationCreation(AgentContext parent, AgentContext child, String requestingUserId) { |
| 161 | + ProvenanceEvent event = ProvenanceEvent.builder() |
| 162 | + .eventId(UUID.randomUUID().toString()) |
| 163 | + .sessionId(child.getId().toString()) |
| 164 | + .actor(child.getName()) |
| 165 | + .triggeringUser(requestingUserId) |
| 166 | + .eventType(ProvenanceEvent.EventType.AGENT_RESPOND) // Reusing existing type |
| 167 | + .input("Parent: " + parent.getId() + " (gen " + parent.getGeneration() + ")") |
| 168 | + .outputSummary("Child: " + child.getId() + " (gen " + child.getGeneration() + |
| 169 | + "), TrustScore: " + child.getTrustScore()) |
| 170 | + .timestamp(Instant.now()) |
| 171 | + .build(); |
| 172 | + |
| 173 | + provenanceLogger.log(event); |
| 174 | + log.info("Logged provenance for generation creation: parent={}, child={}", parent.getId(), child.getId()); |
| 175 | + } |
| 176 | + |
| 177 | + /** |
| 178 | + * Gets the memory decay factor used for inheritance. |
| 179 | + */ |
| 180 | + public double getMemoryDecayFactor() { |
| 181 | + return MEMORY_RELEVANCE_DECAY; |
| 182 | + } |
| 183 | + |
| 184 | + /** |
| 185 | + * Gets the minimum trust score required for generation creation. |
| 186 | + */ |
| 187 | + public double getMinTrustScoreForGeneration() { |
| 188 | + return MIN_TRUST_SCORE_FOR_GENERATION; |
| 189 | + } |
| 190 | +} |
0 commit comments