Skip to main content

lean_ctx/core/
contracts.rs

1use std::collections::BTreeMap;
2
3// Machine-verified contract versions.
4pub const MCP_MANIFEST_SCHEMA_VERSION: u32 = 1;
5pub const CONTEXT_PROOF_V1_SCHEMA_VERSION: u32 = 1;
6pub const CONTEXT_IR_V1_SCHEMA_VERSION: u32 = 1;
7pub const INTENT_ROUTE_V1_SCHEMA_VERSION: u32 = 1;
8pub const DEGRADATION_POLICY_V1_SCHEMA_VERSION: u32 = 1;
9pub const WORKFLOW_EVIDENCE_LEDGER_V1_SCHEMA_VERSION: u32 = 1;
10pub const AUTONOMY_DRIVERS_V1_SCHEMA_VERSION: u32 = 1;
11pub const TOKENIZER_TRANSLATION_DRIVER_V1_SCHEMA_VERSION: u32 = 1;
12pub const ATTENTION_LAYOUT_DRIVER_V1_SCHEMA_VERSION: u32 = 1;
13pub const VERIFICATION_OBSERVABILITY_V1_SCHEMA_VERSION: u32 = 1;
14pub const HANDOFF_LEDGER_V1_SCHEMA_VERSION: u32 = 1;
15pub const HANDOFF_TRANSFER_BUNDLE_V1_SCHEMA_VERSION: u32 = 1;
16pub const CCP_SESSION_BUNDLE_V1_SCHEMA_VERSION: u32 = 1;
17pub const KNOWLEDGE_POLICY_V1_SCHEMA_VERSION: u32 = 1;
18pub const GRAPH_REPRODUCIBILITY_V1_SCHEMA_VERSION: u32 = 1;
19pub const A2A_SNAPSHOT_V1_SCHEMA_VERSION: u32 = 1;
20pub const MEMORY_BOUNDARY_V1_SCHEMA_VERSION: u32 = 1;
21pub const GOTCHAS_REMINDERS_V1_SCHEMA_VERSION: u32 = 1;
22pub const PROVIDER_FRAMEWORK_V1_SCHEMA_VERSION: u32 = 1;
23pub const CONTEXT_PACKAGE_V1_SCHEMA_VERSION: u32 = 1;
24pub const CONTEXT_PACKAGE_V2_SCHEMA_VERSION: u32 = 2;
25
26pub const PACKAGE_EXTENSION: &str = "ctxpkg";
27pub const LEGACY_PACKAGE_EXTENSION: &str = "lctxpkg";
28pub const MAX_PACKAGE_FILE_BYTES: u64 = 10 * 1024 * 1024; // 10 MB
29
30pub fn is_package_file(path: &std::path::Path) -> bool {
31    path.extension()
32        .and_then(|e| e.to_str())
33        .is_some_and(|ext| ext == PACKAGE_EXTENSION || ext == LEGACY_PACKAGE_EXTENSION)
34}
35
36pub fn default_package_filename(name: &str, version: &str) -> String {
37    format!("{name}-{version}.{PACKAGE_EXTENSION}")
38}
39
40// Documentation-level contracts (do not have a schema field in payloads).
41pub const HTTP_MCP_CONTRACT_VERSION: u32 = 1;
42pub const TEAM_SERVER_CONTRACT_VERSION: u32 = 1;
43pub const CAPABILITIES_CONTRACT_VERSION: u32 = 1;
44
45/// Stability classification of a contract document (GL #394).
46///
47/// The classification is normative — `tests/contracts_frozen.rs` enforces it:
48/// * `Frozen` — the normative surface is immutable. Any change to the doc file
49///   fails CI; semantic evolution requires a new `-v2.md` file (the v1 file
50///   stays in place for existing integrations).
51/// * `Stable` — additive evolution allowed (new optional fields, new sections);
52///   breaking changes still require a version bump per CONTRACTS.md rules.
53/// * `Experimental` — may change or disappear without notice; not covered by
54///   the deprecation policy.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum ContractStatus {
57    Frozen,
58    Stable,
59    Experimental,
60}
61
62impl ContractStatus {
63    pub fn as_str(self) -> &'static str {
64        match self {
65            ContractStatus::Frozen => "frozen",
66            ContractStatus::Stable => "stable",
67            ContractStatus::Experimental => "experimental",
68        }
69    }
70}
71
72/// One contract document under `docs/contracts/`, classified for the
73/// stability matrix in CONTRACTS.md and the `/v1/capabilities` response.
74pub struct ContractDoc {
75    /// Short stable identifier (used in capabilities `contract_status`).
76    pub id: &'static str,
77    /// File name inside `docs/contracts/` (the normative artifact).
78    pub doc_file: &'static str,
79    pub version: u32,
80    pub status: ContractStatus,
81}
82
83/// The complete classified inventory of `docs/contracts/*.md` — the single
84/// source of truth for the stability matrix. `tests/contracts_frozen.rs`
85/// asserts that every file in the directory is listed here (no contract can
86/// stay unclassified) and that frozen docs never change.
87pub fn contract_docs() -> Vec<ContractDoc> {
88    use ContractStatus::{Experimental, Frozen, Stable};
89    let doc = |id, doc_file, version, status| ContractDoc {
90        id,
91        doc_file,
92        version,
93        status,
94    };
95    vec![
96        // ── Frozen: externally consumed platform/transport promises ────────
97        doc("http-mcp", "http-mcp-contract-v1.md", 1, Frozen),
98        doc("team-server", "team-server-contract-v1.md", 1, Frozen),
99        doc("context-ir", "context-ir-v1.md", 1, Frozen),
100        doc(
101            "local-free-invariant",
102            "local-free-invariant-v1.md",
103            1,
104            Frozen,
105        ),
106        doc(
107            "oss-plane-separation",
108            "oss-plane-separation-v1.md",
109            1,
110            Frozen,
111        ),
112        doc("billing-plane", "billing-plane-v1.md", 1, Frozen),
113        doc("wasm-abi", "wasm-abi-v1.md", 1, Frozen),
114        // ── Stable: additive evolution allowed ──────────────────────────────
115        // capabilities is additive BY DESIGN: its drift test binds the doc's
116        // key list to TOP_LEVEL_KEYS, so the doc grows with every new key —
117        // freezing the file would contradict its own contract.
118        doc("capabilities", "capabilities-contract-v1.md", 1, Stable),
119        doc("billing-plane-v2", "billing-plane-v2.md", 2, Stable),
120        // v2 = v1 + storageQuotaBytes/roiWebhookUrl (GL #387/#388); v1 stays frozen.
121        doc("billing-plane-v3", "billing-plane-v3.md", 3, Stable),
122        // v3 = v1 + business plan + sso_oidc entitlement (GL #460/#533); additive.
123        doc("evidence-bundle", "evidence-bundle-v1.md", 1, Stable),
124        // Offline-verifiable audit evidence ZIP (GL #425, H3 Epic A).
125        doc("team-server-v2", "team-server-contract-v2.md", 2, Stable),
126        doc("a2a", "a2a-contract-v1.md", 1, Stable),
127        doc(
128            "attention-layout-driver",
129            "attention-layout-driver-v1.md",
130            1,
131            Stable,
132        ),
133        doc("autonomy-drivers", "autonomy-drivers-v1.md", 1, Stable),
134        doc("ccp-session-bundle", "ccp-session-bundle-v1.md", 1, Stable),
135        doc("conformance", "conformance-v1.md", 1, Stable),
136        doc("degradation-policy", "degradation-policy-v1.md", 1, Stable),
137        doc("extension-trust", "extension-trust-v1.md", 1, Stable),
138        doc("extractors", "extractors-v1.md", 1, Stable),
139        doc(
140            "gotchas-reminders",
141            "gotchas-reminders-contract-v1.md",
142            1,
143            Stable,
144        ),
145        doc(
146            "graph-reproducibility",
147            "graph-reproducibility-contract-v1.md",
148            1,
149            Stable,
150        ),
151        doc(
152            "handoff-transfer-bundle",
153            "handoff-transfer-bundle-v1.md",
154            1,
155            Stable,
156        ),
157        doc("intent-route", "intent-route-v1.md", 1, Stable),
158        doc(
159            "knowledge-policy",
160            "knowledge-policy-contract-v1.md",
161            1,
162            Stable,
163        ),
164        doc(
165            "memory-boundary",
166            "memory-boundary-contract-v1.md",
167            1,
168            Stable,
169        ),
170        doc("persona-spec", "persona-spec-v1.md", 1, Stable),
171        doc(
172            "provider-framework",
173            "provider-framework-contract-v1.md",
174            1,
175            Stable,
176        ),
177        doc(
178            "tokenizer-translation-driver",
179            "tokenizer-translation-driver-v1.md",
180            1,
181            Stable,
182        ),
183        doc(
184            "workflow-evidence-ledger",
185            "workflow-evidence-ledger-v1.md",
186            1,
187            Stable,
188        ),
189        doc("wrapped-permalink", "wrapped-permalink-v1.md", 1, Stable),
190        // ── Experimental: may change without notice ─────────────────────────
191        doc(
192            "hosted-personal-index",
193            "hosted-personal-index-v1.md",
194            1,
195            Experimental,
196        ),
197        doc(
198            "personal-cloud-encryption",
199            "personal-cloud-encryption-v1.md",
200            1,
201            Experimental,
202        ),
203        // 2026-06 org/cloud-plane wave — fresh surfaces, not yet consumed by
204        // external integrations; promote to Stable deliberately, not by default.
205        doc(
206            "context-policy-packs",
207            "context-policy-packs-v1.md",
208            1,
209            Experimental,
210        ),
211        doc("device-overview", "device-overview-v1.md", 1, Experimental),
212        doc("email-digest", "email-digest-v1.md", 1, Experimental),
213        doc("org-audit-log", "org-audit-log-v1.md", 1, Experimental),
214        doc("org-sso-oidc", "org-sso-oidc-v1.md", 1, Experimental),
215        // Quality loop (GL #494): edit-failure feedback into mode selection.
216        doc("quality-loop", "quality-loop-v1.md", 1, Experimental),
217        // Hosted ctxpkg registry (GL #406): fresh server surface.
218        doc("ctxpkg-registry", "ctxpkg-registry-v1.md", 1, Experimental),
219        doc(
220            "team-invite-links",
221            "team-invite-links-v1.md",
222            1,
223            Experimental,
224        ),
225    ]
226}
227
228/// Contract-id → stability status, exported through `/v1/capabilities` so
229/// clients can verify compatibility before relying on a surface (GL #394).
230pub fn status_kv() -> BTreeMap<&'static str, &'static str> {
231    contract_docs()
232        .into_iter()
233        .map(|d| (d.id, d.status.as_str()))
234        .collect()
235}
236
237pub fn versions_kv() -> BTreeMap<&'static str, u32> {
238    BTreeMap::from([
239        (
240            "leanctx.contract.mcp_manifest.schema_version",
241            MCP_MANIFEST_SCHEMA_VERSION,
242        ),
243        (
244            "leanctx.contract.context_proof_v1.schema_version",
245            CONTEXT_PROOF_V1_SCHEMA_VERSION,
246        ),
247        (
248            "leanctx.contract.context_ir_v1.schema_version",
249            CONTEXT_IR_V1_SCHEMA_VERSION,
250        ),
251        (
252            "leanctx.contract.intent_route_v1.schema_version",
253            INTENT_ROUTE_V1_SCHEMA_VERSION,
254        ),
255        (
256            "leanctx.contract.degradation_policy_v1.schema_version",
257            DEGRADATION_POLICY_V1_SCHEMA_VERSION,
258        ),
259        (
260            "leanctx.contract.workflow_evidence_ledger_v1.schema_version",
261            WORKFLOW_EVIDENCE_LEDGER_V1_SCHEMA_VERSION,
262        ),
263        (
264            "leanctx.contract.autonomy_drivers_v1.schema_version",
265            AUTONOMY_DRIVERS_V1_SCHEMA_VERSION,
266        ),
267        (
268            "leanctx.contract.tokenizer_translation_driver_v1.schema_version",
269            TOKENIZER_TRANSLATION_DRIVER_V1_SCHEMA_VERSION,
270        ),
271        (
272            "leanctx.contract.attention_layout_driver_v1.schema_version",
273            ATTENTION_LAYOUT_DRIVER_V1_SCHEMA_VERSION,
274        ),
275        (
276            "leanctx.contract.verification_observability_v1.schema_version",
277            VERIFICATION_OBSERVABILITY_V1_SCHEMA_VERSION,
278        ),
279        (
280            "leanctx.contract.handoff_ledger_v1.schema_version",
281            HANDOFF_LEDGER_V1_SCHEMA_VERSION,
282        ),
283        (
284            "leanctx.contract.handoff_transfer_bundle_v1.schema_version",
285            HANDOFF_TRANSFER_BUNDLE_V1_SCHEMA_VERSION,
286        ),
287        (
288            "leanctx.contract.ccp_session_bundle_v1.schema_version",
289            CCP_SESSION_BUNDLE_V1_SCHEMA_VERSION,
290        ),
291        (
292            "leanctx.contract.knowledge_policy_v1.schema_version",
293            KNOWLEDGE_POLICY_V1_SCHEMA_VERSION,
294        ),
295        (
296            "leanctx.contract.graph_reproducibility_v1.schema_version",
297            GRAPH_REPRODUCIBILITY_V1_SCHEMA_VERSION,
298        ),
299        (
300            "leanctx.contract.a2a_snapshot_v1.schema_version",
301            A2A_SNAPSHOT_V1_SCHEMA_VERSION,
302        ),
303        (
304            "leanctx.contract.memory_boundary_v1.schema_version",
305            MEMORY_BOUNDARY_V1_SCHEMA_VERSION,
306        ),
307        (
308            "leanctx.contract.gotchas_reminders_v1.schema_version",
309            GOTCHAS_REMINDERS_V1_SCHEMA_VERSION,
310        ),
311        (
312            "leanctx.contract.provider_framework_v1.schema_version",
313            PROVIDER_FRAMEWORK_V1_SCHEMA_VERSION,
314        ),
315        (
316            "leanctx.contract.context_package_v1.schema_version",
317            CONTEXT_PACKAGE_V1_SCHEMA_VERSION,
318        ),
319        (
320            "leanctx.contract.context_package_v2.schema_version",
321            CONTEXT_PACKAGE_V2_SCHEMA_VERSION,
322        ),
323        (
324            "leanctx.contract.http_mcp.contract_version",
325            HTTP_MCP_CONTRACT_VERSION,
326        ),
327        (
328            "leanctx.contract.team_server.contract_version",
329            TEAM_SERVER_CONTRACT_VERSION,
330        ),
331        (
332            "leanctx.contract.capabilities.contract_version",
333            CAPABILITIES_CONTRACT_VERSION,
334        ),
335    ])
336}
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341
342    #[test]
343    fn contract_docs_have_unique_ids_and_files() {
344        let docs = contract_docs();
345        let mut ids: Vec<_> = docs.iter().map(|d| d.id).collect();
346        let mut files: Vec<_> = docs.iter().map(|d| d.doc_file).collect();
347        ids.sort_unstable();
348        files.sort_unstable();
349        let unique_ids: std::collections::BTreeSet<_> = ids.iter().collect();
350        let unique_files: std::collections::BTreeSet<_> = files.iter().collect();
351        assert_eq!(unique_ids.len(), docs.len(), "duplicate contract id");
352        assert_eq!(unique_files.len(), docs.len(), "duplicate doc file");
353    }
354
355    #[test]
356    fn frozen_set_covers_the_platform_promises() {
357        // The freeze (GL #394) is only meaningful if the externally consumed
358        // surfaces are actually in it. Removing one of these from `Frozen`
359        // is itself a breaking policy change.
360        let docs = contract_docs();
361        for id in [
362            "http-mcp",
363            "team-server",
364            "context-ir",
365            "local-free-invariant",
366            "oss-plane-separation",
367            "billing-plane",
368            "wasm-abi",
369        ] {
370            let entry = docs.iter().find(|d| d.id == id).expect("listed");
371            assert_eq!(
372                entry.status,
373                ContractStatus::Frozen,
374                "{id} must stay frozen"
375            );
376        }
377    }
378
379    #[test]
380    fn status_kv_matches_docs() {
381        let kv = status_kv();
382        assert_eq!(kv.len(), contract_docs().len());
383        assert_eq!(kv["http-mcp"], "frozen");
384        assert_eq!(kv["hosted-personal-index"], "experimental");
385        assert_eq!(kv["personal-cloud-encryption"], "experimental");
386    }
387
388    #[test]
389    fn doc_files_follow_versioned_naming() {
390        // v1→v2 rule: every doc file carries its version suffix so a breaking
391        // change lands as a NEW file instead of mutating the old one.
392        for d in contract_docs() {
393            assert!(
394                d.doc_file.ends_with(&format!("-v{}.md", d.version)),
395                "{} must end in -v{}.md",
396                d.doc_file,
397                d.version
398            );
399        }
400    }
401}