hol-cigar 0.14.2

Open-source context engineering protocol for AI agents: governed retrieval, bounded multi-agent handoffs, MCP, provenance, recoverable effects, and replay.
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
//! The `cigar.context-worker.v1` stdio worker, as a library.
//!
//! Applications that ship their own native process can serve the worker protocol
//! without the separate `cigar-context-worker` binary: call [`serve`] with the
//! process's stdin and stdout (or any line-based reader and writer), or [`main`]
//! to take the same arguments as the binary. The protocol, limits and replies are
//! the binary's; the binary itself is a thin wrapper around [`main`].
//!
//! One caller-owned graph and cache per call to [`serve`]. Frames are bounded,
//! unknown fields are refused, and errors never echo input.
use crate::{
    AnswerDraft, AnswerPolicy, ClaimReview, ContextDelta, ContextError, ContextGraph,
    ContextPrompt, ContextRequest, ContextSnapshot, ContextView, ContextViewHandle,
    ContextViewSpec, ContextViews, Document, EdgeKind, GraphLimits, O200kTokenizer,
    TokenCacheLimits, TokenCounter,
};
use serde::Deserialize;
use serde_json::{Value, json};
use std::io::{BufRead, Read, Write};

#[cfg(feature = "broker")]
mod broker_worker;

/// The worker protocol this module speaks.
pub const PROTOCOL: &str = "cigar.context-worker.v1";
/// The `cigar-context` release this worker was built from, reported as
/// `core_version` in the `init` reply.
pub const CORE_VERSION: &str = env!("CARGO_PKG_VERSION");
const MAX_FRAME: usize = 32 * 1024 * 1024;
const MAX_RESPONSE: usize = 64 * 1024 * 1024;

#[derive(Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct Limits {
    max_documents: Option<usize>,
    max_document_bytes: Option<usize>,
    max_total_bytes: Option<usize>,
    max_edges_per_document: Option<usize>,
    max_edges: Option<usize>,
    cache_entries: Option<usize>,
    cache_text_bytes: Option<usize>,
}

#[derive(Deserialize)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
enum Command {
    Init {
        domain: String,
        #[serde(default)]
        limits: Limits,
    },
    Upsert {
        document: Document,
    },
    ReplaceSource {
        source: String,
        documents: Vec<Document>,
    },
    Remove {
        node_id: String,
    },
    Link {
        from: String,
        to: String,
        kind: EdgeKind,
    },
    Unlink {
        from: String,
        to: String,
        kind: EdgeKind,
    },
    Compile {
        request: ContextRequest,
    },
    Explain {
        request: ContextRequest,
        snapshot: ContextSnapshot,
    },
    ReviewKeys {
        draft: AnswerDraft,
    },
    CheckAnswer {
        request: ContextRequest,
        draft: AnswerDraft,
        reviews: Vec<ClaimReview>,
        #[serde(default)]
        policy: AnswerPolicy,
    },
    Chunks {
        document: Document,
        max_lines: usize,
        overlap_lines: usize,
    },
    ChunksAtLines {
        document: Document,
        starts: Vec<usize>,
    },
    Verify {
        snapshot: ContextSnapshot,
    },
    PromptView {
        snapshot: ContextSnapshot,
        max_tokens: usize,
    },
    VerifyPrompt {
        snapshot: ContextSnapshot,
        prompt: ContextPrompt,
    },
    ResolveCitation {
        snapshot: ContextSnapshot,
        prompt: ContextPrompt,
        reference: String,
    },
    Delta {
        base: ContextSnapshot,
        target: ContextSnapshot,
    },
    ApplyDelta {
        base: ContextSnapshot,
        delta: ContextDelta,
    },
    Stats {},
    ClearCache {},
    DefineView {
        spec: ContextViewSpec,
    },
    RevokeView {
        view_id: String,
    },
    CompileView {
        view: ContextViewHandle,
        request: ContextRequest,
    },
    ExplainView {
        view: ContextViewHandle,
        context: ContextView,
    },
    ReplaceViewSource {
        view: ContextViewHandle,
        source: String,
        documents: Vec<Document>,
    },
    CheckViewAnswer {
        view: ContextViewHandle,
        context: ContextView,
        draft: AnswerDraft,
        reviews: Vec<ClaimReview>,
        #[serde(default)]
        policy: AnswerPolicy,
    },
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Request {
    id: u32,
    command: Command,
}

struct Session {
    graph: ContextGraph,
    tokenizer: O200kTokenizer,
    views: ContextViews,
}

impl Session {
    fn new(domain: String, limits: Limits) -> Result<Self, ContextError> {
        let defaults = GraphLimits::default();
        let cache = TokenCacheLimits::default();
        let graph = ContextGraph::new(
            domain,
            GraphLimits {
                max_documents: limits.max_documents.unwrap_or(defaults.max_documents),
                max_document_bytes: limits
                    .max_document_bytes
                    .unwrap_or(defaults.max_document_bytes),
                max_total_bytes: limits.max_total_bytes.unwrap_or(defaults.max_total_bytes),
                max_edges_per_document: limits
                    .max_edges_per_document
                    .unwrap_or(defaults.max_edges_per_document),
                max_edges: limits.max_edges.unwrap_or(defaults.max_edges),
            },
        )?;
        let tokenizer = O200kTokenizer::with_cache_limits(TokenCacheLimits {
            max_entries: limits.cache_entries.unwrap_or(cache.max_entries),
            max_text_bytes: limits.cache_text_bytes.unwrap_or(cache.max_text_bytes),
        })?;
        Ok(Self {
            graph,
            tokenizer,
            views: ContextViews::default(),
        })
    }

