Skip to main content

lean_ctx/core/
contracts.rs

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