bock-ai 0.1.0

AI provider interface for Bock's AI-native code generation pipeline (Generate, Repair, Optimize, Select)
Documentation
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Provider wrapper that adds content-addressed response caching
//! around any [`AiProvider`] implementation.
//!
//! Each call's request is reduced to a deterministic JSON key (mode +
//! model identifier + the cacheable surface of the request) and looked
//! up in an [`AiCache`]. On a hit, the cached response is returned
//! immediately; on a miss the inner provider is called and its
//! response is stored under the same key.
//!
//! Per §17.8, cached responses are treated as **pinned** — the
//! `from_cache: true` signal returned by the
//! [`*_cached`](Self::generate_cached) inherent methods lets the
//! decision-recording layer set [`Decision::pinned`](
//! crate::decision::Decision::pinned) accordingly. The plain
//! [`AiProvider`] impl drops the signal so the wrapper is a drop-in
//! replacement for any existing provider.

use async_trait::async_trait;
use serde::Serialize;

use crate::cache::AiCache;
use crate::error::AiError;
use crate::provider::AiProvider;
use crate::request::{
    GenerateRequest, GenerateResponse, OptimizeRequest, OptimizeResponse, RepairRequest,
    RepairResponse, SelectContext, SelectOption, SelectRequest, SelectResponse,
};

/// Provider wrapper that intercepts each call with [`AiCache`].
///
/// Generic in the inner provider so the wrapper can be stacked on top
/// of any [`AiProvider`] without erasing the concrete type.
#[derive(Debug)]
pub struct CachingProvider<P: AiProvider> {
    inner: P,
    cache: AiCache,
}

impl<P: AiProvider> CachingProvider<P> {
    /// Wraps `inner` with the given cache.
    pub fn new(inner: P, cache: AiCache) -> Self {
        Self { inner, cache }
    }

    /// Borrows the underlying cache (e.g., for stats or clear).
    #[must_use]
    pub fn cache(&self) -> &AiCache {
        &self.cache
    }

    /// Returns the inner provider.
    pub fn inner(&self) -> &P {
        &self.inner
    }

    /// [`generate`](AiProvider::generate) plus a `from_cache` flag.
    ///
    /// Callers that record decisions use the flag to set
    /// [`Decision::pinned`](crate::decision::Decision::pinned) — see
    /// §17.8: cached responses are treated as pinned.
    ///
    /// # Errors
    /// Forwards any error from the inner provider on a cache miss.
    pub async fn generate_cached(
        &self,
        request: &GenerateRequest,
    ) -> Result<(GenerateResponse, bool), AiError> {
        let key = generate_key(self.inner.model_id(), request);
        if let Some(resp) = self.cache.get::<_, GenerateResponse>(&key) {
            return Ok((resp, true));
        }
        let resp = self.inner.generate(request).await?;
        let _ = self.cache.put(&key, &resp);
        Ok((resp, false))
    }

    /// [`repair`](AiProvider::repair) plus a `from_cache` flag.
    ///
    /// # Errors
    /// Forwards any error from the inner provider on a cache miss.
    pub async fn repair_cached(
        &self,
        request: &RepairRequest,
    ) -> Result<(RepairResponse, bool), AiError> {
        let key = repair_key(self.inner.model_id(), request);
        if let Some(resp) = self.cache.get::<_, RepairResponse>(&key) {
            return Ok((resp, true));
        }
        let resp = self.inner.repair(request).await?;
        let _ = self.cache.put(&key, &resp);
        Ok((resp, false))
    }

    /// [`optimize`](AiProvider::optimize) plus a `from_cache` flag.
    ///
    /// # Errors
    /// Forwards any error from the inner provider on a cache miss.
    pub async fn optimize_cached(
        &self,
        request: &OptimizeRequest,
    ) -> Result<(OptimizeResponse, bool), AiError> {
        let key = optimize_key(self.inner.model_id(), request);
        if let Some(resp) = self.cache.get::<_, OptimizeResponse>(&key) {
            return Ok((resp, true));
        }
        let resp = self.inner.optimize(request).await?;
        let _ = self.cache.put(&key, &resp);
        Ok((resp, false))
    }

