| 1 | package extension |
| 2 | |
| 3 | import ( |
| 4 | "crypto/sha256" |
| 5 | "encoding/hex" |
| 6 | "encoding/json" |
| 7 | "maps" |
| 8 | "sort" |
| 9 | |
| 10 | "reasonix/internal/provider" |
| 11 | ) |
| 12 | |
| 13 | // RuntimeSnapshot is the frozen, effective runtime configuration produced by |
| 14 | // one Builder run. It is immutable after Freeze: fields are private and every |
| 15 | // accessor returns defensive copies, so snapshots can be shared across turns, |
| 16 | // subagents, and frontends without locking. Two snapshots with equal |
| 17 | // CacheHash are interchangeable for provider caching purposes even if their |
| 18 | // provenance differs. |
| 19 | type RuntimeSnapshot struct { |
| 20 | generation uint64 |
| 21 | catalog *Catalog |
| 22 | systemPrompt string |
| 23 | toolSchemas []provider.ToolSchema |
| 24 | interceptorChain map[InterceptorPoint][]Contribution |
| 25 | replacements map[Slot]ContributionSource |
| 26 | diagnostics []string |
| 27 | cacheHash string |
| 28 | systemHash string |
| 29 | toolsHash string |
| 30 | } |
| 31 | |
| 32 | // Generation returns the build generation. Generations let stale cleanup |
| 33 | // (RuntimeSet.CloseIfGeneration) recognize that a snapshot has been |
| 34 | // superseded. |
| 35 | func (s *RuntimeSnapshot) Generation() uint64 { return s.generation } |
| 36 | |
| 37 | // WithGeneration returns a shallow copy of the snapshot with a new generation. |
| 38 | // CacheHash and provider-visible fields are preserved byte-for-byte so a |
| 39 | // no-op rebuild can advance generation without prompt/tool cache churn. |
| 40 | func (s *RuntimeSnapshot) WithGeneration(gen uint64) *RuntimeSnapshot { |
| 41 | if s == nil { |
| 42 | return nil |
| 43 | } |
| 44 | cp := *s |
| 45 | cp.generation = gen |
| 46 | return &cp |
| 47 | } |
| 48 | |
| 49 | // WithLiveContributions returns a copy with generation advanced and interceptor |
| 50 | // chain / replacement slots rebuilt from live sidecar contributions. System |
| 51 | // prompt, tool schemas, and CacheHash stay byte-identical: provider/MCP backend |
| 52 | // rolls must not churn the provider-visible prefix. Catalog overlay is rebuilt |
| 53 | // so doctor/UI see the live provider/UI contribution set. |
| 54 | func (s *RuntimeSnapshot) WithLiveContributions(gen uint64, live []Contribution) *RuntimeSnapshot { |
| 55 | if s == nil { |
| 56 | return nil |
| 57 | } |
| 58 | cp := *s |
| 59 | cp.generation = gen |
| 60 | // Always drop plugin-scoped live kinds, even when live is empty (plugin removed). |
| 61 | catalog := NewCatalog() |
| 62 | if s.catalog != nil { |
| 63 | for _, ct := range s.catalog.All() { |
| 64 | switch ct.Kind { |
| 65 | case KindInterceptor, KindProvider, KindUIAction, KindStrategy: |
| 66 | if ct.Source.Scope == ScopePlugin { |
| 67 | continue |
| 68 | } |
| 69 | } |
| 70 | catalog.Add(ct) |
| 71 | } |
| 72 | } |
| 73 | if len(live) > 0 { |
| 74 | catalog.Add(live...) |
| 75 | } |
| 76 | |
| 77 | chains := map[InterceptorPoint][]Contribution{} |
| 78 | for _, ct := range catalog.ByKind(KindInterceptor) { |
| 79 | point := InterceptorPoint(ct.ID) |
| 80 | chains[point] = append(chains[point], ct) |
| 81 | } |
| 82 | for point, chain := range chains { |
| 83 | chains[point] = SortInterceptors(chain) |
| 84 | } |
| 85 | // Rebuild replacements: keep non-plugin owners, drop all plugin owners, |
| 86 | // then re-apply live strategy claims only. |
| 87 | repl := make(map[Slot]ContributionSource) |
| 88 | for slot, src := range s.replacements { |
| 89 | if src.Scope != ScopePlugin { |
| 90 | repl[slot] = src |
| 91 | } |
| 92 | } |
| 93 | for _, ct := range catalog.ByKind(KindStrategy) { |
| 94 | if claimer, ok := ct.Payload.(SlotClaimer); ok { |
| 95 | for _, slot := range claimer.ReplacementSlots() { |
| 96 | repl[slot] = ct.Source |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | catalog.freeze() |
| 101 | cp.catalog = catalog |
| 102 | cp.interceptorChain = chains |
| 103 | cp.replacements = repl |
| 104 | // CacheHash intentionally unchanged (system + tools only). |
| 105 | return &cp |
| 106 | } |
| 107 | |
| 108 | // Catalog returns the frozen catalog of effective (post-resolution) |
| 109 | // contributions. The catalog itself is immutable; its accessors return |
| 110 | // copies. |
| 111 | func (s *RuntimeSnapshot) Catalog() *Catalog { return s.catalog } |
| 112 | |
| 113 | // SystemPrompt returns the assembled system prompt text. |
| 114 | func (s *RuntimeSnapshot) SystemPrompt() string { return s.systemPrompt } |
| 115 | |
| 116 | // ToolSchemas returns the canonical provider-visible tool schemas, sorted by |
| 117 | // name. The slice is a copy — mutating it cannot affect the snapshot. |
| 118 | func (s *RuntimeSnapshot) ToolSchemas() []provider.ToolSchema { |
| 119 | out := make([]provider.ToolSchema, len(s.toolSchemas)) |
| 120 | copy(out, s.toolSchemas) |
| 121 | return out |
| 122 | } |
| 123 | |
| 124 | // InterceptorChain returns the ordered interceptor chain per point (a deep |
| 125 | // copy). Points with no interceptors are absent, not empty. |
| 126 | func (s *RuntimeSnapshot) InterceptorChain() map[InterceptorPoint][]Contribution { |
| 127 | out := make(map[InterceptorPoint][]Contribution, len(s.interceptorChain)) |
| 128 | for point, chain := range s.interceptorChain { |
| 129 | cp := make([]Contribution, len(chain)) |
| 130 | copy(cp, chain) |
| 131 | out[point] = cp |
| 132 | } |
| 133 | return out |
| 134 | } |
| 135 | |
| 136 | // Replacements returns the winning owner per replacement slot (a copy). |
| 137 | func (s *RuntimeSnapshot) Replacements() map[Slot]ContributionSource { |
| 138 | out := make(map[Slot]ContributionSource, len(s.replacements)) |
| 139 | maps.Copy(out, s.replacements) |
| 140 | return out |
| 141 | } |
| 142 | |
| 143 | // Diagnostics returns human-readable notes about the assembly — currently the |
| 144 | // shadowing disputes a ConflictCollect build resolved with its ordinary |
| 145 | // winner rules instead of failing. Each entry names the kind, the canonical |
| 146 | // ID, and every source that claimed it. The slice is a copy; empty means the |
| 147 | // build resolved cleanly. |
| 148 | func (s *RuntimeSnapshot) Diagnostics() []string { |
| 149 | out := make([]string, len(s.diagnostics)) |
| 150 | copy(out, s.diagnostics) |
| 151 | return out |
| 152 | } |
| 153 | |
| 154 | // CacheHash returns the fingerprint of the provider-visible prefix state. |
| 155 | func (s *RuntimeSnapshot) CacheHash() string { return s.cacheHash } |
| 156 | |
| 157 | // CacheShape returns the two halves of CacheHash — the system-prompt hash and |
| 158 | // the tool-schemas hash — so cache-miss diagnostics can say which half moved |
| 159 | // without re-hashing. |
| 160 | func (s *RuntimeSnapshot) CacheShape() (systemHash, toolsHash string) { |
| 161 | return s.systemHash, s.toolsHash |
| 162 | } |
| 163 | |
| 164 | // normalizeToolSchemas sorts schemas by (name, description, parameters) so a |
| 165 | // reordered input cannot change the hash. This mirrors the canonicalization |
| 166 | // in internal/agent/cache_shape.go; it is reimplemented here rather than |
| 167 | // imported because the kernel must stay below the agent package in the |
| 168 | // dependency graph. |
| 169 | func normalizeToolSchemas(schemas []provider.ToolSchema) []provider.ToolSchema { |
| 170 | out := make([]provider.ToolSchema, len(schemas)) |
| 171 | copy(out, schemas) |
| 172 | sort.Slice(out, func(i, j int) bool { |
| 173 | if out[i].Name != out[j].Name { |
| 174 | return out[i].Name < out[j].Name |
| 175 | } |
| 176 | if out[i].Description != out[j].Description { |
| 177 | return out[i].Description < out[j].Description |
| 178 | } |
| 179 | return string(out[i].Parameters) < string(out[j].Parameters) |
| 180 | }) |
| 181 | return out |
| 182 | } |
| 183 | |
| 184 | // cacheHashInput is the canonical hashed form: JSON object keys in |
| 185 | // declaration order, schemas pre-sorted, parameters pre-canonicalized at |
| 186 | // assemble time (provider.CanonicalizeSchema sorts schema keys, so the raw |
| 187 | // bytes are stable across processes). |
| 188 | type cacheHashInput struct { |
| 189 | SystemPrompt string `json:"systemPrompt"` |
| 190 | ToolSchemas []provider.ToolSchema `json:"toolSchemas"` |
| 191 | } |
| 192 | |
| 193 | func sha256Hex(b []byte) string { |
| 194 | sum := sha256.Sum256(b) |
| 195 | return hex.EncodeToString(sum[:]) |
| 196 | } |
| 197 | |
| 198 | // computeCacheShape hashes the system prompt and the canonical tool schemas. |
| 199 | // Keeping the two halves separate costs nothing and lets CacheShape explain |
| 200 | // prefix-cache misses the way internal/agent.CompareShape does. |
| 201 | func computeCacheShape(systemPrompt string, schemas []provider.ToolSchema) (systemHash, toolsHash, cacheHash string) { |
| 202 | canonical := normalizeToolSchemas(schemas) |
| 203 | toolsJSON, _ := json.Marshal(canonical) |
| 204 | systemHash = sha256Hex([]byte(systemPrompt)) |
| 205 | toolsHash = sha256Hex(toolsJSON) |
| 206 | combined, _ := json.Marshal(cacheHashInput{SystemPrompt: systemPrompt, ToolSchemas: canonical}) |
| 207 | cacheHash = sha256Hex(combined) |
| 208 | return systemHash, toolsHash, cacheHash |
| 209 | } |
| 210 |