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;
25pub const CONTEXT_SNAPSHOT_V1_SCHEMA_VERSION: u32 = 1;
26
27pub const PACKAGE_EXTENSION: &str = "ctxpkg";
28pub const LEGACY_PACKAGE_EXTENSION: &str = "lctxpkg";
29pub const MAX_PACKAGE_FILE_BYTES: u64 = 10 * 1024 * 1024; // 10 MB
30
31pub fn is_package_file(path: &std::path::Path) -> bool {
32    path.extension()
33        .and_then(|e| e.to_str())
34        .is_some_and(|ext| ext == PACKAGE_EXTENSION || ext == LEGACY_PACKAGE_EXTENSION)
35}
36
37pub fn default_package_filename(name: &str, version: &str) -> String {
38    format!("{name}-{version}.{PACKAGE_EXTENSION}")
39}
40
41// Documentation-level contracts (do not have a schema field in payloads).
42pub const HTTP_MCP_CONTRACT_VERSION: u32 = 1;
43pub const TEAM_SERVER_CONTRACT_VERSION: u32 = 1;
44pub const CAPABILITIES_CONTRACT_VERSION: u32 = 1;
45
46/// Stability classification of a contract document (GL #394).
47///
48/// The classification is normative — `tests/contracts_frozen.rs` enforces it:
49/// * `Frozen` — the normative surface is immutable. Any change to the doc file
50///   fails CI; semantic evolution requires a new `-v2.md` file (the v1 file
51///   stays in place for existing integrations).
52/// * `Stable` — additive evolution allowed (new optional fields, new sections);
53///   breaking changes still require a version bump per CONTRACTS.md rules.
54/// * `Experimental` — may change or disappear without notice; not covered by
55///   the deprecation policy.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum ContractStatus {
58    Frozen,
59    Stable,
60    Experimental,
61}
62
63impl ContractStatus {
64    pub fn as_str(self) -> &'static str {
65        match self {
66            ContractStatus::Frozen => "frozen",
67            ContractStatus::Stable => "stable",
68            ContractStatus::Experimental => "experimental",
69        }
70    }
71}
72
73/// One contract document under `docs/contracts/`, classified for the
74/// stability matrix in CONTRACTS.md and the `/v1/capabilities` response.
75pub struct ContractDoc {
76    /// Short stable identifier (used in capabilities `contract_status`).
77    pub id: &'static str,
78    /// File name inside `docs/contracts/` (the normative artifact).
79    pub doc_file: &'static str,
80    pub version: u32,
81    pub status: ContractStatus,
82}
83
84/// The complete classified inventory of `docs/contracts/*.md` — the single
85/// source of truth for the stability matrix. `tests/contracts_frozen.rs`
86/// asserts that every file in the directory is listed here (no contract can
87/// stay unclassified) and that frozen docs never change.
88pub fn contract_docs() -> Vec<ContractDoc> {
89    use ContractStatus::{Experimental, Frozen, Stable};
90    let doc = |id, doc_file, version, status| ContractDoc {
91        id,
92        doc_file,
93        version,
94        status,
95    };
96    vec![
97        // ── Frozen: externally consumed platform/transport promises ────────
98        doc("http-mcp", "http-mcp-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("wasm-abi", "wasm-abi-v1.md", 1, Frozen),
113        // Release promotion, offline rollback rehearsal and signing-key
114        // rotation are externally consumed fail-closed supply-chain formats.
115        // Their exact v1 semantics are immutable; evolution requires v2.
116        doc("delivery-manifest", "delivery-manifest-v1.md", 1, Frozen),
117        doc(
118            "deployment-rehearsal",
119            "deployment-rehearsal-v1.md",
120            1,
121            Frozen,
122        ),
123        doc(
124            "release-key-rotation",
125            "release-key-rotation-v1.md",
126            1,
127            Frozen,
128        ),
129        // ── Stable: additive evolution allowed ──────────────────────────────
130        // capabilities is additive BY DESIGN: its drift test binds the doc's
131        // key list to TOP_LEVEL_KEYS, so the doc grows with every new key —
132        // freezing the file would contradict its own contract.
133        doc("capabilities", "capabilities-contract-v1.md", 1, Stable),
134        // v2 = v1 + storageQuotaBytes/roiWebhookUrl (GL #387/#388); v1 stays frozen.
135        // v3 = v1 + sso_oidc entitlement (GL #460/#533); additive. Business merged into Team in v3.9.
136        doc("evidence-bundle", "evidence-bundle-v1.md", 1, Stable),
137        doc("a2a", "a2a-contract-v1.md", 1, Stable),
138        doc(
139            "attention-layout-driver",
140            "attention-layout-driver-v1.md",
141            1,
142            Stable,
143        ),
144        doc("autonomy-drivers", "autonomy-drivers-v1.md", 1, Stable),
145        doc("conformance", "conformance-v1.md", 1, Stable),
146        doc(
147            "ocla-verifier-conformance",
148            "ocla-verifier-conformance-v1.md",
149            1,
150            Stable,
151        ),
152        doc("degradation-policy", "degradation-policy-v1.md", 1, Stable),
153        doc("extension-trust", "extension-trust-v1.md", 1, Stable),
154        doc("extractors", "extractors-v1.md", 1, Stable),
155        doc("contracts-readme", "README.md", 1, Stable),
156        doc("deprecation-policy", "DEPRECATION.md", 1, Stable),
157        doc("audit-schedule", "audit-schedule-v1.md", 1, Stable),
158        doc("branch-protection", "branch-protection-v1.md", 1, Stable),
159        doc(
160            "certification-levels",
161            "certification-levels-v1.md",
162            1,
163            Stable,
164        ),
165        doc("release-integrity", "release-integrity-v1.md", 1, Stable),
166        doc("evidence-bundle-v2", "evidence-bundle-v2.md", 2, Stable),
167        doc(
168            "evidence-bundle-v2-verification",
169            "evidence-bundle-v2-verification-v1.md",
170            1,
171            Stable,
172        ),
173        doc(
174            "public-product-claims",
175            "public-product-claims-v1.md",
176            1,
177            Stable,
178        ),
179        doc(
180            "gotchas-reminders",
181            "gotchas-reminders-contract-v1.md",
182            1,
183            Stable,
184        ),
185        doc(
186            "graph-reproducibility",
187            "graph-reproducibility-contract-v1.md",
188            1,
189            Stable,
190        ),
191        doc(
192            "handoff-transfer-bundle",
193            "handoff-transfer-bundle-v1.md",
194            1,
195            Stable,
196        ),
197        doc("intent-route", "intent-route-v1.md", 1, Stable),
198        doc(
199            "knowledge-policy",
200            "knowledge-policy-contract-v1.md",
201            1,
202            Stable,
203        ),
204        doc(
205            "memory-boundary",
206            "memory-boundary-contract-v1.md",
207            1,
208            Stable,
209        ),
210        doc("persona-spec", "persona-spec-v1.md", 1, Stable),
211        doc(
212            "provider-framework",
213            "provider-framework-contract-v1.md",
214            1,
215            Stable,
216        ),
217        doc(
218            "tokenizer-translation-driver",
219            "tokenizer-translation-driver-v1.md",
220            1,
221            Stable,
222        ),
223        doc(
224            "workflow-evidence-ledger",
225            "workflow-evidence-ledger-v1.md",
226            1,
227            Stable,
228        ),
229        doc("wrapped-permalink", "wrapped-permalink-v1.md", 1, Stable),
230        // Community addon manifest (#858): self-declared stable (v1); the format
231        // evolves additively (new optional fields), so Stable, not Frozen.
232        doc("addon-manifest", "addon-manifest-v1.md", 1, Stable),
233        // ── Experimental: may change without notice ─────────────────────────
234        // W0/W1 token-intelligence foundations are locally verified but do not
235        // yet claim complete hotpath adoption or externally consumed stability.
236        doc(
237            "context-candidate-admission",
238            "context-candidate-admission-v1.md",
239            1,
240            Experimental,
241        ),
242        doc(
243            "multi-agent-efficiency-benchmark",
244            "multi-agent-efficiency-benchmark-v1.md",
245            1,
246            Experimental,
247        ),
248        // The committed artifact is conformance-only; external deployment use
249        // and governed attestor adoption remain deliberately unclaimed.
250        doc(
251            "test-deployment-evidence",
252            "test-deployment-evidence-v1.md",
253            1,
254            Experimental,
255        ),
256        // Local Rust adapter only; external callability, authenticated approval,
257        // and recovery orchestration are deliberately not claimed by v2.
258        doc(
259            "ocla-config-tuning",
260            "ocla-config-tuning-v2.md",
261            2,
262            Experimental,
263        ),
264        doc(
265            "personal-cloud-encryption",
266            "personal-cloud-encryption-v1.md",
267            1,
268            Experimental,
269        ),
270        // 2026-06 org/cloud-plane wave — fresh surfaces, not yet consumed by
271        // external integrations; promote to Stable deliberately, not by default.
272        doc(
273            "context-policy-packs",
274            "context-policy-packs-v1.md",
275            1,
276            Experimental,
277        ),
278        // Quality loop (GL #494): edit-failure feedback into mode selection.
279        doc("quality-loop", "quality-loop-v1.md", 1, Experimental),
280        // Edit metering (GL #1144): anchored-vs-str_replace efficiency channel.
281        doc("edit-metering", "edit-metering-v1.md", 1, Experimental),
282        // Hosted ctxpkg registry (GL #406): fresh server surface.
283        doc("ctxpkg-registry", "ctxpkg-registry-v1.md", 1, Experimental),
284        // Context Time Machine (GL #1022/#1023): git-anchored, signed temporal
285        // snapshot format — fresh surface, evolving additively until stable.
286        doc(
287            "context-snapshot",
288            "context-snapshot-v1.md",
289            1,
290            Experimental,
291        ),
292        doc(
293            "team-invite-links",
294            "team-invite-links-v1.md",
295            1,
296            Experimental,
297        ),
298        doc("pillar-boundaries", "pillar-boundaries-v1.md", 1, Stable),
299        // Logical editor-session telemetry is an additive local-dashboard surface;
300        // keep it experimental until multiple integrations implement the lifecycle.
301        doc(
302            "logical-session-presence",
303            "logical-session-presence-v1.md",
304            1,
305            Experimental,
306        ),
307        doc(
308            "tokenizer-calibration",
309            "tokenizer-calibration-v1.md",
310            1,
311            Experimental,
312        ),
313        doc(
314            "engine-interface-compatibility",
315            "engine-interface-compatibility-v1.md",
316            1,
317            Stable,
318        ),
319        // P2 protocol artifacts: strict canonical surfaces with exact Rust and
320        // schema conformance tests; hashes are pinned in frozen-hashes.json.
321        doc(
322            "invocation-context-binding",
323            "invocation-context-binding-v1.md",
324            1,
325            Frozen,
326        ),
327        doc(
328            "invocation-evidence-manifest",
329            "invocation-evidence-manifest-v1.md",
330            1,
331            Frozen,
332        ),
333        doc("receipt-document", "receipt-document-v1.md", 1, Frozen),
334        doc(
335            "native-engine-context-proof",
336            "native-engine-context-proof-v1.md",
337            1,
338            Experimental,
339        ),
340    ]
341}
342
343/// Contract-id → stability status, exported through `/v1/capabilities` so
344/// clients can verify compatibility before relying on a surface (GL #394).
345pub fn status_kv() -> BTreeMap<&'static str, &'static str> {
346    contract_docs()
347        .into_iter()
348        .map(|d| (d.id, d.status.as_str()))
349        .collect()
350}
351
352pub fn versions_kv() -> BTreeMap<&'static str, u32> {
353    BTreeMap::from([
354        (
355            "leanctx.contract.mcp_manifest.schema_version",
356            MCP_MANIFEST_SCHEMA_VERSION,
357        ),
358        (
359            "leanctx.contract.context_proof_v1.schema_version",
360            CONTEXT_PROOF_V1_SCHEMA_VERSION,
361        ),
362        (
363            "leanctx.contract.context_ir_v1.schema_version",
364            CONTEXT_IR_V1_SCHEMA_VERSION,
365        ),
366        (
367            "leanctx.contract.intent_route_v1.schema_version",
368            INTENT_ROUTE_V1_SCHEMA_VERSION,
369        ),
370        (
371            "leanctx.contract.degradation_policy_v1.schema_version",
372            DEGRADATION_POLICY_V1_SCHEMA_VERSION,
373        ),
374        (
375            "leanctx.contract.workflow_evidence_ledger_v1.schema_version",
376            WORKFLOW_EVIDENCE_LEDGER_V1_SCHEMA_VERSION,
377        ),
378        (
379            "leanctx.contract.autonomy_drivers_v1.schema_version",
380            AUTONOMY_DRIVERS_V1_SCHEMA_VERSION,
381        ),
382        (
383            "leanctx.contract.tokenizer_translation_driver_v1.schema_version",
384            TOKENIZER_TRANSLATION_DRIVER_V1_SCHEMA_VERSION,
385        ),
386        (
387            "leanctx.contract.attention_layout_driver_v1.schema_version",
388            ATTENTION_LAYOUT_DRIVER_V1_SCHEMA_VERSION,
389        ),
390        (
391            "leanctx.contract.verification_observability_v1.schema_version",
392            VERIFICATION_OBSERVABILITY_V1_SCHEMA_VERSION,
393        ),
394        (
395            "leanctx.contract.handoff_ledger_v1.schema_version",
396            HANDOFF_LEDGER_V1_SCHEMA_VERSION,
397        ),
398        (
399            "leanctx.contract.handoff_transfer_bundle_v1.schema_version",
400            HANDOFF_TRANSFER_BUNDLE_V1_SCHEMA_VERSION,
401        ),
402        (
403            "leanctx.contract.ccp_session_bundle_v1.schema_version",
404            CCP_SESSION_BUNDLE_V1_SCHEMA_VERSION,
405        ),
406        (
407            "leanctx.contract.knowledge_policy_v1.schema_version",
408            KNOWLEDGE_POLICY_V1_SCHEMA_VERSION,
409        ),
410        (
411            "leanctx.contract.graph_reproducibility_v1.schema_version",
412            GRAPH_REPRODUCIBILITY_V1_SCHEMA_VERSION,
413        ),
414        (
415            "leanctx.contract.a2a_snapshot_v1.schema_version",
416            A2A_SNAPSHOT_V1_SCHEMA_VERSION,
417        ),
418        (
419            "leanctx.contract.memory_boundary_v1.schema_version",
420            MEMORY_BOUNDARY_V1_SCHEMA_VERSION,
421        ),
422        (
423            "leanctx.contract.gotchas_reminders_v1.schema_version",
424            GOTCHAS_REMINDERS_V1_SCHEMA_VERSION,
425        ),
426        (
427            "leanctx.contract.provider_framework_v1.schema_version",
428            PROVIDER_FRAMEWORK_V1_SCHEMA_VERSION,
429        ),
430        (
431            "leanctx.contract.context_package_v1.schema_version",
432            CONTEXT_PACKAGE_V1_SCHEMA_VERSION,
433        ),
434        (
435            "leanctx.contract.context_package_v2.schema_version",
436            CONTEXT_PACKAGE_V2_SCHEMA_VERSION,
437        ),
438        (
439            "leanctx.contract.context_snapshot_v1.schema_version",
440            CONTEXT_SNAPSHOT_V1_SCHEMA_VERSION,
441        ),
442        (
443            "leanctx.contract.http_mcp.contract_version",
444            HTTP_MCP_CONTRACT_VERSION,
445        ),
446        (
447            "leanctx.contract.team_server.contract_version",
448            TEAM_SERVER_CONTRACT_VERSION,
449        ),
450        (
451            "leanctx.contract.capabilities.contract_version",
452            CAPABILITIES_CONTRACT_VERSION,
453        ),
454    ])
455}
456
457#[cfg(test)]
458mod tests {
459    use super::*;
460
461    #[test]
462    fn contract_docs_have_unique_ids_and_files() {
463        let docs = contract_docs();
464        let mut ids: Vec<_> = docs.iter().map(|d| d.id).collect();
465        let mut files: Vec<_> = docs.iter().map(|d| d.doc_file).collect();
466        ids.sort_unstable();
467        files.sort_unstable();
468        let unique_ids: std::collections::BTreeSet<_> = ids.iter().collect();
469        let unique_files: std::collections::BTreeSet<_> = files.iter().collect();
470        assert_eq!(unique_ids.len(), docs.len(), "duplicate contract id");
471        assert_eq!(unique_files.len(), docs.len(), "duplicate doc file");
472    }
473
474    #[test]
475    fn frozen_set_covers_the_platform_promises() {
476        // The freeze (GL #394) is only meaningful if the externally consumed
477        // surfaces are actually in it. Removing one of these from `Frozen`
478        // is itself a breaking policy change.
479        let docs = contract_docs();
480        for id in [
481            "http-mcp",
482            "context-ir",
483            "local-free-invariant",
484            "oss-plane-separation",
485            "wasm-abi",
486            "delivery-manifest",
487            "deployment-rehearsal",
488            "release-key-rotation",
489        ] {
490            let entry = docs.iter().find(|d| d.id == id).expect("listed");
491            assert_eq!(
492                entry.status,
493                ContractStatus::Frozen,
494                "{id} must stay frozen"
495            );
496        }
497    }
498
499    #[test]
500    fn status_kv_matches_docs() {
501        let kv = status_kv();
502        assert_eq!(kv.len(), contract_docs().len());
503        assert_eq!(kv["http-mcp"], "frozen");
504        assert_eq!(kv["personal-cloud-encryption"], "experimental");
505        assert_eq!(kv["context-candidate-admission"], "experimental");
506        assert_eq!(kv["multi-agent-efficiency-benchmark"], "experimental");
507        assert_eq!(kv["test-deployment-evidence"], "experimental");
508    }
509
510    #[test]
511    fn doc_files_follow_versioned_naming() {
512        // v1→v2 rule: every doc file carries its version suffix so a breaking
513        // change lands as a NEW file instead of mutating the old one.
514        // Governance metadata (README, DEPRECATION) are exempt.
515        for d in contract_docs() {
516            if d.doc_file == "README.md" || d.doc_file == "DEPRECATION.md" {
517                continue;
518            }
519            assert!(
520                d.doc_file.ends_with(&format!("-v{}.md", d.version)),
521                "{} must end in -v{}.md",
522                d.doc_file,
523                d.version
524            );
525        }
526    }
527}