    /// [`select`](AiProvider::select) plus a `from_cache` flag.
    ///
    /// # Errors
    /// Forwards any error from the inner provider on a cache miss.
    pub async fn select_cached(
        &self,
        request: &SelectRequest,
    ) -> Result<(SelectResponse, bool), AiError> {
        let key = select_key(self.inner.model_id(), request);
        if let Some(resp) = self.cache.get::<_, SelectResponse>(&key) {
            return Ok((resp, true));
        }
        let resp = self.inner.select(request).await?;
        let _ = self.cache.put(&key, &resp);
        Ok((resp, false))
    }
}

#[async_trait]
impl<P: AiProvider> AiProvider for CachingProvider<P> {
    async fn generate(
        &self,
        request: &GenerateRequest,
    ) -> Result<GenerateResponse, AiError> {
        self.generate_cached(request).await.map(|(r, _)| r)
    }

    async fn repair(&self, request: &RepairRequest) -> Result<RepairResponse, AiError> {
        self.repair_cached(request).await.map(|(r, _)| r)
    }

    async fn optimize(
        &self,
        request: &OptimizeRequest,
    ) -> Result<OptimizeResponse, AiError> {
        self.optimize_cached(request).await.map(|(r, _)| r)
    }

    async fn select(&self, request: &SelectRequest) -> Result<SelectResponse, AiError> {
        self.select_cached(request).await.map(|(r, _)| r)
    }

    fn model_id(&self) -> String {
        self.inner.model_id()
    }
}

// ─── Cache key construction ──────────────────────────────────────────────────
//
// The request types in `request.rs` carry an `AIRNode` and a
// `Strictness`, neither of which currently implements `Serialize`. The
// cacheable surface is reconstructed below into a `Serialize` shadow
// struct: scalar fields pass through, the AIR node is captured via its
// `Debug` projection (stable for any given node value), and the
// strictness is rendered as a static string.
//
// Adding `Serialize` to `AIRNode` would propagate through `bock-air`,
// `bock-ast`, `bock-source`, and `bock-errors` — out of scope for this
// package. The shadow approach keeps the change contained to
// `bock-ai` and makes the cacheable contract for each mode explicit.

#[derive(Serialize)]
struct GenerateKey<'a> {
    mode: &'a str,
    model_id: String,
    target_id: &'a str,
    module_path: &'a str,
    imports: &'a [String],
    siblings: &'a [String],
    annotations: &'a [String],
    prior_decisions: Vec<(&'a str, &'a str)>,
    strictness: &'static str,
    node_debug: String,
    capabilities: Vec<(&'a String, &'a String)>,
    conventions: Vec<(&'a String, &'a String)>,
}

fn generate_key(model_id: String, req: &GenerateRequest) -> GenerateKey<'_> {
    let prior: Vec<(&str, &str)> = req
        .prior_decisions
        .iter()
        .map(|d| (d.decision.as_str(), d.choice.as_str()))
        .collect();
    GenerateKey {
        mode: "generate",
        model_id,
        target_id: &req.target.id,
        module_path: &req.module_context.module_path,
        imports: &req.module_context.imports,
        siblings: &req.module_context.siblings,
        annotations: &req.module_context.annotations,
        prior_decisions: prior,
        strictness: strictness_str(req.strictness),
        node_debug: format!("{:?}", req.node),
        capabilities: req.target.capabilities.iter().collect(),
        conventions: req.target.conventions.iter().collect(),
    }
}

#[derive(Serialize)]
struct RepairKey<'a> {
    mode: &'a str,
    model_id: String,
    target_id: &'a str,
    original_code: &'a str,
    compiler_error: &'a str,
    node_debug: String,
}

fn repair_key(model_id: String, req: &RepairRequest) -> RepairKey<'_> {
    RepairKey {
        mode: "repair",
        model_id,
        target_id: &req.target.id,
        original_code: &req.original_code,
        compiler_error: &req.compiler_error,
        node_debug: format!("{:?}", req.node),
    }
}

