| 152 | } |
| 153 | |
| 154 | func (s *JSONFileStore) applyWrite(op writeOp) { |
| 155 | s.mu.Lock() |
| 156 | defer s.mu.Unlock() |
| 157 | |
| 158 | if op.toolStats != nil { |
| 159 | s.data.ToolStats[op.toolStats.ToolID] = *op.toolStats |
| 160 | s.dirty++ |
| 161 | } |
| 162 | |
| 163 | if op.pattern != nil { |
| 164 | // SNAPSHOT semantics: replace entire record. |
| 165 | // The engine owns the authoritative counts; the store is a mirror. |
| 166 | // Cumulative merging caused count inflation over time. |
| 167 | record := *op.pattern |
| 168 | toolsCopy := make(map[string]int, len(record.SuccessfulTools)) |
| 169 | for k, v := range record.SuccessfulTools { |
| 170 | toolsCopy[k] = v |
| 171 | } |
| 172 | record.SuccessfulTools = toolsCopy |
| 173 | s.data.QueryPatterns[record.Pattern] = record |
| 174 | s.dirty++ |
| 175 | } |
| 176 | |
| 177 | if s.dirty >= s.flushEvery { |
| 178 | if err := s.flushLocked(); err != nil { |
| 179 | s.logger.Printf("buffered flush: %v", err) |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | func (s *JSONFileStore) Save(record ToolStatsRecord) error { |
| 185 | select { |