    fn rendered(&self, snapshot: ContextSnapshot) -> Result<Value, ContextError> {
        let rendered = snapshot.render_verified(&self.tokenizer)?;
        Ok(json!({"rendered": rendered, "snapshot": snapshot}))
    }

    fn execute(&mut self, command: Command) -> Result<Value, ContextError> {
        match command {
            Command::Init { .. } => Err(ContextError::InvalidInput),
            Command::Upsert { document } => Ok(json!(self.graph.upsert(document)?)),
            Command::ReplaceSource { source, documents } => {
                Ok(json!(self.graph.replace_source(&source, documents)?))
            }
            Command::Remove { node_id } => Ok(json!(self.graph.remove(&node_id)?)),
            Command::Link { from, to, kind } => Ok(json!(self.graph.link(&from, &to, kind)?)),
            Command::Unlink { from, to, kind } => Ok(json!(self.graph.unlink(&from, &to, kind)?)),
            Command::Compile { request } => {
                self.rendered(self.graph.compile(&request, &self.tokenizer)?)
            }
            Command::Explain { request, snapshot } => Ok(json!(self.graph.explain(
                &request,
                &snapshot,
                &self.tokenizer
            )?)),
            Command::ReviewKeys { draft } => Ok(json!(draft.review_keys()?)),
            Command::CheckAnswer {
                request,
                draft,
                reviews,
                policy,
            } => Ok(json!(self.graph.check_answer(
                &request,
                &draft,
                &reviews,
                &policy,
                &self.tokenizer
            )?)),
            Command::Chunks {
                document,
                max_lines,
                overlap_lines,
            } => Ok(json!(document.chunks(max_lines, overlap_lines)?)),
            Command::ChunksAtLines { document, starts } => {
                Ok(json!(document.chunks_at_lines(&starts)?))
            }
            Command::Verify { snapshot } => self.rendered(snapshot),
            Command::PromptView {
                snapshot,
                max_tokens,
            } => Ok(json!(snapshot.prompt_view(max_tokens, &self.tokenizer)?)),
            Command::VerifyPrompt { snapshot, prompt } => {
                prompt.verify(&snapshot, &self.tokenizer)?;
                Ok(json!(prompt))
            }
            Command::ResolveCitation {
                snapshot,
                prompt,
                reference,
            } => Ok(json!(prompt.resolve(
                &reference,
                &snapshot,
                &self.tokenizer
            )?)),
            Command::Delta { base, target } => {
                Ok(json!(target.delta_from(&base, &self.tokenizer)?))
            }
            Command::ApplyDelta { base, delta } => {
                self.rendered(delta.apply(&base, &self.tokenizer)?)
            }
            Command::Stats {} => {
                let cache = self.tokenizer.cache_stats()?;
                Ok(
                    json!({"documents": self.graph.len(), "revision": self.graph.revision(),
                    "cache": {"hits": cache.hits, "misses": cache.misses,
                        "entries": cache.entries, "text_bytes": cache.text_bytes}}),
                )
            }
            Command::ClearCache {} => {
                self.tokenizer.clear_cache()?;
                Ok(Value::Null)
            }
            Command::DefineView { spec } => Ok(json!(self.views.define(spec)?)),
            Command::RevokeView { view_id } => Ok(json!(self.views.revoke(&view_id))),
            Command::CompileView { view, request } => {
                let context = self
                    .views
                    .compile(&self.graph, &view, &request, &self.tokenizer)?;
                Ok(json!({"rendered": context.snapshot().render(), "context": context}))
            }
            Command::ExplainView { view, context } => Ok(json!(self.views.explain(
                &self.graph,
                &view,
                &context,
                &self.tokenizer,
            )?)),
            Command::ReplaceViewSource {
                view,
                source,
                documents,
            } => Ok(json!(self.views.replace_source(
                &mut self.graph,
                &view,
                &source,
                documents
            )?)),
            Command::CheckViewAnswer {
                view,
                context,
                draft,
                reviews,
                policy,
            } => Ok(json!(self.views.check_answer(
                &self.graph,
                &view,
                &context,
                &draft,
                &reviews,
                &policy,
                &self.tokenizer
            )?)),
        }
    }
}

fn handle(session: &mut Option<Session>, command: Command) -> Result<Value, ContextError> {
    if let Some(session) = session {
        return session.execute(command);
    }
    if let Command::Init { domain, limits } = command {
        let value = Session::new(domain, limits)?;
        let reply = json!({"protocol": PROTOCOL, "core_version": CORE_VERSION,
        "tokenizer": value.tokenizer.identity(), "max_frame_bytes": MAX_FRAME,
        "max_response_bytes": MAX_RESPONSE, "capabilities": [
            "context_graph.v1", "source_replace.v1", "snapshot_integrity.v1",
            "answer_review.v1", "context_views.v1", "selection_explanation.v1", "document_boundaries.v1"
        ]});
        *session = Some(value);
        Ok(reply)
    } else {
        Err(ContextError::InvalidInput)
    }
}

/// Serve worker frames from `input` until it ends or a frame is refused.
///
/// Each request is one JSON line; each reply is one JSON line written to
/// `output` and flushed. An oversized, unterminated or malformed frame ends the
/// session, as in the binary.
pub fn serve(input: &mut impl BufRead, output: &mut impl Write) -> std::io::Result<()> {
    let mut session = None;
    loop {
        let mut frame = Vec::new();
        let bytes = input
            .take((MAX_FRAME + 1) as u64)
            .read_until(b'\n', &mut frame)?;
        if bytes == 0 {
            return Ok(());
        }
        // Over-limit or unterminated frames invalidate the transport; do not resynchronize.
        if bytes > MAX_FRAME || frame.last() != Some(&b'\n') {
            return Ok(());
        }
        let reply = match serde_json::from_slice::<Request>(&frame) {
            Ok(request) => match handle(&mut session, request.command) {
                Ok(value) => json!({"id": request.id, "ok": true, "result": value}),
                Err(error) => json!({"id": request.id, "ok": false, "error": format!("{error:?}")}),
            },
            // Malformed commands cannot be safely correlated. Close after a content-free error.
            Err(_) => {
                output.write_all(b"{\"id\":null,\"ok\":false,\"error\":\"InvalidInput\"}\n")?;
                output.flush()?;
                return Ok(());
            }
        };
        let mut encoded = serde_json::to_vec(&reply)?;
        encoded.push(b'\n');
        if encoded.len() > MAX_RESPONSE {
            return Ok(());
        }
        output.write_all(&encoded)?;
        output.flush()?;
    }
}

/// Run the worker the way the `cigar-context-worker` binary does.
///
/// `args` are the command-line arguments after the program name: none to serve
/// the stdio protocol, `--version` to print the version and protocol, or
/// `--broker` (with the `broker` feature) to run the local broker host.
pub fn main(args: &[String]) -> std::io::Result<()> {
    #[cfg(feature = "broker")]
    if args == ["--broker"] {
        return broker_worker::run();
    }
    if args == ["--version"] {
        println!(
            "cigar-context-worker {} {PROTOCOL}",
            env!("CARGO_PKG_VERSION")
        );
        return Ok(());
    }
    if !args.is_empty() {
        return Err(std::io::Error::other("worker accepts JSONL on stdin only"));
    }
    serve(&mut std::io::stdin().lock(), &mut std::io::stdout().lock())
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn rejects_unknown_fields_without_echoing_input() -> Result<(), Box<dyn std::error::Error>> {
        let input = b"{\"id\":1,\"command\":{\"op\":\"stats\",\"secret\":\"PRIVATE\"}}\n";
        let mut out = Vec::new();
        serve(&mut &input[..], &mut out)?;
        assert_eq!(
            out,
            b"{\"id\":null,\"ok\":false,\"error\":\"InvalidInput\"}\n"
        );
        Ok(())
    }
    #[test]
    fn rejects_partial_and_oversized_frames() -> Result<(), Box<dyn std::error::Error>> {
        for input in [b"{}".to_vec(), vec![b' '; MAX_FRAME + 1]] {
            let mut out = Vec::new();
            serve(&mut &input[..], &mut out)?;
            assert!(out.is_empty());
        }
        Ok(())
    }
    #[test]
    fn initialization_is_once_and_required() -> Result<(), Box<dyn std::error::Error>> {
        let mut session = None;
        assert_eq!(
            handle(&mut session, Command::Stats {}),
            Err(ContextError::InvalidInput)
        );
        let init = || Command::Init {
            domain: "test".into(),
            limits: Limits::default(),
        };
        assert_eq!(
            handle(&mut session, init())?.get("protocol"),
            Some(&json!(PROTOCOL))
        );
        assert_eq!(
            handle(&mut session, init()),
            Err(ContextError::InvalidInput)
        );
        assert_eq!(
            handle(&mut session, Command::Stats {})?.get("documents"),
            Some(&json!(0))
        );
        Ok(())
    }
}