#[derive(Serialize)]
struct OptimizeKey<'a> {
    mode: &'a str,
    model_id: String,
    target_id: &'a str,
    working_code: &'a str,
    node_debug: String,
    optimization_hints: Vec<String>,
}

fn optimize_key(model_id: String, req: &OptimizeRequest) -> OptimizeKey<'_> {
    OptimizeKey {
        mode: "optimize",
        model_id,
        target_id: &req.target.id,
        working_code: &req.working_code,
        node_debug: format!("{:?}", req.node),
        optimization_hints: req
            .optimization_hints
            .iter()
            .map(|h| format!("{h:?}"))
            .collect(),
    }
}

#[derive(Serialize)]
struct SelectKey<'a> {
    mode: &'a str,
    model_id: String,
    rationale_prompt: &'a str,
    options: Vec<(&'a str, &'a str)>,
    context: SelectContextKey<'a>,
}

#[derive(Serialize)]
struct SelectContextKey<'a> {
    error: Option<&'a str>,
    annotations: &'a [String],
    history: &'a [String],
    metadata: Vec<(&'a String, &'a String)>,
}

fn select_key(model_id: String, req: &SelectRequest) -> SelectKey<'_> {
    let options: Vec<(&str, &str)> = req
        .options
        .iter()
        .map(|o: &SelectOption| (o.id.as_str(), o.description.as_str()))
        .collect();
    let ctx: &SelectContext = &req.context;
    SelectKey {
        mode: "select",
        model_id,
        rationale_prompt: &req.rationale_prompt,
        options,
        context: SelectContextKey {
            error: ctx.error.as_deref(),
            annotations: &ctx.annotations,
            history: &ctx.history,
            metadata: ctx.metadata.iter().collect(),
        },
    }
}

fn strictness_str(s: bock_types::Strictness) -> &'static str {
    match s {
        bock_types::Strictness::Sketch => "sketch",
        bock_types::Strictness::Development => "development",
        bock_types::Strictness::Production => "production",
    }
}

// ─── Serialize derives for response types ────────────────────────────────────
//
// The cache stores responses as JSON. The response types live in
// `request.rs`; `Serialize`/`Deserialize` are added there alongside
// the existing derives so the cache is the only consumer of the new
// contract.

#[cfg(test)]
mod tests {
    use super::*;
    use crate::request::{
        Alternative, GenerateRequest, ModuleContext, OptimizationHint, RepairRequest,
        SelectContext, SelectOption, SelectRequest, TargetProfile,
    };
    use crate::StubProvider;
    use bock_air::{AIRNode, NodeIdGen, NodeKind};
    use bock_errors::Span;
    use bock_types::Strictness;
    use std::collections::HashMap;

    fn dummy_node() -> AIRNode {
        let gen = NodeIdGen::new();
        AIRNode::new(
            gen.next(),
            Span::dummy(),
            NodeKind::Block {
                stmts: Vec::new(),
                tail: None,
            },
        )
    }

    fn target() -> TargetProfile {
        TargetProfile {
            id: "js".into(),
            display_name: "JavaScript".into(),
            capabilities: HashMap::new(),
            conventions: HashMap::new(),
        }
    }

    fn gen_req() -> GenerateRequest {
        GenerateRequest {
            node: dummy_node(),
            target: target(),
            module_context: ModuleContext::default(),
            prior_decisions: Vec::new(),
            strictness: Strictness::Development,
        }
    }

    #[tokio::test]
    async fn generate_first_call_misses_then_hits() {
        let dir = tempfile::tempdir().unwrap();
        let provider = CachingProvider::new(StubProvider::default(), AiCache::new(dir.path()));
        let req = gen_req();

        let (r1, hit1) = provider.generate_cached(&req).await.unwrap();
        assert!(!hit1, "first call should miss");

        let (r2, hit2) = provider.generate_cached(&req).await.unwrap();
        assert!(hit2, "second call should hit cache");
        assert_eq!(r1, r2);
    }

