Skip to main content

velesdb_memory/context/
model.rs

1//! Data model of the context compiler: the request/response value types.
2//!
3//! Like [`crate::model`], these are pure data with `Serialize`/`Deserialize` +
4//! `JsonSchema` derives, so the domain types double as the MCP wire types —
5//! no duplicate DTO layer. Invariants the compiler upholds over these shapes:
6//! same request ⇒ byte-identical [`CompiledContext`] (determinism), and the
7//! assembled content never exceeds the request's token budget.
8
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11use serde_json::{Map, Value};
12
13use super::chunk::ChunkPolicy;
14use super::insights::CompilationInsights;
15
16/// What the compiler decided to do with one fragment.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
18#[serde(rename_all = "lowercase")]
19pub enum ContextAction {
20    /// Emitted verbatim — critical content (code, constraints, exact values).
21    Preserve,
22    /// Emitted as a deterministic structured reduction (never a generative
23    /// summary) — e.g. repeated log lines collapsed with a count.
24    Abstract,
25    /// Not emitted, but recoverable through its `ctx://source/<id>` handle.
26    Retrieve,
27    /// Not emitted and not externalized — redundant content (duplicates).
28    Drop,
29    /// Emitted verbatim at the front of the output, forming a stable prefix
30    /// that maximizes provider prompt-cache hits across compilations.
31    Cache,
32}
33
34/// How much fidelity a compiled context may have lost versus its input.
35///
36/// Ordered: `Low < Medium < High`, so callers can compare against a policy
37/// threshold.
38#[derive(
39    Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
40)]
41#[serde(rename_all = "lowercase")]
42pub enum FidelityRisk {
43    /// Nothing was lost: everything fit, only exact duplicates were dropped.
44    #[default]
45    Low,
46    /// Recoverable reductions happened: abstractions, or non-critical
47    /// fragments externalized behind retrieval handles.
48    Medium,
49    /// Critical content (a preserve-classified fragment) could not be packed
50    /// — the caller should consider retrieving it or raising the budget.
51    High,
52}
53
54/// Inline media payload attached to a [`ContextFragment`] (US-009, PR1:
55/// screenshots/images only). `ContextFragment::content` stays the
56/// text/caption — often empty for a bare screenshot — while the pixels live
57/// here, base64-encoded so the JSON wire never needs a binary frame.
58///
59/// The fragment packs atomically (see [`super::pieces`] in the compiler)
60/// and its token cost comes from [`super::estimator::ImageTokenEstimator`].
61/// A media fragment that cannot fit the budget is externalized behind a
62/// `ctx://source` handle exactly like text (US-009, PR2: the memory bridge
63/// persists the bytes behind it — see
64/// [`crate::MemoryService::retrieve_context_source`]); the memoryless core
65/// compiler mints the same handle either way, since it never knows whether
66/// a resolver is attached. See the crate README's "media fragments"
67/// section.
68#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
69pub struct MediaRef {
70    /// Declared MIME type (e.g. `"image/png"`, `"image/jpeg"`). Only PNG and
71    /// JPEG headers are sniffed for dimensions; any other value (or an
72    /// unreadable header) falls back to a deterministic, safe over-count
73    /// (see [`super::estimator::ImageTokenEstimator`]) — never rejected for
74    /// an unrecognized mime alone.
75    pub mime: String,
76    /// The raw media bytes, base64-encoded (standard alphabet, padded).
77    /// Capped at [`crate::limits::MAX_MEDIA_BYTES`] and validated for
78    /// well-formedness at compile time — a request carrying an oversized or
79    /// malformed payload is rejected before any other work.
80    pub bytes_b64: String,
81}
82
83/// The resolved original behind a `ctx://source/<hash>` handle (US-002:
84/// text sources; US-009 PR2 extends this with the fragment's inline media,
85/// when it carried one). `media` is `#[serde(default)]`: every source
86/// stored before PR2, and every text-only fragment since, round-trips with
87/// `media: None` — the exact pre-PR2 shape for a caller reading only
88/// `.content`.
89#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
90pub struct ContextSource {
91    /// The original fragment content, byte for byte (a media fragment's
92    /// caption — often empty for a bare screenshot).
93    pub content: String,
94    /// The original media payload, when the fragment carried one.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub media: Option<MediaRef>,
97}
98
99/// One unit of caller-supplied context to compile.
100#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
101#[schemars(transform = crate::schema::strip_int_formats)]
102pub struct ContextFragment {
103    /// Caller-side identifier. When absent, the compiler derives a stable
104    /// content-addressed id (see [`super::fragment_id`]). Accepts a JSON
105    /// number or a decimal string on input (see
106    /// [`super::wire::deserialize_optional_id`]) — a caller that got a
107    /// `fragment_id` back as a string (e.g. under
108    /// [`CompilePolicy::ids_as_strings`]) can resubmit it unchanged.
109    #[serde(
110        default,
111        skip_serializing_if = "Option::is_none",
112        deserialize_with = "super::wire::deserialize_optional_id"
113    )]
114    pub id: Option<u64>,
115    /// The fragment text. `#[serde(default)]` (V2b-1): a `path` fragment
116    /// carries no `content` on the wire — the adapter resolves `path` into
117    /// `content` in a pre-pass before the pure compiler core ever sees the
118    /// request, so this stays the only field the core reads.
119    #[serde(default)]
120    pub content: String,
121    /// Read this file's content from disk in place of an inline `content`
122    /// (V2b-1 path ingestion). `path` is EXCLUSIVE — it is resolved into
123    /// `content` before the compiler core runs, so a fragment carrying
124    /// `path` together with `content` or `media` is rejected. `content` and
125    /// `media` together are fine, and are the intended shape for an image
126    /// and its caption. A fragment carrying none of the three is rejected
127    /// as well. Requires the server to be started
128    /// with `VELESDB_MEMORY_INGEST_ROOTS` set (a colon/semicolon-separated
129    /// allowlist of directories, platform `PATH`-list syntax); otherwise
130    /// every `path` fragment fails with an explicit "ingestion disabled"
131    /// error. The path must be absolute and resolve (after following
132    /// symlinks) to a plain file under one of the configured roots, no
133    /// larger than [`crate::limits::MAX_INGEST_FILE_BYTES`] and valid UTF-8.
134    /// The **pure compiler core never reads this field** — resolution is an
135    /// adapter-side I/O pre-pass (see the crate's `context::ingest`
136    /// module); a `path` fragment that reaches [`super::ContextCompiler`]
137    /// unresolved is rejected with
138    /// [`crate::error::MemoryError::IngestDisabled`].
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub path: Option<String>,
141    /// Free-form kind hint (`"code"`, `"log"`, `"prose"`, …) — classification
142    /// works without it, but honors it when present.
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub kind: Option<String>,
145    /// Caller priority, higher packs first (default `0`).
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub priority: Option<u8>,
148    /// Caller metadata. Recognized keys: `"verbatim": true` forces
149    /// [`ContextAction::Preserve`]; `"cache": true` forces
150    /// [`ContextAction::Cache`].
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    pub metadata: Option<Map<String, Value>>,
153    /// Inline media payload (US-009, PR1). `None` (the default) keeps every
154    /// pre-0.9.0 request wire-compatible. When set, the fragment packs as one
155    /// atomic piece — see [`MediaRef`].
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub media: Option<MediaRef>,
158}
159
160/// Which memories the compiler may pull in alongside the caller's fragments.
161/// Consumed by the memory bridge (US-002); carried in the request shape from
162/// the start so the wire contract does not change when it lands.
163#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
164#[schemars(transform = crate::schema::strip_int_formats)]
165pub struct MemoryScope {
166    /// Restrict recalled memories to this project facet.
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub project: Option<String>,
169    /// How many memories to consider (adapter-clamped).
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    pub k: Option<usize>,
172    /// Graph-walk depth of the fused recall (default 2). Deeper hops reach
173    /// longer cause/fix chains from the vector seed.
174    #[serde(default, skip_serializing_if = "Option::is_none")]
175    pub hops: Option<usize>,
176    /// Fusion weight added to graph-reached memories (default 0.15). Raise
177    /// it (e.g. `0.5`–`0.8`) when pulling from curated fact chains built
178    /// with `relate`: evidence that shares **no vocabulary** with the query
179    /// can then out-rank lexically-noisy near-misses — the tri-engine's
180    /// answer to the purely lexical relevance of caller fragments.
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub graph_boost: Option<f64>,
183}
184
185/// Usage-driven importance weights of the memory-bridge blend (US-002 of
186/// EPIC-P-071): how much a pulled memory's learned RL confidence and its
187/// batch-relative recency tilt the fused similarity ranking.
188///
189/// The blend only ever applies to the pool the fused vector+graph similarity
190/// already selected — confidence is *not* relevance, so a heavily reinforced
191/// but off-topic fact can never enter the pool through these weights. Per
192/// pulled memory the ranking key becomes
193/// `fused_norm + confidence_weight·(confidence − 0.5)·2 + recency_weight·recency_norm`,
194/// clock-free and deterministic (recency is min-max normalised **within the
195/// pulled batch**, never against wall time).
196///
197/// Both weights at `0.0` disable the blend entirely: the output is
198/// byte-identical to the 0.8.0 behaviour (pinned by a golden test). The
199/// defaults are **active** on purpose — upgrading from 0.8.0 with the
200/// default policy, RL-reinforced memories rank higher out of the box; zero
201/// the weights to restore the exact 0.8.0 ordering.
202///
203/// Recommended range for both weights: `[0.0, 1.0]` (at `1.0` a term can
204/// fully offset the similarity gap within the pool). Values outside that
205/// range are **accepted verbatim, never clamped** — a negative weight
206/// deliberately inverts its term (e.g. demote reinforced facts), a weight
207/// above `1.0` lets the term dominate similarity. Only the recorded
208/// decision `relevance` is clamped into `[0, 1]`; the ranking itself uses
209/// the raw blended score.
210#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
211#[serde(default)]
212pub struct ImportanceWeights {
213    /// Weight of the learned RL confidence (`_veles_rl_*`, fed by
214    /// [`feedback`](crate::MemoryService::feedback)). A memory with no
215    /// feedback history counts as the neutral `0.5`, contributing exactly
216    /// `0`. Default `0.2`.
217    pub confidence: f64,
218    /// Weight of the batch-relative recency term. Inert unless
219    /// [`Self::recency_field`] is also set. Default `0.1`.
220    pub recency: f64,
221    /// Caller metadata key holding each memory's **numeric** timestamp-like
222    /// value. `None` (the default) disables the recency term completely —
223    /// there is no standard key to guess. The scale must be monotone and
224    /// homogeneous across the batch (e.g. `YYYYMMDD` integers as in
225    /// [`crate::format_dated_context`], or an epoch); it is documented, not
226    /// verified at run time. Values are min-max normalised over the pulled
227    /// memories that carry the key; a memory without the key contributes `0`
228    /// (never penalised), and a degenerate batch (`max == min`) contributes
229    /// `0` for all.
230    #[serde(skip_serializing_if = "Option::is_none")]
231    pub recency_field: Option<String>,
232}
233
234impl Default for ImportanceWeights {
235    fn default() -> Self {
236        Self {
237            confidence: 0.2,
238            recency: 0.1,
239            recency_field: None,
240        }
241    }
242}
243
244/// Tuning knobs of one compilation. `Default` is the recommended profile.
245#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
246#[serde(default)]
247#[schemars(transform = crate::schema::strip_int_formats)]
248#[allow(clippy::struct_excessive_bools)]
249pub struct CompilePolicy {
250    /// Tokens kept aside for the model's answer; the compiler packs into
251    /// `token_budget − response_reserve_tokens`. Default `0`: the caller
252    /// knows their generation length, the compiler does not guess it.
253    pub response_reserve_tokens: u64,
254    /// Collapse near-duplicates (case/whitespace variants) in addition to
255    /// exact duplicates. Default `true`.
256    pub near_dup_dedup: bool,
257    /// Rule ids to disable (e.g. `"abstract.log_dedup"`). Disabled rules are
258    /// skipped during classification; their fragments fall through to the
259    /// next matching rule.
260    pub disabled_rules: Vec<String>,
261    /// How oversized fragments are split before packing. Only
262    /// [`ChunkPolicy::max_chunk_bytes`] and [`ChunkPolicy::boundary`] apply
263    /// here — the compiler forces `overlap_bytes` to `0`, since it emits
264    /// pieces by concatenation and an overlap prefix would duplicate content
265    /// reported as verbatim. `overlap_bytes` is honoured only by the
266    /// standalone [`crate::context::chunk::chunk_text`] API.
267    pub chunk: ChunkPolicy,
268    /// Memory bridge only: record a compilation event (metadata and hashes,
269    /// **never fragment content**) so savings stay aggregatable. Default
270    /// `true`; set `false` to opt out entirely.
271    pub record_events: bool,
272    /// Memory bridge only: store each distinct fragment's original (as an
273    /// internal system fact, invisible to normal recall) so its
274    /// `ctx://source/<hash>` handle round-trips. Default `true`.
275    pub store_sources: bool,
276    /// TTL applied to stored sources (`None` keeps them until forgotten).
277    #[serde(skip_serializing_if = "Option::is_none")]
278    pub source_ttl_seconds: Option<u64>,
279    /// TTL applied to compilation events (`None` keeps them).
280    #[serde(skip_serializing_if = "Option::is_none")]
281    pub event_ttl_seconds: Option<u64>,
282    /// Caller-supplied pricing table so the insights also report the
283    /// estimated cost avoided for [`super::model::CompileRequest::target_model`] — the
284    /// **wire channel** for cost accounting (MCP and the bindings cannot
285    /// reach the Rust-only [`super::ContextCompiler::with_pricing`] builder).
286    /// Takes precedence over a builder-injected table. `None` (default)
287    /// reports tokens only.
288    #[serde(skip_serializing_if = "Option::is_none")]
289    pub pricing: Option<super::insights::PricingTable>,
290    /// Memory bridge only: usage-driven importance blend over the pulled
291    /// memories (RL confidence + batch-relative recency). The struct-level
292    /// `#[serde(default)]` keeps 0.8.0 requests wire-compatible.
293    pub importance: ImportanceWeights,
294    /// Opt-in, deterministic: before `abstract.log_dedup` groups a `kind =
295    /// "log"` fragment's repeated lines, mask each line's volatile prefix
296    /// (ISO/syslog timestamps, bracketed hex/pid counters) with **fixed**
297    /// patterns — never a caller-supplied regex, so the collapse stays
298    /// reproducible — so lines identical modulo timestamp collapse into one
299    /// annotated line instead of surviving as distinct entries. The emitted
300    /// line is still the first occurrence's exact bytes; only the grouping
301    /// key changes. Default `false`: masking is opt-in because it changes
302    /// what "duplicate" means for logs, so callers who rely on the previous
303    /// byte-exact grouping keep it unless they ask. See the crate README's
304    /// "Normalizing timestamped logs" section for the exact patterns.
305    pub normalize_log_timestamps: bool,
306    /// Wire-compat opt-in for the MCP context tools (`compile_context`,
307    /// `explain_compilation`): when `true`, every [`super::wire::ID_KEYS`]
308    /// field of the RESPONSE (`fragment_id`, `content_hash`, `memory_id`,
309    /// `fragment_ids`) is rewritten into its decimal-string form, through
310    /// the exact same tree walk the Node and WASM bindings already apply on
311    /// every response ([`super::wire::stringify_id_fields`]). A raw MCP
312    /// client — one that talks JSON-RPC directly, without either binding —
313    /// parses ids as JS `number`s (IEEE-754 doubles), which silently lose
314    /// precision above 2^53; string ids round-trip exactly. Default
315    /// `false`: existing MCP clients keep today's byte-identical numeric
316    /// response unless they opt in.
317    pub ids_as_strings: bool,
318    /// Quick win (V2a-2): when `true`, `sections` and `decisions` are
319    /// emptied out of the response after compilation — `content`,
320    /// `insights`, `risk`, `warnings`, `sources`, and `retrieval_handles`
321    /// are unaffected. The full audit trail (`sections`/`decisions`) is
322    /// still recoverable: re-compile the same request without
323    /// `slim_response` (compilation is deterministic, so nothing is lost,
324    /// only not sent this time). Default `false`.
325    pub slim_response: bool,
326}
327
328impl Default for CompilePolicy {
329    fn default() -> Self {
330        Self {
331            response_reserve_tokens: 0,
332            near_dup_dedup: true,
333            disabled_rules: Vec::new(),
334            chunk: ChunkPolicy::default(),
335            record_events: true,
336            store_sources: true,
337            source_ttl_seconds: None,
338            event_ttl_seconds: None,
339            pricing: None,
340            importance: ImportanceWeights::default(),
341            normalize_log_timestamps: false,
342            ids_as_strings: false,
343            slim_response: false,
344        }
345    }
346}
347
348/// Aggregated savings over the recorded compilation events (memory bridge).
349#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
350#[schemars(transform = crate::schema::strip_int_formats)]
351pub struct ContextSavings {
352    /// Number of compilation events aggregated.
353    pub events: u64,
354    /// Sum of estimated input tokens across events.
355    pub tokens_in: u64,
356    /// Sum of estimated output tokens across events.
357    pub tokens_out: u64,
358    /// Sum of estimated tokens saved across events.
359    pub tokens_saved: u64,
360    /// Estimated cost avoided, in micro-units, keyed by currency (events
361    /// priced under different pricing tables never silently mix).
362    pub cost_saved_micros_by_currency: std::collections::BTreeMap<String, u64>,
363    /// `true` when the aggregation hit the recall cap
364    /// ([`crate::limits::MAX_RECALL_LIMIT`]) — older events beyond the cap
365    /// were not folded in.
366    pub truncated: bool,
367}
368
369/// A full compile request: what to compile, under which budget, for whom.
370#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
371#[schemars(transform = crate::schema::strip_int_formats)]
372pub struct CompileRequest {
373    /// What the agent is working on — drives relevance scoring.
374    pub query: String,
375    /// The context fragments to compile.
376    pub fragments: Vec<ContextFragment>,
377    /// Project facet, recorded in provenance and used by the memory bridge.
378    #[serde(default, skip_serializing_if = "Option::is_none")]
379    pub project: Option<String>,
380    /// Target model name — selects the row of the pricing table
381    /// ([`CompilePolicy::pricing`] on the wire, or the Rust
382    /// [`super::ContextCompiler::with_pricing`] builder) for cost insights.
383    /// Without a table, insights report tokens only.
384    #[serde(default, skip_serializing_if = "Option::is_none")]
385    pub target_model: Option<String>,
386    /// Hard token ceiling for the assembled content.
387    pub token_budget: u64,
388    /// Which memories may be pulled in (US-002; ignored by the memoryless core).
389    #[serde(default, skip_serializing_if = "Option::is_none")]
390    pub memory_scope: Option<MemoryScope>,
391    /// Per-request policy override; `None` uses the compiler's policy.
392    #[serde(default, skip_serializing_if = "Option::is_none")]
393    pub policy: Option<CompilePolicy>,
394}
395
396/// Where a section sits in the assembled output.
397#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
398#[serde(rename_all = "lowercase")]
399pub enum SectionKind {
400    /// The stable, cache-marked prefix.
401    Cache,
402    /// The main compiled body.
403    Body,
404}
405
406/// One contiguous block of the assembled output.
407#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
408#[schemars(transform = crate::schema::strip_int_formats)]
409pub struct CompiledSection {
410    /// Which block this is.
411    pub kind: SectionKind,
412    /// The block's text (verbatim slice of [`CompiledContext::content`]).
413    pub content: String,
414    /// Ids of the fragments emitted into this block, in emission order.
415    pub fragment_ids: Vec<u64>,
416}
417
418/// A pointer from a compiled output back to one original fragment.
419#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
420#[schemars(transform = crate::schema::strip_int_formats)]
421pub struct SourceReference {
422    /// The fragment this source refers to. Accepts a JSON number OR a
423    /// decimal string on input: a `fragment_id` is an FNV-1a 64 content hash
424    /// (see [`ContextDecision::content_hash`]), so it is almost always above
425    /// 2^53 — a float-lossy JSON client that reads one back from a compiled
426    /// context and resubmits it inside a working context would otherwise
427    /// corrupt it silently. Same accepted-forms rule as issue #1468's ids;
428    /// the serialized (output) shape is unchanged.
429    #[serde(deserialize_with = "crate::model::deserialize_id")]
430    pub fragment_id: u64,
431    /// Recoverable address of the original content (`ctx://source/<id>`).
432    pub handle: String,
433    // Un doc-comment de CHAMP est publie tel quel dans la description du
434    // schema annonce (`docs/reference/mcp-tools.json`) : l'archeologie va donc
435    // ici, en commentaire ordinaire, et le contrat seul va au-dessus.
436    //
437    // Aller-retour casse jusqu'au 2026-07-29, trouve en interrogeant le
438    // serveur plutot qu'en relisant le code : `memory_id` fait partie des
439    // `super::wire::ID_KEYS`, donc une reponse sous
440    // `CompilePolicy::ids_as_strings` l'emet en CHAINE — et
441    // `save_working_context` la refusait, alors que c'est precisement la forme
442    // qu'un client a en main lorsqu'il resoumet une `SourceReference` recue
443    // d'un contexte compile.
444    /// The memory backing this source, when it came from recall (US-002).
445    /// Accepts a JSON number OR a decimal string on input, exactly like
446    /// `fragment_id` just above.
447    #[serde(
448        default,
449        skip_serializing_if = "Option::is_none",
450        deserialize_with = "super::wire::deserialize_optional_id"
451    )]
452    pub memory_id: Option<u64>,
453}
454
455/// A not-emitted fragment the caller can fetch back on demand.
456#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
457#[schemars(transform = crate::schema::strip_int_formats)]
458pub struct RetrievalHandle {
459    /// Recoverable address of the original content (`ctx://source/<id>`).
460    pub handle: String,
461    /// The fragment behind the handle.
462    pub fragment_id: u64,
463    /// Estimated token cost of re-injecting the full original.
464    pub estimated_tokens: u64,
465}
466
467/// The auditable record of what happened to one fragment and why.
468#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
469#[schemars(transform = crate::schema::strip_int_formats)]
470pub struct ContextDecision {
471    /// The fragment this decision is about (caller id, or content-derived).
472    pub fragment_id: u64,
473    /// Content hash of the *original* fragment text (FNV-1a 64, the crate's
474    /// [`stable id`](super::fragment_id)) — lets an auditor prove which exact
475    /// bytes the decision covered even when the caller supplied its own id.
476    pub content_hash: u64,
477    /// What was done.
478    pub action: ContextAction,
479    /// The stable id of the rule that decided (e.g. `"preserve.code_fence"`).
480    pub rule_id: String,
481    /// Lexical relevance of the fragment to the request query, in `[0, 1]`.
482    pub relevance: f32,
483    /// Fidelity risk this single decision contributes.
484    pub risk: FidelityRisk,
485    /// Human-readable explanation of the decision.
486    pub reason: String,
487    /// The memory backing this fragment, when it came from recall (US-002).
488    #[serde(default, skip_serializing_if = "Option::is_none")]
489    pub memory_id: Option<u64>,
490    /// Recoverable address of the original content, when not fully emitted.
491    #[serde(default, skip_serializing_if = "Option::is_none")]
492    pub handle: Option<String>,
493}
494
495/// A mechanical heads-up over one decision, surfaced in
496/// [`CompiledContext::warnings`] so a caller can check "was anything
497/// relevant cut?" without scanning every entry of `decisions` by hand
498/// (V2a-2 quick win). Only [`ContextAction::Retrieve`] decisions at or
499/// above the relevance threshold qualify.
500///
501/// **An empty list is not a clean bill of health** (#1703 DC-4). Several
502/// real losses never warn: a [`ContextAction::Preserve`] the packer could
503/// only fit partially, an [`ContextAction::Abstract`], and two of
504/// `dup_verdict`'s [`ContextAction::Drop`] shapes — a media duplicate whose
505/// caption diverges from its twin's, and a duplicate whose twin was itself
506/// not fully emitted. Both say so in their own reason strings. `decisions`
507/// remains the exhaustive record; this list is a low-noise shortcut over it,
508/// not a substitute for it.
509#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
510#[schemars(transform = crate::schema::strip_int_formats)]
511pub struct ContextWarning {
512    /// The fragment this warning is about.
513    pub fragment_id: u64,
514    /// What happened to it (always [`ContextAction::Retrieve`] today).
515    pub action: ContextAction,
516    /// Lexical relevance to the request query, in `[0, 1]` — the same value
517    /// as the matching `decisions` entry.
518    pub relevance: f32,
519    /// The matching `decisions` entry's `reason`, copied verbatim.
520    pub reason: String,
521}
522
523/// The compiler's output: the assembled context plus its full audit trail.
524#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
525#[schemars(transform = crate::schema::strip_int_formats)]
526pub struct CompiledContext {
527    /// The assembled context, ready to inject into a prompt.
528    pub content: String,
529    /// The output split into ordered blocks (cache prefix first). Emptied by
530    /// [`CompilePolicy::slim_response`].
531    pub sections: Vec<CompiledSection>,
532    /// One decision per input fragment (duplicates included). Emptied by
533    /// [`CompilePolicy::slim_response`].
534    pub decisions: Vec<ContextDecision>,
535    /// One source pointer per distinct fragment.
536    pub sources: Vec<SourceReference>,
537    /// Handles for the fragments that were externalized, not emitted.
538    pub retrieval_handles: Vec<RetrievalHandle>,
539    /// Token (and optional cost) savings of this compilation.
540    pub insights: CompilationInsights,
541    /// Overall fidelity risk (the max over all decisions).
542    pub risk: FidelityRisk,
543    /// Mechanical, low-noise heads-up over `decisions` (V2a-2 quick win):
544    /// every externalized fragment relevant enough to the query that a
545    /// caller should double-check it was not needed. `#[serde(default)]` so
546    /// a pre-0.10.0 caller reading an older stored/replayed response still
547    /// deserializes (defaults to empty).
548    #[serde(default)]
549    pub warnings: Vec<ContextWarning>,
550}
551
552/// One asserted fact inside a [`WorkingContext`].
553#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
554pub struct ContextFact {
555    /// The fact text.
556    pub text: String,
557    /// Where the fact came from, when known.
558    #[serde(default, skip_serializing_if = "Option::is_none")]
559    pub source: Option<SourceReference>,
560}
561
562/// A lightweight pointer to a past [`ContextDecision`].
563#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
564#[schemars(transform = crate::schema::strip_int_formats)]
565pub struct ContextDecisionRef {
566    /// The fragment the decision was about. Accepts a JSON number OR a
567    /// decimal string on input, for the same reason as
568    /// [`SourceReference::fragment_id`].
569    #[serde(deserialize_with = "crate::model::deserialize_id")]
570    pub fragment_id: u64,
571    /// The rule that decided.
572    pub rule_id: String,
573}
574
575/// The distilled working state of an agent session — small enough to carry
576/// across sessions, structured enough to resume from. Persisted and reloaded
577/// by the memory bridge (US-002) under `type = working_context` metadata.
578#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
579pub struct WorkingContext {
580    /// What the session is trying to achieve.
581    #[serde(default, skip_serializing_if = "Option::is_none")]
582    pub goal: Option<String>,
583    /// Constraints currently in force (never compressed away).
584    #[serde(default)]
585    pub active_constraints: Vec<ContextFact>,
586    /// Facts that were verified, with their sources.
587    #[serde(default)]
588    pub verified_facts: Vec<ContextFact>,
589    /// Hypotheses still open.
590    #[serde(default)]
591    pub open_hypotheses: Vec<ContextFact>,
592    /// Decisions taken so far.
593    #[serde(default)]
594    pub decisions: Vec<ContextDecisionRef>,
595    /// Exact evidence the session relies on (verbatim, addressable).
596    #[serde(default)]
597    pub exact_evidence: Vec<SourceReference>,
598    /// Actions still to do.
599    #[serde(default)]
600    pub pending_actions: Vec<String>,
601}
602
603impl WorkingContext {
604    /// Whether this working state records nothing at all: no goal (or a blank
605    /// one, which says no more than an absent one) and every list empty.
606    ///
607    /// Saving is an idempotent upsert, so an empty state would *replace* —
608    /// that is, destroy — whatever a previous save stored under the same
609    /// project and session. [`crate::MemoryService::save_working_context`]
610    /// refuses one for exactly that reason (issue #1654).
611    #[must_use]
612    pub fn is_empty(&self) -> bool {
613        self.goal.as_ref().is_none_or(|goal| goal.trim().is_empty())
614            && self.active_constraints.is_empty()
615            && self.verified_facts.is_empty()
616            && self.open_hypotheses.is_empty()
617            && self.decisions.is_empty()
618            && self.exact_evidence.is_empty()
619            && self.pending_actions.is_empty()
620    }
621}
622
623/// What a working-context lookup returns, on every surface: the MCP
624/// `load_working_context` tool AND the Node/Python/WASM bindings.
625///
626/// An envelope (not a bare `Option<WorkingContext>`): the MCP spec requires
627/// the output schema's root to be an object, so a nullable root is rejected
628/// by rmcp.
629///
630/// It lives here — in the shared model — rather than in the `mcp` module
631/// because the `mcp` module is a Cargo feature the bindings do not enable:
632/// a type declared there is unreachable from them, and each binding would
633/// have to re-declare the envelope AND re-derive its two policy rules ("list
634/// on a hit too", "never re-emit the requested session"). Four copies of a
635/// rule is four chances for it to diverge in silence. Built once, by
636/// [`MemoryService::resume_working_context`](crate::MemoryService::resume_working_context).
637#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
638#[schemars(transform = crate::schema::strip_int_formats)]
639pub struct LoadedWorkingContext {
640    /// `true` when a working context was found under this exact project +
641    /// session. Wire-additive alongside `working` (added V2a-1): a client
642    /// that only reads `working` sees no change.
643    pub found: bool,
644    /// The previously saved working context, or `null` when nothing was ever
645    /// saved under that project + session (a fresh start, not an error).
646    pub working: Option<WorkingContext>,
647    /// The OTHER sessions saved under this SAME project (never the requested
648    /// one) — helps recover from a typo in `session` instead of silently
649    /// starting fresh (e.g. `"task-1234"` saved, `"task-1235"` requested by
650    /// mistake). Populated on a hit as well as on a miss: a typo that lands
651    /// on another real session is the case the caller can least detect on its
652    /// own. Empty only when the project has no other session.
653    #[serde(default)]
654    pub other_sessions: Vec<String>,
655}
656
657/// One session recorded in a project's working-context index (V2a-1's
658/// `list_working_contexts` quick win).
659#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
660pub struct WorkingContextSession {
661    /// The session id, as passed to `save_working_context`.
662    pub session: String,
663    /// Unix seconds this session was last saved — updated on every
664    /// `save_working_context` call under this project + session, not just
665    /// the first (a resave never duplicates the entry).
666    pub saved_at: u64,
667}
668
669/// The per-project index [`save_working_context`](crate::MemoryService::save_working_context)
670/// maintains so [`list_working_contexts`](crate::MemoryService::list_working_contexts)
671/// never has to scan the whole store: one system fact per project, appended
672/// (or refreshed) on every save. The REJECTED alternative was an approximate
673/// `query_filtered` scan over working-context facts (capped at
674/// `MAX_RECALL_LIMIT`, imprecise) — this index is exact and O(1) to read.
675#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
676pub struct WorkingContextIndex {
677    /// Every session ever saved under this project.
678    #[serde(default)]
679    pub sessions: Vec<WorkingContextSession>,
680}