    #[tokio::test]
    async fn repair_round_trips_through_cache() {
        let dir = tempfile::tempdir().unwrap();
        let provider = CachingProvider::new(StubProvider::default(), AiCache::new(dir.path()));
        let req = RepairRequest {
            original_code: "let x = 1;".into(),
            compiler_error: "missing semicolon".into(),
            node: dummy_node(),
            target: target(),
        };
        let (_, h1) = provider.repair_cached(&req).await.unwrap();
        let (_, h2) = provider.repair_cached(&req).await.unwrap();
        assert!(!h1);
        assert!(h2);
    }

    #[tokio::test]
    async fn optimize_round_trips_through_cache() {
        let dir = tempfile::tempdir().unwrap();
        let provider = CachingProvider::new(StubProvider::default(), AiCache::new(dir.path()));
        let req = OptimizeRequest {
            working_code: "return 1;".into(),
            node: dummy_node(),
            target: target(),
            optimization_hints: vec![OptimizationHint::Performance],
        };
        let (_, h1) = provider.optimize_cached(&req).await.unwrap();
        let (_, h2) = provider.optimize_cached(&req).await.unwrap();
        assert!(!h1);
        assert!(h2);
    }

    #[tokio::test]
    async fn select_round_trips_through_cache() {
        let dir = tempfile::tempdir().unwrap();
        let provider = CachingProvider::new(StubProvider::default(), AiCache::new(dir.path()));
        let req = SelectRequest {
            options: vec![
                SelectOption {
                    id: "retry".into(),
                    description: "retry".into(),
                },
                SelectOption {
                    id: "fallback".into(),
                    description: "fallback".into(),
                },
            ],
            context: SelectContext::default(),
            rationale_prompt: "pick one".into(),
        };
        let (_, h1) = provider.select_cached(&req).await.unwrap();
        let (_, h2) = provider.select_cached(&req).await.unwrap();
        assert!(!h1);
        assert!(h2);
    }

    #[tokio::test]
    async fn trait_impl_drops_from_cache_signal() {
        let dir = tempfile::tempdir().unwrap();
        let provider = CachingProvider::new(StubProvider::default(), AiCache::new(dir.path()));
        let req = gen_req();
        // Calling through the trait should also populate and read the
        // cache, just without surfacing the signal.
        let r1 = provider.generate(&req).await.unwrap();
        let r2 = provider.generate(&req).await.unwrap();
        assert_eq!(r1, r2);
        // Underlying cache now has exactly one entry.
        assert_eq!(provider.cache().stats().unwrap().entries, 1);
    }

    #[tokio::test]
    async fn distinct_requests_do_not_collide() {
        let dir = tempfile::tempdir().unwrap();
        let provider = CachingProvider::new(StubProvider::default(), AiCache::new(dir.path()));

        let r1 = RepairRequest {
            original_code: "let x = 1;".into(),
            compiler_error: "e1".into(),
            node: dummy_node(),
            target: target(),
        };
        let r2 = RepairRequest {
            original_code: "let x = 2;".into(),
            compiler_error: "e1".into(),
            node: dummy_node(),
            target: target(),
        };

        let (_, h1) = provider.repair_cached(&r1).await.unwrap();
        let (_, h2) = provider.repair_cached(&r2).await.unwrap();
        assert!(!h1);
        assert!(!h2, "different request must miss separately");
        assert_eq!(provider.cache().stats().unwrap().entries, 2);
    }

    #[tokio::test]
    async fn alternative_serializes_through_cache() {
        // Sanity: ensure the response types we cache survive a JSON
        // round trip including their nested Alternative records.
        let dir = tempfile::tempdir().unwrap();
        let provider = CachingProvider::new(StubProvider::default(), AiCache::new(dir.path()));
        let req = gen_req();
        let (resp, _) = provider.generate_cached(&req).await.unwrap();
        let _alt = Alternative {
            label: "rendered".into(),
            reasoning: None,
            confidence: 0.5,
        };
        // Round trip the actual cached response.
        let bytes = serde_json::to_vec(&resp).unwrap();
        let _back: GenerateResponse = serde_json::from_slice(&bytes).unwrap();
    }
}