crprotocol 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. crp/__init__.py +126 -0
  2. crp/__main__.py +8 -0
  3. crp/_typing.py +27 -0
  4. crp/_version.py +5 -0
  5. crp/adapters.py +31 -0
  6. crp/advanced/__init__.py +40 -0
  7. crp/advanced/auto_ingest.py +400 -0
  8. crp/advanced/cqs.py +235 -0
  9. crp/advanced/cross_window.py +477 -0
  10. crp/advanced/curator.py +265 -0
  11. crp/advanced/feedback.py +146 -0
  12. crp/advanced/hierarchical.py +211 -0
  13. crp/advanced/meta_learning.py +401 -0
  14. crp/advanced/parallel.py +98 -0
  15. crp/advanced/review_cycle.py +329 -0
  16. crp/advanced/scale_mode.py +129 -0
  17. crp/advanced/source_grounding.py +207 -0
  18. crp/ckf/__init__.py +35 -0
  19. crp/ckf/community.py +377 -0
  20. crp/ckf/fabric.py +445 -0
  21. crp/ckf/gc.py +175 -0
  22. crp/ckf/graph_walk.py +87 -0
  23. crp/ckf/merge.py +133 -0
  24. crp/ckf/pattern_query.py +122 -0
  25. crp/ckf/pubsub.py +128 -0
  26. crp/ckf/semantic.py +207 -0
  27. crp/cli/__init__.py +7 -0
  28. crp/cli/main.py +329 -0
  29. crp/cli/sidecar.py +929 -0
  30. crp/cli/startup.py +272 -0
  31. crp/continuation/__init__.py +103 -0
  32. crp/continuation/completion.py +348 -0
  33. crp/continuation/degradation.py +157 -0
  34. crp/continuation/document_map.py +160 -0
  35. crp/continuation/flow.py +109 -0
  36. crp/continuation/gap.py +419 -0
  37. crp/continuation/manager.py +484 -0
  38. crp/continuation/quality_monitor.py +179 -0
  39. crp/continuation/stitch.py +419 -0
  40. crp/continuation/trigger.py +142 -0
  41. crp/continuation/voice.py +157 -0
  42. crp/core/__init__.py +69 -0
  43. crp/core/batch.py +77 -0
  44. crp/core/circuit_breaker.py +116 -0
  45. crp/core/config.py +377 -0
  46. crp/core/context_tools.py +540 -0
  47. crp/core/dispatch_router.py +3977 -0
  48. crp/core/errors.py +128 -0
  49. crp/core/extraction_facade.py +384 -0
  50. crp/core/facilitator.py +713 -0
  51. crp/core/idempotency.py +215 -0
  52. crp/core/orchestrator.py +1435 -0
  53. crp/core/relay_strategies.py +613 -0
  54. crp/core/security_manager.py +140 -0
  55. crp/core/session.py +134 -0
  56. crp/core/task_intent.py +36 -0
  57. crp/core/window.py +363 -0
  58. crp/envelope/__init__.py +30 -0
  59. crp/envelope/builder.py +288 -0
  60. crp/envelope/decomposer.py +236 -0
  61. crp/envelope/formatter.py +168 -0
  62. crp/envelope/packer.py +211 -0
  63. crp/envelope/reranker.py +209 -0
  64. crp/envelope/scoring.py +310 -0
  65. crp/extraction/__init__.py +45 -0
  66. crp/extraction/complexity.py +96 -0
  67. crp/extraction/contradiction.py +132 -0
  68. crp/extraction/pipeline.py +360 -0
  69. crp/extraction/quality_gate.py +237 -0
  70. crp/extraction/stage1_regex.py +173 -0
  71. crp/extraction/stage2_statistical.py +244 -0
  72. crp/extraction/stage3_gliner.py +210 -0
  73. crp/extraction/stage4_uie.py +183 -0
  74. crp/extraction/stage5_discourse.py +175 -0
  75. crp/extraction/stage6_llm.py +178 -0
  76. crp/extraction/structured_output.py +219 -0
  77. crp/extraction/types.py +299 -0
  78. crp/license_guard.py +722 -0
  79. crp/observability/__init__.py +30 -0
  80. crp/observability/audit.py +118 -0
  81. crp/observability/events.py +233 -0
  82. crp/observability/metrics.py +264 -0
  83. crp/observability/quality.py +135 -0
  84. crp/observability/structured_logging.py +81 -0
  85. crp/observability/telemetry.py +117 -0
  86. crp/provenance/__init__.py +314 -0
  87. crp/provenance/_embeddings.py +97 -0
  88. crp/provenance/_types.py +378 -0
  89. crp/provenance/attribution_scorer.py +252 -0
  90. crp/provenance/claim_detector.py +229 -0
  91. crp/provenance/contradiction_detector.py +243 -0
  92. crp/provenance/distortion_detector.py +397 -0
  93. crp/provenance/entailment_verifier.py +358 -0
  94. crp/provenance/fabrication_detector.py +203 -0
  95. crp/provenance/hallucination_scorer.py +320 -0
  96. crp/provenance/omission_analyzer.py +106 -0
  97. crp/provenance/provenance_chain.py +205 -0
  98. crp/provenance/report_generator.py +440 -0
  99. crp/providers/__init__.py +43 -0
  100. crp/providers/anthropic.py +270 -0
  101. crp/providers/base.py +135 -0
  102. crp/providers/custom.py +63 -0
  103. crp/providers/diagnostic.py +251 -0
  104. crp/providers/llamacpp.py +224 -0
  105. crp/providers/manager.py +139 -0
  106. crp/providers/ollama.py +243 -0
  107. crp/providers/openai.py +628 -0
  108. crp/providers/tokenizers.py +48 -0
  109. crp/py.typed +0 -0
  110. crp/resources/__init__.py +53 -0
  111. crp/resources/adaptive_allocator.py +525 -0
  112. crp/resources/cost_model.py +388 -0
  113. crp/resources/overhead_manager.py +217 -0
  114. crp/resources/resource_manager.py +262 -0
  115. crp/schemas/__init__.py +20 -0
  116. crp/schemas/cost-estimate.json +33 -0
  117. crp/schemas/crp-error.json +43 -0
  118. crp/schemas/envelope-preview.json +40 -0
  119. crp/schemas/persisted-state-header.json +27 -0
  120. crp/schemas/quality-report.json +94 -0
  121. crp/schemas/session-handle.json +33 -0
  122. crp/schemas/session-status.json +57 -0
  123. crp/schemas/stream-event.json +18 -0
  124. crp/schemas/task-intent.json +42 -0
  125. crp/security/__init__.py +93 -0
  126. crp/security/audit_trail.py +392 -0
  127. crp/security/binding.py +192 -0
  128. crp/security/compliance.py +813 -0
  129. crp/security/consent.py +593 -0
  130. crp/security/embedding_defense.py +161 -0
  131. crp/security/encryption.py +202 -0
  132. crp/security/injection.py +335 -0
  133. crp/security/integrity.py +267 -0
  134. crp/security/privacy.py +662 -0
  135. crp/security/quarantine.py +249 -0
  136. crp/security/rbac.py +221 -0
  137. crp/security/validation.py +164 -0
  138. crp/state/__init__.py +31 -0
  139. crp/state/cold_storage.py +258 -0
  140. crp/state/compaction.py +263 -0
  141. crp/state/critical_state.py +104 -0
  142. crp/state/event_log.py +313 -0
  143. crp/state/fact.py +189 -0
  144. crp/state/serialization.py +189 -0
  145. crp/state/session_cleanup.py +77 -0
  146. crp/state/snapshot.py +290 -0
  147. crp/state/warm_store.py +346 -0
  148. crprotocol-2.0.0.dist-info/METADATA +1295 -0
  149. crprotocol-2.0.0.dist-info/RECORD +153 -0
  150. crprotocol-2.0.0.dist-info/WHEEL +4 -0
  151. crprotocol-2.0.0.dist-info/entry_points.txt +2 -0
  152. crprotocol-2.0.0.dist-info/licenses/LICENSE.md +170 -0
  153. crprotocol-2.0.0.dist-info/licenses/NOTICE +18 -0
@@ -0,0 +1,1295 @@
1
+ Metadata-Version: 2.4
2
+ Name: crprotocol
3
+ Version: 2.0.0
4
+ Summary: Context Relay Protocol — unbounded context, unbounded generation, amplified reasoning for LLMs
5
+ Project-URL: Homepage, https://crprotocol.io
6
+ Project-URL: Documentation, https://crprotocol.io
7
+ Project-URL: Repository, https://github.com/Constantinos-uni/context-relay-protocol
8
+ Project-URL: Issues, https://github.com/Constantinos-uni/context-relay-protocol/issues
9
+ Project-URL: Changelog, https://github.com/Constantinos-uni/context-relay-protocol/blob/main/CHANGELOG.md
10
+ Author: Constantinos Vidiniotis
11
+ License-Expression: LicenseRef-Elastic-2.0
12
+ License-File: LICENSE.md
13
+ License-File: NOTICE
14
+ Keywords: context,crp,llm,protocol,relay
15
+ Classifier: Development Status :: 5 - Production/Stable
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.10
25
+ Provides-Extra: cli
26
+ Requires-Dist: click<9,>=8.0; extra == 'cli'
27
+ Provides-Extra: dev
28
+ Requires-Dist: mypy<2,>=1.5; extra == 'dev'
29
+ Requires-Dist: pip-audit<3,>=2.6; extra == 'dev'
30
+ Requires-Dist: pytest-asyncio<1,>=0.21; extra == 'dev'
31
+ Requires-Dist: pytest-cov<6,>=4.1; extra == 'dev'
32
+ Requires-Dist: pytest<9,>=7.4; extra == 'dev'
33
+ Requires-Dist: ruff<1,>=0.1; extra == 'dev'
34
+ Provides-Extra: full
35
+ Requires-Dist: anthropic<2,>=0.7; extra == 'full'
36
+ Requires-Dist: blake3<2,>=0.3; extra == 'full'
37
+ Requires-Dist: click<9,>=8.0; extra == 'full'
38
+ Requires-Dist: cryptography<44,>=41.0; extra == 'full'
39
+ Requires-Dist: gliner<2,>=0.2; extra == 'full'
40
+ Requires-Dist: hnswlib<1,>=0.7; extra == 'full'
41
+ Requires-Dist: httpx<1,>=0.24; extra == 'full'
42
+ Requires-Dist: igraph<1,>=0.11; extra == 'full'
43
+ Requires-Dist: leidenalg<1,>=0.10; extra == 'full'
44
+ Requires-Dist: openai<3,>=1.0; extra == 'full'
45
+ Requires-Dist: prometheus-client<1,>=0.17; extra == 'full'
46
+ Requires-Dist: sentence-transformers<4,>=2.2; extra == 'full'
47
+ Requires-Dist: spacy<4,>=3.5; extra == 'full'
48
+ Provides-Extra: nlp
49
+ Requires-Dist: gliner<2,>=0.2; extra == 'nlp'
50
+ Requires-Dist: hnswlib<1,>=0.7; extra == 'nlp'
51
+ Requires-Dist: sentence-transformers<4,>=2.2; extra == 'nlp'
52
+ Requires-Dist: spacy<4,>=3.5; extra == 'nlp'
53
+ Provides-Extra: security
54
+ Requires-Dist: blake3<2,>=0.3; extra == 'security'
55
+ Requires-Dist: cryptography<44,>=41.0; extra == 'security'
56
+ Description-Content-Type: text/markdown
57
+
58
+ <!--
59
+ Copyright (c) 2026 Constantinos Vidiniotis. All rights reserved.
60
+ Licensed under the terms described in LICENSE.md in the root of this repository.
61
+ -->
62
+
63
+ <p align="center">
64
+ <img src="media/logo.svg" alt="CRP Logo" width="200" />
65
+ </p>
66
+
67
+ <h1 align="center">Context Relay Protocol (CRP)™</h1>
68
+
69
+ <p align="center">
70
+ <strong>An open protocol for structured context management across LLM invocations.</strong>
71
+ </p>
72
+
73
+ <p align="center">
74
+ <a href="LICENSE.md"><img src="https://img.shields.io/badge/Spec-CC_BY--SA_4.0-blue.svg" alt="Spec: CC BY-SA 4.0"></a>
75
+ <a href="LICENSE.md"><img src="https://img.shields.io/badge/Code-ELv2-orange.svg" alt="Code: Elastic License 2.0"></a>
76
+ <img src="https://img.shields.io/badge/Spec_Version-2.0.0-brightgreen.svg" alt="Spec Version: 2.0.0">
77
+ <img src="https://img.shields.io/badge/RFC_2119-Conformant-orange.svg" alt="RFC 2119">
78
+ <img src="https://img.shields.io/badge/Language_Neutral-JSON_Schema-yellow.svg" alt="Language Neutral">
79
+ <img src="https://img.shields.io/badge/Status-Specification_Complete-green.svg" alt="Status: Specification Complete">
80
+ <a href="https://github.com/Constantinos-uni/context-relay-protocol/actions"><img src="https://img.shields.io/github/actions/workflow/status/Constantinos-uni/context-relay-protocol/ci.yml?label=CI" alt="CI"></a>
81
+ <img src="https://img.shields.io/badge/python-3.10%2B-blue.svg" alt="Python 3.10+">
82
+ <img src="https://img.shields.io/badge/tests-1%2C537-brightgreen.svg" alt="1,537 tests">
83
+ </p>
84
+
85
+ <p align="center">
86
+ <a href="#quick-start">Quick Start</a> •
87
+ <a href="#the-problem">The Problem</a> •
88
+ <a href="#what-crp-does">Solution</a> •
89
+ <a href="#inter-llm-context-sharing-http-sidecar">Inter-LLM Sharing</a> •
90
+ <a href="BENCHMARKS.md">Benchmarks</a> •
91
+ <a href="#specification-documents">Specification</a> •
92
+ <a href="#sdk-status">SDKs</a> •
93
+ <a href="#community">Community</a>
94
+ </p>
95
+
96
+ ---
97
+
98
+ > MCP gives agents tools. A2A lets agents talk. **CRP gives every agent unbounded context, unbounded generation, and amplified reasoning** — the foundation both protocols assume but neither provides.
99
+
100
+ ---
101
+
102
+ ## Table of Contents
103
+
104
+ 1. [The Problem](#the-problem)
105
+ 2. [What CRP Does](#what-crp-does)
106
+ 3. [Key Differentiators](#key-differentiators)
107
+ 4. [Quick Start](#quick-start)
108
+ 5. [How CRP Works](#how-crp-works)
109
+ 6. [Architecture Overview](#architecture-overview)
110
+ 7. [Core Capabilities](#core-capabilities)
111
+ 8. [Inter-LLM Context Sharing (HTTP Sidecar)](#inter-llm-context-sharing-http-sidecar)
112
+ 9. [End-to-End Example: Penetration Test](#end-to-end-example-a-penetration-test)
113
+ 10. [CRP in the AI Stack](#crp-in-the-ai-stack)
114
+ 11. [Extraction Quality](#extraction-quality)
115
+ 12. [Efficiency and Cost](#efficiency-and-cost)
116
+ 13. [Observability and Auditing](#observability-and-auditing)
117
+ 14. [Limitations and Trade-offs](#limitations-and-trade-offs)
118
+ 15. [Why Large Context Windows Are Not Enough](#why-large-context-windows-are-not-enough)
119
+ 16. [Specification Documents](#specification-documents)
120
+ 17. [JSON Schemas](#json-schemas)
121
+ 18. [API Surface](#api-surface)
122
+ 19. [SDK Status](#sdk-status)
123
+ 20. [Comparison with Alternatives](#comparison-with-alternatives)
124
+ 21. [Hardware Requirements](#hardware-requirements)
125
+ 22. [Configuration](#configuration)
126
+ 23. [Use Cases](#use-cases)
127
+ 24. [Roadmap](#roadmap)
128
+ 25. [Contributing](#contributing)
129
+ 26. [Governance](#governance)
130
+ 27. [Security](#security)
131
+ 28. [Community](#community)
132
+ 29. [Built With](#built-with)
133
+ 30. [Intellectual Property & License](#license)
134
+
135
+ ---
136
+
137
+ ## The Problem
138
+
139
+ Every agentic AI system forces its LLM to work inside a single, shared context window. Planning, reasoning, tool calling, analysis, memory, and output generation all compete for the same finite token budget. This creates three compounding failures:
140
+
141
+ | Failure | What Happens | Impact |
142
+ |---------|-------------|--------|
143
+ | **Context Contamination** | Tool output from step 3 dilutes reasoning for step 12 | The LLM "forgets" early discoveries. Later decisions degrade |
144
+ | **Attention Collapse** | At 30K+ tokens, attention spreads thin over irrelevant content | Critical facts in the middle are effectively invisible ([Liu et al., 2023](https://arxiv.org/abs/2307.03172)) |
145
+ | **Hard Ceiling** | When the context window fills, the system truncates or stops | Reports are incomplete. Analysis is shallow. Output is arbitrarily cut short |
146
+
147
+ These aren't edge cases — they happen on **every non-trivial agentic task** and get worse the more capable your agent becomes.
148
+
149
+ ---
150
+
151
+ ## What CRP Does
152
+
153
+ CRP is a **middleware layer** that wraps your existing LLM calls. It does NOT replace your LLM — it **amplifies** it.
154
+
155
+ For every LLM call you already make, CRP:
156
+
157
+ 1. **Builds a better prompt** — adds an envelope of relevant historical facts, source passages, and the LLM's own synthesis alongside your system prompt and task input
158
+ 2. **Calls YOUR LLM** — through your existing provider and infrastructure
159
+ 3. **Returns the raw output unchanged** — exactly what the LLM generated, not a filtered version
160
+ 4. **Observes the output** (read-only) — extracts facts into the knowledge fabric so future windows benefit
161
+ 5. **Carries the LLM's understanding forward** — progressive synthesis evolves across windows
162
+ 6. **Scaffolds reasoning** — decomposes complex tasks into micro-steps for models that can't chain-of-thought natively
163
+
164
+ ```
165
+ WITHOUT CRP WITH CRP
166
+
167
+ One shared window, N dedicated windows,
168
+ everything competing: each pristine:
169
+
170
+ +---------------------------+ +----------+ +----------+ +----------+
171
+ | System prompt | | System | | System | | System |
172
+ | + Tool schemas (10K tok) | | Envelope | | Envelope | | Envelope |
173
+ | + Tool output #1-#3 | | Task | | Task | | Task |
174
+ | + Reasoning history | | | | | | |
175
+ | + Prior conversation | | Full | | Full | | Full |
176
+ | + Current task (buried) | | 128K | | 128K | | 128K |
177
+ +---------------------------+ +----------+ +----------+ +----------+
178
+
179
+ Total capacity: 128K (fixed) Total capacity: N × 128K (unbounded)
180
+ Quality: degrades with length Quality: peak per window (tier-reported)
181
+ Input limit: context window Input limit: unbounded (auto-ingest)
182
+ Output limit: max_output_tokens Output limit: unbounded (continuation)
183
+ ```
184
+
185
+ ---
186
+
187
+ ## Key Differentiators
188
+
189
+ - **Embedded library, not a server** — zero deployment overhead. `pip install crprotocol` and you're running. No Docker, no infrastructure. Optional HTTP sidecar (`crp serve`) for [inter-LLM context sharing](#inter-llm-context-sharing-http-sidecar) — never started automatically
190
+ - **Works with any LLM provider** — auto-detected, 3 fields to configure. Built-in adapters for OpenAI, Anthropic, Ollama, and llama.cpp — plus `CustomProvider` to wrap any LLM in 3 lines
191
+ - **Structured knowledge extraction** — 6-stage graduated pipeline (regex → statistical NLP → GLiNER NER → UIE relations → RST discourse → LLM-assisted relational). Not just text chunking
192
+ - **Contextual Knowledge Fabric (CKF)** — graph-structured knowledge with 4-mode retrieval (graph walk + pattern query + semantic fallback + community summaries), event-sourced history, and cross-session persistence
193
+ - **Unbounded input** — automatically ingests documents larger than any model's context window through structure-aware chunking with protected spans
194
+ - **Unbounded output** — automatic continuation with voice profile preservation, document maps, degradation-triggered re-grounding, and content-type-aware stitching
195
+ - **Honest quality guarantees** — a degradation model, not magic claims. Quality tiers S through D, reported with every dispatch. Extraction recall percentages published per stage
196
+ - **Cross-session knowledge** — sessions build on each other. CKF persists facts, reasoning traces, and graph structure across sessions
197
+ - **Reasoning amplification** — meta-learning scaffolds (ORC + ICML + RTL) enable 2B–7B models to perform multi-step reasoning they cannot do natively
198
+ - **Zero in-window overhead** — CRP operates entirely outside the LLM's context window. No protocol tokens, no function call schemas, no memory management instructions inside the window
199
+ - **Full observability** — per-window metrics, session dashboards, window DAG traceability, telemetry export. Debug "why did it do that?" by tracing decisions through the DAG
200
+
201
+ ---
202
+
203
+ ## Quick Start
204
+
205
+ ### Minimal Integration (3 lines)
206
+
207
+ ```python
208
+ import crp
209
+
210
+ # Auto-detects your LLM from environment (OPENAI_API_KEY, ANTHROPIC_API_KEY, or Ollama)
211
+ client = crp.Client()
212
+ output, report = client.dispatch(
213
+ system_prompt="You are a helpful assistant.",
214
+ task_input="Summarize this document: ..."
215
+ )
216
+ # output = raw LLM output, unmodified
217
+ # report.quality_tier = "S" | "A" | "B" | "C" | "D"
218
+ ```
219
+
220
+ ### Explicit Provider
221
+
222
+ ```python
223
+ from crp import Client
224
+ from crp.providers import OpenAIAdapter
225
+
226
+ client = Client(provider=OpenAIAdapter(model="gpt-4o"))
227
+ output, report = client.dispatch(
228
+ system_prompt="You are a helpful assistant.",
229
+ task_input="Summarize this document: ..."
230
+ )
231
+ ```
232
+
233
+ ### Model Name Shortcut
234
+
235
+ ```python
236
+ import crp
237
+
238
+ # Pass model= for automatic provider detection
239
+ client = crp.Client(model="claude-sonnet-4-20250514") # → AnthropicAdapter
240
+ client = crp.Client(model="gpt-4o") # → OpenAIAdapter
241
+ client = crp.Client(model="llama3.1") # → OllamaAdapter
242
+ ```
243
+
244
+ ### Local Models (Zero-Config)
245
+
246
+ ```python
247
+ from crp import Client
248
+ from crp.providers import OllamaAdapter
249
+
250
+ client = Client(provider=OllamaAdapter()) # Auto-detects localhost:11434
251
+ output, report = client.dispatch(
252
+ system_prompt="You are a security analyst.",
253
+ task_input="Analyze these scan results: ..."
254
+ )
255
+ ```
256
+
257
+ ### llama.cpp / vLLM
258
+
259
+ ```python
260
+ from crp import Client
261
+ from crp.providers import LlamaCppAdapter
262
+
263
+ client = Client(provider=LlamaCppAdapter(server_url="http://localhost:8080"))
264
+ output, report = client.dispatch(system_prompt=system, task_input=user_message)
265
+ ```
266
+
267
+ ### Any Custom Setup
268
+
269
+ ```python
270
+ from crp import Client
271
+ from crp.providers import CustomProvider
272
+
273
+ def my_generate(messages, **kw):
274
+ # Your existing LLM function
275
+ return ("response text", "stop") # (output, finish_reason)
276
+
277
+ client = Client(provider=CustomProvider(
278
+ generate_fn=my_generate,
279
+ count_tokens_fn=lambda text: len(text) // 4,
280
+ context_size=128000,
281
+ ))
282
+ output, report = client.dispatch(system_prompt=system, task_input=user_message)
283
+ ```
284
+
285
+ ### Direct Ingestion (No LLM Window)
286
+
287
+ ```python
288
+ client.ingest(nmap_output) # ~7ms, extraction only — no LLM call
289
+ client.ingest(nikto_output) # Facts go to warm state automatically
290
+ client.ingest(api_response) # Available in next window's envelope
291
+ ```
292
+
293
+ ### LLM Compatibility
294
+
295
+ | API Style | Provider | Examples |
296
+ |-----------|---------|----------|
297
+ | Chat completions | `OpenAIAdapter`, `AnthropicAdapter`, `OllamaAdapter` | OpenAI, Anthropic, Ollama |
298
+ | HTTP completions | `LlamaCppAdapter` | llama.cpp, any OpenAI-compatible HTTP endpoint |
299
+ | Any custom setup | `CustomProvider` | Any function that takes messages → returns (text, reason) |
300
+
301
+ ### Configuration
302
+
303
+ ```bash
304
+ # .env — ALL optional (CRP auto-detects LLM from API keys or local Ollama)
305
+ CRP_ENABLED=true # Master switch (default: enabled)
306
+ CRP_LOG_ENVELOPES=false # Debug logging (default: false)
307
+ CRP_MAX_CONTINUATIONS=50 # Safety limit on continuation windows
308
+ ```
309
+
310
+ ### Async Support
311
+
312
+ ```python
313
+ # Works with FastAPI, asyncio, any async framework
314
+ output, report = await client.async_dispatch("You are helpful.", "Explain CRP.")
315
+ facts_count = await client.async_ingest(text, label="docs")
316
+ async for event in client.async_dispatch_stream("You are helpful.", "Explain CRP."):
317
+ if event.event_type == "token":
318
+ print(event.data, end="")
319
+ await client.async_close()
320
+ ```
321
+
322
+ > **More examples**: See [`examples/`](examples/) for runnable scripts — quickstart, multi-turn, ingestion, streaming, async, and provider selection.
323
+
324
+ ---
325
+
326
+ ## How CRP Works
327
+
328
+ ### Four Core Mechanisms
329
+
330
+ All operate **outside the LLM** — zero protocol tokens inside the model's window.
331
+
332
+ #### 1. Task Isolation
333
+
334
+ Every LLM call gets its own dedicated context window containing: system prompt, context envelope, and task input. Nothing else. CRP does NOT add LLM calls — every `crp.dispatch()` maps 1:1 to calls your application already makes. The only "extra" windows are continuations when output hits the physical limit.
335
+
336
+ #### 2. Context Envelopes + Knowledge Fabric
337
+
338
+ Between windows, an **envelope** carries forward everything the next window needs. Built by **extraction** (not summarization) — atomic facts and relationships are pulled from output using a graduated 6-stage pipeline, stored in the **Contextual Knowledge Fabric (CKF)** — a fact graph with typed edges, event-sourced history, community detection, and multi-mode retrieval:
339
+
340
+ - **Graph Walk** — traverse edges from seed facts (2-hop BFS) to reconstruct the subgraph around the task's focal point
341
+ - **Pattern Query** — content-addressable structured matching inspired by tuple spaces (Gelernter, 1985)
342
+ - **Semantic Fallback** — traditional ANN cosine similarity when graph structure is insufficient
343
+ - **Community Summaries** — Leiden community detection produces topic clusters; summaries provide high-level context
344
+
345
+ Facts are scored by **multi-aspect semantic similarity** with cross-encoder reranking, and packed greedily with dependency-aware graph packing until the window is full.
346
+
347
+ #### 3. Multi-Signal Completion Detection
348
+
349
+ The protocol monitors four signals across windows:
350
+
351
+ | Signal | What It Measures | Dominates For |
352
+ |--------|-----------------|---------------|
353
+ | **Fact Flow** | New facts per token | Entity-rich content |
354
+ | **Structural Flow** | New headings/paragraphs/list items | Structured documents |
355
+ | **Vocabulary Novelty** | New n-grams vs. seen n-grams | Creative/discursive content |
356
+ | **Structural Completion** | Conclusion detection | Summaries and conclusions |
357
+
358
+ Signals are weighted by content type — preventing premature termination of conclusions, summaries, and rhetorical passages that produce few new facts but are genuine content.
359
+
360
+ #### 4. Envelope-Based Continuation
361
+
362
+ When output hits the physical limit, CRP:
363
+
364
+ 1. Incrementally extracts facts from the new window's output — `O(N)` per window, not `O(N²)` accumulated
365
+ 2. Identifies what's missing via multi-level gap analysis
366
+ 3. Builds a continuation envelope with voice profile + document map + structural state for long-chain coherence
367
+ 4. Dispatches a fresh window — the continuation sees extracted essence, not raw overlap
368
+
369
+ ### What CRP Sends to Your LLM
370
+
371
+ ```python
372
+ # You call:
373
+ response = client.dispatch(
374
+ system_prompt="You are a security analyst.",
375
+ task_input="Analyze these nmap results: ..."
376
+ )
377
+
378
+ # CRP constructs and sends to YOUR LLM:
379
+ messages = [
380
+ {"role": "system", "content": "You are a security analyst."}, # UNCHANGED
381
+ {"role": "user", "content": envelope_text + "\n\n" + task_input} # envelope ADDED
382
+ ]
383
+ ```
384
+
385
+ Your system prompt and task input pass through unchanged. The envelope is additional context — historical facts from prior windows, scored by relevance. The LLM doesn't know CRP exists. **Zero protocol overhead inside the window.**
386
+
387
+ ### Output Guarantee
388
+
389
+ `dispatch()` returns the complete, unmodified LLM output. Always. Extraction is a read-only side effect — it never modifies, filters, or summarizes the returned string.
390
+
391
+ ---
392
+
393
+ ## Architecture Overview
394
+
395
+ ```
396
+ +---------------------------------------------------------------------+
397
+ | YOUR APPLICATION |
398
+ | (any code that calls an LLM — agents, pipelines, reports) |
399
+ +---------------------------------------------------------------------+
400
+ |
401
+ | crp.dispatch(system_prompt, task_input)
402
+ v
403
+ +---------------------------------------------------------------------+
404
+ | CRP ORCHESTRATOR |
405
+ | |
406
+ | +-----------------+ +-----------------+ +----------------------+ |
407
+ | | Envelope | | Warm State | | Extraction Pipeline | |
408
+ | | Builder | | Store + Fact | | (Blackboard-Reactive)| |
409
+ | | (multi-aspect | | Graph + Event | | regex → stat → NER → | |
410
+ | | scoring + | | Log | | UIE → discourse → | |
411
+ | | cross-encoder | | (session facts, | | LLM-relational | |
412
+ | | reranking + | | scored + | | (graduated, content- | |
413
+ | | CKF multi-mode | | embedded + | | type-adaptive, | |
414
+ | | retrieval + | | graph edges + | | self-gating) | |
415
+ | | source | | FactEvents) | | | |
416
+ | | grounding) | | | | | |
417
+ | +-----------------+ +-----------------+ +----------------------+ |
418
+ | |
419
+ | +-----------------+ +-----------------+ +----------------------+ |
420
+ | | Multi-Signal | | Continuation | | CKF (Knowledge | |
421
+ | | Completion + | | Manager | | Fabric) | |
422
+ | | Degradation | | (auto-ingest, | | graph walk + | |
423
+ | | Monitor | | gap analysis, | | pattern query + | |
424
+ | | (fact flow + | | stitch, | | semantic fallback + | |
425
+ | | structural + | | voice profile, | | community summary + | |
426
+ | | vocabulary + | | document map, | | pub-sub events + | |
427
+ | | chain degr.) | | re-grounding) | | cross-session graph) | |
428
+ | +-----------------+ +-----------------+ +----------------------+ |
429
+ | |
430
+ | +-----------------+ +-----------------+ +----------------------+ |
431
+ | | Source | | LLM Context | | Meta-Learning | |
432
+ | | Grounding | | Curator | | Engine | |
433
+ | | Engine | | (periodic | | (ORC: orchestrated | |
434
+ | | (original text | | curation | | reasoning chains, | |
435
+ | | passages in | | windows, | | ICML: in-context | |
436
+ | | envelopes, | | progressive | | meta-learning, | |
437
+ | | dual-layer | | understanding, | | RTL: reasoning | |
438
+ | | fact+source) | | LLM synthesis) | | template library) | |
439
+ | +-----------------+ +-----------------+ +----------------------+ |
440
+ +---------------------------------------------------------------------+
441
+ |
442
+ | Standard LLM API call (unchanged)
443
+ v
444
+ +------------------------+
445
+ | LLM (any model) |
446
+ | Local or cloud |
447
+ +------------------------+
448
+ ```
449
+
450
+ ---
451
+
452
+ ## Core Capabilities
453
+
454
+ ### Unbounded Context: Input > Model's Window
455
+
456
+ **Problem**: Your input is 1M tokens but your model has 128K context.
457
+
458
+ CRP's **auto-ingest** handles this transparently:
459
+
460
+ 1. Detects overflow: `system_prompt + task_input + generation_reserve > context_window`
461
+ 2. Structure-aware chunking at natural boundaries with protected spans (code blocks, tables, JSON objects are never split). 500-token overlap with boundary reconciliation
462
+ 3. Extracts facts from each chunk — zero LLM calls for typical content
463
+ 4. Builds envelope with multi-aspect scoring, cross-encoder reranking, and dependency-aware graph packing
464
+ 5. Dispatches with a maximally-saturated context window
465
+
466
+ ```python
467
+ # Transparent — the user doesn't manage chunking
468
+ result = crp.dispatch(
469
+ system_prompt="You are a legal analyst.",
470
+ task_input=million_token_contract # CRP handles the rest
471
+ )
472
+ ```
473
+
474
+ Strictly better than truncation (which loses 87% of 1M input on a 128K model). See [02_CORE_PROTOCOL.md §7.6](specification/02_CORE_PROTOCOL.md) for the honest degradation model.
475
+
476
+ ### Unbounded Generation: Output > Model's Limit
477
+
478
+ **Problem**: Your model outputs 4K tokens per call, but you need 100K.
479
+
480
+ CRP's **continuation loop** handles this automatically:
481
+
482
+ 1. LLM generates → hits output limit (`finish_reason: "length"`)
483
+ 2. CRP incrementally extracts facts from the output — `O(N)` not `O(N²)`
484
+ 3. Runs multi-level gap analysis
485
+ 4. Builds continuation envelope: facts + structural state + remaining items + voice profile + document map
486
+ 5. Dispatches fresh window — full context capacity, no attention degradation
487
+ 6. Stitches outputs with content-type-aware boundary detection, echo detection, heading hierarchy validation
488
+ 7. Periodically runs re-grounding windows that re-extract from accumulated output to correct warm state drift
489
+ 8. Repeats until multi-signal completion detection indicates genuine completion
490
+
491
+ ```python
492
+ result = crp.dispatch(
493
+ system_prompt="Write a comprehensive security report.",
494
+ task_input="All findings here...",
495
+ max_continuations=50 # Optional safety limit
496
+ )
497
+ # result contains the full output, stitched from multiple windows
498
+ ```
499
+
500
+ ### Peak Quality Per Window
501
+
502
+ Every window gets the model's full context capacity. The envelope fills all remaining space with semantically-ranked facts. Fresh KV cache per window eliminates attention degradation. Self-calibrating weights and thresholds require zero configuration.
503
+
504
+ ### Concurrency Model
505
+
506
+ Each `CRPOrchestrator` instance is **single-threaded by design** — one dispatch at a time per session. Different sessions (separate `CRPOrchestrator` instances) are fully isolated and can run concurrently without interference. Each session has its own `WarmStateStore`, `FactGraph`, `WindowDAG`, and event log. To process multiple tasks concurrently, create one orchestrator per task.
507
+
508
+ ---
509
+
510
+ ## Inter-LLM Context Sharing (HTTP Sidecar)
511
+
512
+ > **Optional.** The sidecar is never started automatically. You must explicitly run `crp serve` to enable it.
513
+
514
+ CRP includes an HTTP sidecar that exposes the **full protocol surface** over REST, enabling multiple applications — potentially using different LLMs — to share extracted knowledge without direct LLM-to-LLM communication.
515
+
516
+ ### Why This Matters
517
+
518
+ Application A (Claude) extracts facts about code architecture. Application B (GPT-4) receives those facts via the `/facts/share` endpoint. Both benefit from the other's knowledge — without API key sharing, without prompt injection, without any LLM talking to another LLM. The knowledge flows through CRP's structured extraction layer.
519
+
520
+ This is **not** a chat relay. It is structured, scored, ranked knowledge transfer.
521
+
522
+ ### Quick Start
523
+
524
+ ```bash
525
+ # Start the sidecar (loopback only, no auth — local development)
526
+ crp serve
527
+
528
+ # Start with authentication (recommended)
529
+ crp serve --auth-token "my-secret-token"
530
+
531
+ # Bind to all interfaces (REQUIRES auth token)
532
+ crp serve --bind-all --auth-token "my-secret-token" --port 9470
533
+ ```
534
+
535
+ ### Example: Two LLMs Sharing Knowledge
536
+
537
+ ```bash
538
+ # 1. Create sessions for two different applications
539
+ SESSION_A=$(curl -s -X POST http://localhost:9470/sessions \
540
+ -H "Authorization: Bearer $TOKEN" \
541
+ -H "Content-Type: application/json" \
542
+ -d '{"model": "claude-app", "context_window": 128000}' | python -c "import sys,json; print(json.load(sys.stdin)['session_id'])")
543
+
544
+ SESSION_B=$(curl -s -X POST http://localhost:9470/sessions \
545
+ -H "Authorization: Bearer $TOKEN" \
546
+ -H "Content-Type: application/json" \
547
+ -d '{"model": "gpt4-app", "context_window": 128000}' | python -c "import sys,json; print(json.load(sys.stdin)['session_id'])")
548
+
549
+ # 2. Application A ingests data and dispatches
550
+ curl -X POST http://localhost:9470/sessions/$SESSION_A/ingest \
551
+ -H "Authorization: Bearer $TOKEN" \
552
+ -H "Content-Type: application/json" \
553
+ -d '{"text": "The authentication module uses bcrypt with cost factor 12..."}'
554
+
555
+ curl -X POST http://localhost:9470/sessions/$SESSION_A/dispatch \
556
+ -H "Authorization: Bearer $TOKEN" \
557
+ -H "Content-Type: application/json" \
558
+ -d '{"system_prompt": "You are a security analyst.", "task_input": "Analyze the auth module."}'
559
+
560
+ # 3. Share Application A's knowledge → Application B
561
+ curl -X POST http://localhost:9470/sessions/$SESSION_A/facts/share \
562
+ -H "Authorization: Bearer $TOKEN" \
563
+ -H "Content-Type: application/json" \
564
+ -d '{"target_session_id": "'$SESSION_B'", "min_confidence": 0.5}'
565
+
566
+ # 4. Application B now has A's extracted facts in its warm state.
567
+ # Its next dispatch will include those facts in the envelope.
568
+ curl -X POST http://localhost:9470/sessions/$SESSION_B/dispatch \
569
+ -H "Authorization: Bearer $TOKEN" \
570
+ -H "Content-Type: application/json" \
571
+ -d '{"system_prompt": "You are a code reviewer.", "task_input": "Review the auth module for best practices."}'
572
+ # → GPT-4 now sees Claude's extracted security facts in its context envelope
573
+ ```
574
+
575
+ ### Full Endpoint Reference
576
+
577
+ **Session Lifecycle**
578
+
579
+ | Method | Endpoint | Description |
580
+ |--------|----------|-------------|
581
+ | `POST` | `/sessions` | Create a new CRP session |
582
+ | `GET` | `/sessions` | List sessions (owned by caller only) |
583
+ | `GET` | `/sessions/:id/status` | Session metrics and health |
584
+ | `POST` | `/sessions/:id/close` | Close and clean up session |
585
+
586
+ **Dispatch (All 6 Variants)**
587
+
588
+ | Method | Endpoint | Description |
589
+ |--------|----------|-------------|
590
+ | `POST` | `/sessions/:id/dispatch` | Basic dispatch |
591
+ | `POST` | `/sessions/:id/dispatch/tools` | Tool-mediated dispatch |
592
+ | `POST` | `/sessions/:id/dispatch/reflexive` | Reflexive (verify) dispatch |
593
+ | `POST` | `/sessions/:id/dispatch/progressive` | Progressive dispatch |
594
+ | `POST` | `/sessions/:id/dispatch/stream-augmented` | Stream-augmented dispatch |
595
+ | `POST` | `/sessions/:id/dispatch/agentic` | Agentic dispatch |
596
+
597
+ **Knowledge**
598
+
599
+ | Method | Endpoint | Description |
600
+ |--------|----------|-------------|
601
+ | `POST` | `/sessions/:id/ingest` | Ingest raw text (extraction only, no LLM call) |
602
+ | `GET` | `/sessions/:id/facts` | Query extracted facts (with `?limit=` and `?min_confidence=`) |
603
+ | `POST` | `/sessions/:id/facts/share` | **Share facts to another session** (core feature) |
604
+ | `POST` | `/sessions/:id/facts/feedback` | Boost, penalize, or reject a fact |
605
+ | `GET` | `/sessions/:id/envelope` | Preview envelope contents |
606
+
607
+ **Admin**
608
+
609
+ | Method | Endpoint | Description |
610
+ |--------|----------|-------------|
611
+ | `POST` | `/sessions/:id/providers` | Register a fallback provider |
612
+ | `POST` | `/sessions/:id/estimate` | Cost estimation |
613
+ | `GET` | `/health` | Health check (session count, auth status, version) |
614
+
615
+ ### Security Model
616
+
617
+ The sidecar is designed with defense-in-depth. Every layer is enforced on every request.
618
+
619
+ | Layer | Protection | Detail |
620
+ |-------|-----------|--------|
621
+ | **Bind address** | Loopback by default | Binds to `127.0.0.1` — only local processes can connect |
622
+ | **Authentication** | Bearer token | `--auth-token` enables timing-safe (`secrets.compare_digest`) token verification |
623
+ | **Bind-all gate** | `--bind-all` requires auth | Cannot expose to network without `--auth-token` (or explicit `--allow-unauthenticated` override) |
624
+ | **Session ownership** | Token-hash binding | Sessions are bound to the SHA-256 hash of the token that created them. Other tokens get `403 Forbidden` |
625
+ | **Rate limiting** | Per-IP burst window | Default 120 req/60s per IP. Configurable via `--rate-limit`. Uses monotonic clock (immune to clock drift) |
626
+ | **Body size limit** | 10 MB cap | Requests exceeding 10 MB receive `413 Payload Too Large`. Prevents memory exhaustion |
627
+ | **Session cap** | 64 concurrent sessions | Returns `503 Service Unavailable` when exceeded. Configurable via `--max-sessions` |
628
+ | **Security headers** | On every response | `X-Content-Type-Options: nosniff`, `Cache-Control: no-store` |
629
+ | **No HTTPS** | By design | Deploy behind a TLS-terminating reverse proxy (nginx, Caddy) for production |
630
+
631
+ ### CLI Options
632
+
633
+ ```
634
+ crp serve [OPTIONS]
635
+
636
+ Options:
637
+ --port INTEGER Port number (default: 9470)
638
+ --bind-all Bind to 0.0.0.0 (requires --auth-token)
639
+ --auth-token TEXT Bearer token for authentication
640
+ --allow-unauthenticated Override auth requirement for --bind-all
641
+ --max-sessions INTEGER Max concurrent sessions (default: 64)
642
+ --rate-limit INTEGER Max requests per IP per 60s (default: 120)
643
+ ```
644
+
645
+ ### Integration with CRP Protocol
646
+
647
+ The sidecar is a thin HTTP layer over the same `CRPOrchestrator` that the Python SDK uses directly. Every session created via the sidecar is a full CRP session with:
648
+
649
+ - All 6 extraction stages (regex → statistical → NER → UIE → discourse → LLM-relational)
650
+ - Contextual Knowledge Fabric (CKF) with graph walk, pattern query, semantic fallback, community summaries
651
+ - Multi-signal completion detection and automatic continuation
652
+ - Envelope building with multi-aspect scoring and cross-encoder reranking
653
+ - Event emission for all pipeline stages (`fact.shared`, `fact.received`, `dispatch.completed`, etc.)
654
+ - RBAC enforcement, budget tracking, and cost estimation
655
+
656
+ The sidecar adds no protocol modifications. A fact extracted via the sidecar is identical to one extracted via `client.dispatch()`. A session created via HTTP behaves identically to one created via Python.
657
+
658
+ ---
659
+
660
+ ## End-to-End Example: A Penetration Test
661
+
662
+ Your pentest application already has separate LLM calls for planning, tool selection, analysis, and reporting. With CRP, each `llm.generate()` becomes `crp.dispatch()`. **CRP does not add, remove, or restructure your calls.**
663
+
664
+ ### Step 1: Planning
665
+
666
+ ```python
667
+ plan = crp.dispatch(
668
+ system_prompt="You are a penetration testing planner...",
669
+ task_input="Create a pentest plan for target 192.168.1.50. Scope: external, web focus."
670
+ )
671
+ ```
672
+
673
+ | Phase | What Happens | Time |
674
+ |-------|-------------|------|
675
+ | Envelope | Empty (first window — cold start) | 0ms |
676
+ | LLM generates | Phase 1: Recon. Phase 2: Web vuln. Phase 3: Exploitation. Phase 4: Reporting | ~3s |
677
+ | Extraction | regex captures "192.168.1.50"; statistical: "nmap", "nikto" = 8 facts | ~6ms |
678
+ | Warm state | 8 facts with embeddings | — |
679
+
680
+ ### Step 2: Tool Selection
681
+
682
+ ```python
683
+ tool_choice = crp.dispatch(
684
+ system_prompt="You are a security tool selector...",
685
+ task_input="Select and configure the first tool for recon of 192.168.1.50"
686
+ )
687
+ ```
688
+
689
+ | Phase | What Happens | Time |
690
+ |-------|-------------|------|
691
+ | Envelope | 8 facts from Step 1, scored by similarity to "tool selection for recon" | ~3ms |
692
+ | LLM generates | "Run: nmap -sV -sC -p- 192.168.1.50" | ~2s |
693
+ | Extraction | regex: full nmap command; statistical: "version detection" = 6 new facts | ~5ms |
694
+ | Warm state | Now 14 facts (8 + 6) | — |
695
+
696
+ ### Step 3: Tool Execution + Ingestion
697
+
698
+ ```python
699
+ nmap_result = run_tool("nmap", "-sV -sC -p- 192.168.1.50") # Your tool runner
700
+ crp.ingest(nmap_result) # ~7ms extraction; 22 new facts (ports, services, versions)
701
+ ```
702
+
703
+ No LLM call. Extraction pipeline processes raw tool output directly. Warm state: 36 facts.
704
+
705
+ ### Step 4: Analysis
706
+
707
+ | Phase | What Happens | Time |
708
+ |-------|-------------|------|
709
+ | Envelope | 36 facts scored for "vulnerability analysis". ~4200 tokens of dense, relevant context | ~4ms |
710
+ | LLM generates | "Critical: Apache 2.4.52 — CVE-2024-XXXX. High: OpenSSH 8.2 — known auth bypass..." | ~5s |
711
+ | Extraction | 12 new facts: CVEs, severity ratings, affected services, attack vectors | ~8ms |
712
+ | Warm state | 48 facts | — |
713
+
714
+ ### Step 5: Report Generation + Continuation
715
+
716
+ | Phase | What Happens | Time |
717
+ |-------|-------------|------|
718
+ | Envelope | 48 facts scored for "report writing". All CVEs, findings, recommendations ranked | ~5ms |
719
+ | LLM generates | "Executive Summary... Finding 1: Critical..." → hits output limit | ~8s |
720
+ | Continuation | Extract from partial report, identify missing sections, build continuation envelope | ~15ms |
721
+ | Window 2 | Fresh context, continues report. 6 more findings + recommendations | ~6s |
722
+ | Stitch | Window 1 + Window 2 joined. Echo detection removes overlap. Clean 12-page report | ~2ms |
723
+
724
+ ### Total CRP Overhead
725
+
726
+ | Step | CRP Time | LLM Time | Overhead |
727
+ |------|----------|----------|----------|
728
+ | Planning | ~6ms | ~3,000ms | 0.2% |
729
+ | Tool selection | ~8ms | ~2,000ms | 0.4% |
730
+ | Ingestion | ~7ms | 0ms | N/A |
731
+ | Analysis | ~12ms | ~5,000ms | 0.2% |
732
+ | Report + continuation | ~22ms | ~14,000ms | 0.2% |
733
+ | **Total** | **~55ms** | **~24,000ms** | **0.2%** |
734
+
735
+ ---
736
+
737
+ ## CRP in the AI Stack
738
+
739
+ ### The Three-Layer Architecture
740
+
741
+ ```
742
+ +-----------------------------------------------------------+
743
+ | Layer 3: A2A — Agent-to-Agent Communication |
744
+ | "How agents talk to each other" |
745
+ +-----------------------------------------------------------+
746
+ | Layer 2: MCP — Model Context Protocol |
747
+ | "How agents access tools" |
748
+ +-----------------------------------------------------------+
749
+ | Layer 1: CRP — Context Relay Protocol |
750
+ | "How each agent manages its own context" |
751
+ | THE FOUNDATION LAYER |
752
+ +-----------------------------------------------------------+
753
+ ```
754
+
755
+ **CRP is complementary to MCP and A2A.** MCP defines how agents access tools. A2A defines how agents communicate. CRP defines how each agent **manages its own context** — the foundation that makes both work at scale.
756
+
757
+ - Without CRP, every MCP tool call competes for context space
758
+ - Without CRP, every A2A message accumulates in a degrading window
759
+ - With CRP + MCP: tool results are extracted into facts, not piled into the window
760
+ - With CRP + A2A: inter-agent messages are structured knowledge, not raw text
761
+
762
+ ---
763
+
764
+ ## Extraction Quality
765
+
766
+ | Stage | Method | What It Extracts | Accuracy | When It Runs |
767
+ |-------|--------|-----------------|----------|-------------|
768
+ | **1** | Regex | IP addresses, CVEs, JSON, version strings | ~99% | Always |
769
+ | **2** | Statistical (TextRank) | Key sentences by term frequency | ~85-90% recall | Always |
770
+ | **3** | GLiNER NER | Entity spans (software, vulnerabilities) | ~80-90% F1 | When yield is low |
771
+ | **4** | UIE Relations | Entity relationships (X vulnerable to Y) | ~70-80% F1 | When yield is low |
772
+ | **5** | Discourse Structure | Logical relations (cause→effect, condition→consequence) via RST | ~65-75% F1 | Reasoning-dense content |
773
+ | **6** | LLM-Assisted Relational | Implicit logical relationships | ~85-90% F1 | Optional, high-complexity only |
774
+
775
+ Stages are graduated — 3-6 activate selectively based on content complexity and prior stage yield. Content is auto-classified as `ENTITY_RICH`, `REASONING_DENSE`, or `NARRATIVE` to route through appropriate strategies.
776
+
777
+ | Content Type | Typical Stages | Typical Time |
778
+ |-------------|---------------|-------------|
779
+ | Structured/factual | 1-2 | ~10-15ms |
780
+ | Mixed content | 1-4 | ~50-80ms |
781
+ | Reasoning-dense | 1-5 | ~160ms |
782
+ | High-complexity | 1-6 | ~500ms+ (Stage 6 uses LLM) |
783
+
784
+ ---
785
+
786
+ ## Efficiency and Cost
787
+
788
+ ### Per-Window Overhead
789
+
790
+ | Operation | Time | When |
791
+ |-----------|------|------|
792
+ | Multi-aspect scoring + graph packing | ~5-10ms | Every window |
793
+ | Cross-encoder reranking (top-200) | ~400ms | When >50 facts (amortized) |
794
+ | Extraction Stages 1-2 | ~6ms | Every window |
795
+ | Extraction Stage 3 (GLiNER) | ~50ms | Only when yield is low |
796
+ | Extraction Stage 4 (UIE) | ~100ms | Only when yield is low |
797
+ | Extraction Stage 5 (Discourse) | ~150ms | Reasoning-dense content |
798
+ | **Typical total** | **~15-20ms** | **0.1-1% of LLM time** |
799
+
800
+ ### Token Efficiency: CRP vs MCP
801
+
802
+ | Cost Factor | MCP | CRP |
803
+ |-------------|-----|-----|
804
+ | Tool schemas in prompt | ALL repeated every call (10K-50K) | Zero — only for tool-selection windows |
805
+ | Accumulated context | All prior results stay, attention degrades | Only relevant extracted facts |
806
+ | Redundant content | Same schemas repeated N times | No repetition — envelope carries only what's relevant |
807
+
808
+ **Example**: 20-step agentic loop, 50 tools:
809
+ - **MCP**: 20 × 10K schema tokens = **200K tokens** on tool definitions alone
810
+ - **CRP**: Schemas in tool-selection windows only. **~90% fewer protocol tokens**
811
+
812
+ ### Cloud API Cost
813
+
814
+ | Scenario | Without CRP | With CRP | Savings |
815
+ |----------|------------|----------|---------|
816
+ | 20-step agentic loop (50 tools) | ~400K tokens | ~120K tokens | ~70% |
817
+ | Long report (3 continuations) | Truncated at limit | 4 windows, complete | N/A (impossible before) |
818
+ | Simple single-turn task | ~2K tokens | ~2K tokens | 0% (no penalty) |
819
+
820
+ ### Real-World: 200-Page Textbook Generation
821
+
822
+ | Provider | Total Cost | Windows |
823
+ |----------|-----------|---------|
824
+ | Claude Opus | ~$17 | ~32 |
825
+ | Claude Sonnet | ~$3.30 | ~32 |
826
+ | GPT-4o | ~$2.50 | ~32 |
827
+ | DeepSeek | ~$0.27 | ~32 |
828
+ | Local model (Ollama) | **$0** | ~32 |
829
+
830
+ Naive approach (paste all prior chapters into context): ~800K+ input tokens and worse quality.
831
+
832
+ ### Cost Controls
833
+
834
+ ```python
835
+ client = Client(
836
+ llm=adapter,
837
+ max_windows_per_session=50,
838
+ max_total_input_tokens=1_000_000,
839
+ max_total_output_tokens=500_000,
840
+ )
841
+
842
+ # Pre-flight estimation
843
+ estimate = client.estimate_session(planned_dispatches=32, avg_output_tokens=4000)
844
+ print(f"Estimated cost: ${estimate.estimated_cost_usd:.2f}")
845
+
846
+ # Live tracking
847
+ status = client.session_status()
848
+ print(f"Running total: ${status.total_cost:.2f}")
849
+ ```
850
+
851
+ Budget caps raise `BudgetExhaustedError` when hit. Rate limits are respected automatically.
852
+
853
+ ---
854
+
855
+ ## Observability and Auditing
856
+
857
+ ### Per-Window Metrics (Automatic)
858
+
859
+ Every `crp.dispatch()` records:
860
+
861
+ ```json
862
+ {
863
+ "window_id": "w-a3f2c1",
864
+ "session_id": "pentest-192.168.1.50",
865
+ "parent_windows": ["w-b7e4d2"],
866
+ "envelope_tokens": 4200,
867
+ "saturation": 0.94,
868
+ "extraction_stages_used": ["regex", "statistical"],
869
+ "extraction_time_ms": 7,
870
+ "facts_extracted": 12,
871
+ "information_flow_rate": 0.0018,
872
+ "quality_tier": "S",
873
+ "gap_analysis": {"required": 7, "fulfilled": 7, "missing": 0},
874
+ "continuation_triggered": false
875
+ }
876
+ ```
877
+
878
+ ### Session Dashboard
879
+
880
+ | Metric | Alert Threshold | What It Means |
881
+ |--------|-----------------|---------------|
882
+ | Total windows | >>2× your call count | Runaway continuations |
883
+ | Continuation rate | >30% | Tasks may be too large for one window |
884
+ | Average saturation | <60% | Extraction yield is low |
885
+ | Extraction yield | <2 facts/window | Content type may need different strategy |
886
+ | Stage escalation rate | >50% | Structured output would help |
887
+
888
+ ### Window DAG Traceability
889
+
890
+ Every session produces a directed acyclic graph:
891
+
892
+ ```
893
+ W1 (plan) → W2 (tool select) → W3 (analysis) → W4 (report) → W5 (report cont.)
894
+ ```
895
+
896
+ Each node shows facts produced, facts consumed, information flow, and envelope saturation. Enables "why did it do that?" debugging by tracing decisions through the DAG.
897
+
898
+ ---
899
+
900
+ ## Limitations and Trade-offs
901
+
902
+ | Limitation | Severity | Mitigation |
903
+ |-----------|----------|-----------|
904
+ | **Extraction is lossy** | MEDIUM | 6-stage pipeline covers spectrum. ~85-90% recall on structured, ~70-80% on reasoning-dense, ~50-65% on implicit. See [§7.6](specification/02_CORE_PROTOCOL.md) for degradation model |
905
+ | **Fact granularity mismatch** | MEDIUM | Graduated pipeline from tight entities (regex) through relationships (UIE, discourse). Fact graph preserves inter-fact relationships |
906
+ | **Hallucinations may pass fact gate** | MEDIUM | Three-tier validation: structural, confidence, anomaly detection. Not perfect for structurally-valid hallucinations |
907
+ | **Cold start** | LOW | First window: empty envelope. First ~5 windows: calibrating. System bootstraps safely — never prematurely terminates |
908
+ | **Not beneficial for single-turn** | N/A | CRP adds zero value (and zero cost) for tasks that fit in one window |
909
+
910
+ ---
911
+
912
+ ## Why Large Context Windows Are Not Enough
913
+
914
+ "But my model has 1M context!" — Three problems:
915
+
916
+ 1. **Output limits are NOT 1M.** Models with 1M *input* have *output* limits of 8K-32K. You still need continuation
917
+ 2. **Attention degrades with length.** "Lost in the middle" means content at position 30K is invisible at position 200K ([Liu et al., 2023](https://arxiv.org/abs/2307.03172))
918
+ 3. **Cost scales quadratically.** Growing context = $O(N^2)$ total tokens. CRP envelopes = $O(N)$ linear scaling
919
+
920
+ But more fundamentally, **context size is only 1 of CRP's 9 permanent value propositions**:
921
+
922
+ | # | Value Proposition | Why Native Context Cannot Provide It |
923
+ |---|---|---|
924
+ | 1 | **Context Quality** | CRP's scored, graph-structured envelopes put the right facts first. Raw text has no ranking |
925
+ | 2 | **Task Isolation** | One window per task. No cross-task attention contamination |
926
+ | 3 | **Attention Optimization** | Critical facts placed in the attention sink, not buried at position 500K |
927
+ | 4 | **Cost Efficiency** | $O(N)$ total tokens vs $O(N^2)$ for growing native context |
928
+ | 5 | **Cross-Session Knowledge** | CKF persists facts and reasoning across sessions |
929
+ | 6 | **Structured Knowledge** | Typed fact graph with edges, communities, temporal history |
930
+ | 7 | **Multi-Agent Coordination** | Envelope = structured state transfer between agents |
931
+ | 8 | **Observability** | Full provenance: every fact has source, confidence, lifecycle |
932
+ | 9 | **Reasoning Amplification** | Meta-learning scaffolds turn 2B models into reasoning systems |
933
+
934
+ **Even a model with infinite native context needs CRP** for propositions 1-4, 6-9.
935
+
936
+ Scientific backing: "Retrieval can significantly improve the performance of LLMs **regardless of their extended context window sizes**" — Xu et al., ICLR 2024.
937
+
938
+ ---
939
+
940
+ ## Specification Documents
941
+
942
+ The complete CRP v2.0 specification:
943
+
944
+ | # | Document | Description | Lines |
945
+ |---|----------|-------------|-------|
946
+ | 1 | [01_RESEARCH_FOUNDATIONS.md](specification/01_RESEARCH_FOUNDATIONS.md) | Academic research backing — 9 research areas, 40+ papers, meta-learning, retrieval augmentation | ~1,200 |
947
+ | 2 | [02_CORE_PROTOCOL.md](specification/02_CORE_PROTOCOL.md) | **The core specification** — 29 sections: axioms, state model, CKF, extraction, completion detection, quality tiers, hierarchical processing, meta-learning, security, concurrency, observability, deployment, publication | ~6,800 |
948
+ | 3 | [03_CONTEXT_ENVELOPE.md](specification/03_CONTEXT_ENVELOPE.md) | Context envelope — multi-phase scoring, CKF retrieval, source grounding, continuation envelopes | ~1,200 |
949
+ | 4 | [04_TOKEN_GENERATION_PROTOCOL.md](specification/04_TOKEN_GENERATION_PROTOCOL.md) | Unbounded output — continuation, stitching, voice profiles, document maps, completion detection | ~950 |
950
+ | 5 | [05_SYSTEM_WIDE_INTEGRATION.md](specification/05_SYSTEM_WIDE_INTEGRATION.md) | Integration architecture — 87+ call sites mapped, component inventory, migration strategy | ~1,750 |
951
+ | 6 | [06_IMPLEMENTATION_PLAN.md](specification/06_IMPLEMENTATION_PLAN.md) | Implementation plan — phased rollout, 13 modules, ~3,890 lines of code planned | ~2,000 |
952
+ | 7 | [07_SECURITY.md](specification/07_SECURITY.md) | Security architecture — threat model, input validation, fact integrity, RBAC, encryption, OWASP, quantum resistance | ~1,300 |
953
+ | 8 | [08_MONETIZATION.md](specification/08_MONETIZATION.md) | Business model — PostgreSQL model (full capability free), 5 revenue pillars, competitive positioning | ~2,000 |
954
+ | 9 | [09_DEPLOYMENT.md](specification/09_DEPLOYMENT.md) | Deployment — embedded library rationale, resource footprint, Lambda/K8s/MCP comparison, containerization | ~2,000 |
955
+
956
+ **Total specification**: ~19,200 lines across 9 documents.
957
+
958
+ ---
959
+
960
+ ## JSON Schemas
961
+
962
+ All API types are defined as [JSON Schema (Draft 2020-12)](https://json-schema.org/draft/2020-12/schema) for language-neutral consumption:
963
+
964
+ | Schema | Description | Source |
965
+ |--------|-------------|--------|
966
+ | [task-intent.json](schemas/task-intent.json) | `TaskIntent` — declarative, all-optional dispatch input | §6.10.2 |
967
+ | [quality-report.json](schemas/quality-report.json) | `QualityReport` — returned with every dispatch | §6.10.2 |
968
+ | [session-status.json](schemas/session-status.json) | `SessionStatus` — session health snapshot | §6.10.2 |
969
+ | [cost-estimate.json](schemas/cost-estimate.json) | `CostEstimate` — pre-flight cost estimation | §6.10.2 |
970
+ | [envelope-preview.json](schemas/envelope-preview.json) | `EnvelopePreview` — inspect without dispatching | §6.10.2 |
971
+ | [session-handle.json](schemas/session-handle.json) | `SessionHandle` — returned by init() | §6.10.8 |
972
+ | [stream-event.json](schemas/stream-event.json) | `StreamEvent` — streaming dispatch events | §6.10.5 |
973
+ | [crp-error.json](schemas/crp-error.json) | `CRPError` — standard error format | §6.10.4 |
974
+ | [persisted-state-header.json](schemas/persisted-state-header.json) | `PersistedStateHeader` — cold state versioning | §6.10.10 |
975
+
976
+ ---
977
+
978
+ ## API Surface
979
+
980
+ CRP exposes a synchronous + async + streaming API. All operations use **direct function invocation** (not network RPC). SDKs MAY expose JSON-RPC or gRPC transports for cross-process access.
981
+
982
+ ### Core Operations
983
+
984
+ | Operation | Stability | Description |
985
+ |-----------|-----------|-------------|
986
+ | `Client(provider=..., app_id=...)` | **Stable** | Create session, init subsystems, restore cold state |
987
+ | `dispatch(system_prompt, task_input, ...)` | **Stable** | Execute LLM window with envelope, extract facts |
988
+ | `dispatch_stream(...)` | Provisional | Streaming variant — emits token/extraction/continuation/done events |
989
+ | `ingest(raw_text, ...)` | **Stable** | Extract facts without LLM invocation (~7ms) |
990
+ | `session_status()` | **Stable** | Session health: windows, tokens, facts, budget remaining, cost |
991
+ | `estimate_session(...)` | **Stable** | Pre-flight cost estimation with USD pricing |
992
+ | `preview_envelope(...)` | **Stable** | Inspect what the envelope would contain |
993
+ | `configure(config)` | **Stable** | Update security/cost config (ADMIN) |
994
+ | `export_state(...)` | Provisional | Export encrypted session state |
995
+ | `close()` | **Stable** | Flush warm → cold, persist CKF, clean up |
996
+
997
+ ### Error Taxonomy
998
+
999
+ | Code | Error | Comparable To |
1000
+ |------|-------|---------------|
1001
+ | 1001 | `BudgetExhaustedError` | gRPC `RESOURCE_EXHAUSTED` |
1002
+ | 1002 | `RateLimitExceeded` | HTTP 429 |
1003
+ | 1003 | `SessionExpired` | gRPC `DEADLINE_EXCEEDED` |
1004
+ | 1005 | `SessionClosed` | gRPC `FAILED_PRECONDITION` |
1005
+ | 1010 | `ValidationError` | gRPC `INVALID_ARGUMENT` |
1006
+ | 1011 | `SecurityInvariantError` | gRPC `ABORTED` |
1007
+ | 1012 | `SignatureInvalidError` | gRPC `UNAUTHENTICATED` |
1008
+ | 1020 | `ProviderError` | gRPC `INTERNAL` |
1009
+ | 1021 | `ProviderTimeoutError` | gRPC `DEADLINE_EXCEEDED` |
1010
+ | 1030 | `StateCorruptedError` | gRPC `DATA_LOSS` |
1011
+ | 1031 | `ChainVerificationFailedError` | gRPC `DATA_LOSS` |
1012
+ Full error taxonomy with all codes in [§6.10.4](specification/02_CORE_PROTOCOL.md).
1013
+
1014
+ ### RBAC Roles (Planned)
1015
+
1016
+ | Role | Permissions |
1017
+ |------|------------|
1018
+ | **OBSERVER** | `session_status`, `estimate_session` |
1019
+ | **OPERATOR** | All OBSERVER + `dispatch`, `ingest`, `preview_envelope` |
1020
+ | **ADMIN** | All OPERATOR + `configure`, `reset_session`, `export_state` |
1021
+
1022
+ > RBAC is fully enforced in the SDK. Every dispatch, ingest, and admin operation checks `RBACEnforcer.check_permission()` and `check_rate_limit()` before proceeding. Default role is OPERATOR (dispatch + ingest). Set via `CRPConfig(default_role="ADMIN")` or `CRPConfig(default_role="OBSERVER")`.
1023
+
1024
+ ---
1025
+
1026
+ ## SDK Status
1027
+
1028
+ | Language | Status | Package | Repository |
1029
+ |----------|--------|---------|------------|
1030
+ | **Python** | ✅ v2.0.0 | `pip install -e ".[dev]"` | This repository |
1031
+ | **TypeScript** | 📋 Planned | `npm install @crp/sdk` | `crp-typescript` |
1032
+ | **Rust** | 📋 Planned | `cargo add crp` | `crp-rust` |
1033
+
1034
+ ### Python SDK — Quick Start
1035
+
1036
+ ```bash
1037
+ pip install -e ".[dev]"
1038
+ ```
1039
+
1040
+ ```python
1041
+ import crp
1042
+
1043
+ # Zero-config: auto-detects LLM from environment
1044
+ client = crp.Client()
1045
+
1046
+ # Or explicit: pass model name or provider
1047
+ client = crp.Client(model="gpt-4o")
1048
+ # client = crp.Client(provider=CustomProvider(...))
1049
+
1050
+ # Dispatch — CRP builds envelope, calls your LLM, extracts facts, returns raw output
1051
+ output, report = client.dispatch(
1052
+ system_prompt="You are a security analyst.",
1053
+ task_input="Analyze the authentication flow in auth.py.",
1054
+ )
1055
+
1056
+ print(output) # Unmodified LLM output (Axiom 9)
1057
+ print(report.quality_tier) # "S" | "A" | "B" | "C" | "D"
1058
+ print(report.facts_extracted) # Facts pulled from output
1059
+ print(report.continuation_windows) # How many continuation windows were used
1060
+ ```
1061
+
1062
+ **Built-in Providers:**
1063
+
1064
+ | Provider | Import | Requirements |
1065
+ |----------|--------|-------------|
1066
+ | Auto-detect | `crp.Client()` | Set `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, or run Ollama |
1067
+ | Custom (any LLM) | `crp.providers.CustomProvider` | None |
1068
+ | OpenAI / Azure | `crp.providers.OpenAIAdapter` | `openai>=1.0`, `tiktoken` |
1069
+ | Anthropic | `crp.providers.AnthropicAdapter` | `anthropic>=0.25` |
1070
+ | Ollama | `crp.providers.OllamaAdapter` | Running Ollama instance |
1071
+ | llama.cpp | `crp.providers.LlamaCppAdapter` | `llama-cpp-python` or HTTP server |
1072
+
1073
+ **Key Features:**
1074
+ - 351 tests passing (integration + benchmarks + unit)
1075
+ - Zero-config auto-detection (`Client()` or `Client(model="...")`)
1076
+ - Quality tier classification (S/A/B/C/D) on every dispatch
1077
+ - Zero-LLM ingestion (`client.ingest()`)
1078
+ - Streaming dispatch (`client.dispatch_stream()`)
1079
+ - Continuation with key findings context threading
1080
+ - Full observability (events, audit log, metrics export)
1081
+ - Budget enforcement (windows, input/output tokens)
1082
+ - State export (encrypted AES-256-GCM)
1083
+
1084
+ The specification is language-neutral. JSON Schemas in [`/schemas/`](schemas/) enable code generation for any language.
1085
+
1086
+ ---
1087
+
1088
+ ## Comparison with Alternatives
1089
+
1090
+ | Approach | What It Does | Limitation | In-Window Overhead |
1091
+ |----------|-------------|------------|-------------------|
1092
+ | **Naive Prompting** | Everything in one window | Context contamination, attention collapse | None (quality degrades) |
1093
+ | **RAG** | Retrieves relevant documents (flat vectors) | No output management, no continuation, no graph | Retrieved chunks only |
1094
+ | **MemGPT / Letta** | Virtual memory via LLM self-management | LLM burns tokens managing its own memory | High (memory function calls) |
1095
+ | **GraphRAG** | Knowledge graph + community summaries | Static offline indexing, no real-time extraction | Low (query overhead) |
1096
+ | **Sliding Window** | Truncates old context | Early context permanently lost | Low (but lossy) |
1097
+ | **MCP** | Standardized tool interface | Manages tool *access*, not tool *output context* | Very High (10K-50K schemas) |
1098
+ | **A2A** | Inter-agent communication | Manages *messages between agents*, not context *within* | Varies |
1099
+ | **CRP** | Task isolation + CKF + extraction envelopes + continuation | Extraction is imperfect | **Zero** |
1100
+
1101
+ **Key distinction**: MCP and A2A solve *different problems*. MCP connects LLMs to tools. A2A connects agents to each other. CRP manages context within each agent. They are complementary and can be used together.
1102
+
1103
+ ---
1104
+
1105
+ ## Hardware Requirements
1106
+
1107
+ | Component | Size | Required? |
1108
+ |-----------|------|-----------|
1109
+ | Your LLM | Varies | Yes (already running) |
1110
+ | all-MiniLM-L6-v2 (embeddings) | ~80MB | Yes |
1111
+ | ms-marco-MiniLM-L6-v2 (reranker) | ~80MB | No (bi-encoder sufficient for <50 facts) |
1112
+ | GLiNER (NER) | ~200MB | No (lazy-loaded, degrades gracefully) |
1113
+ | UIE (relations) | ~400MB | No (lazy-loaded, degrades gracefully) |
1114
+
1115
+ **Minimum**: Any machine running an LLM can run CRP. **80MB required** + 0-680MB optional.
1116
+
1117
+ ---
1118
+
1119
+ ## Configuration
1120
+
1121
+ CRP follows a 5-layer configuration hierarchy (see [§25](specification/02_CORE_PROTOCOL.md)):
1122
+
1123
+ ```
1124
+ Layer 5: Runtime API (highest priority)
1125
+ Layer 4: Environment Variables
1126
+ Layer 3: Session Config File
1127
+ Layer 2: User Config File
1128
+ Layer 1: Built-in Defaults (lowest priority)
1129
+ ```
1130
+
1131
+ All configuration is optional. CRP works with zero configuration if you pass your LLM adapter directly.
1132
+
1133
+ ### Key Environment Variables
1134
+
1135
+ | Variable | Default | Description |
1136
+ |----------|---------|-------------|
1137
+ | `CRP_ENABLED` | `true` | Master switch |
1138
+ | `CRP_LLM_ENDPOINT` | — | Fallback LLM endpoint if no adapter passed |
1139
+ | `CRP_LOG_ENVELOPES` | `false` | Debug: log envelope contents |
1140
+ | `CRP_MAX_WINDOWS` | `100` | Session window limit |
1141
+ | `CRP_TELEMETRY_FILE` | `crp_telemetry.jsonl` | Telemetry output path |
1142
+
1143
+ ---
1144
+
1145
+ ## Use Cases
1146
+
1147
+ | Domain | How CRP Helps |
1148
+ |--------|--------------|
1149
+ | **Penetration Testing** | Each tool selection, analysis, and report section gets a fresh window with full findings context |
1150
+ | **Report Generation** | Unbounded-length reports with per-section windows, gap-aware continuation, quality-tiered output |
1151
+ | **Multi-Step Reasoning** | Each step gets full context; prior conclusions carried as facts. ORC decomposes complex reasoning |
1152
+ | **Agentic Tool Use** | Tool results extracted into facts immediately; next selection sees ALL discoveries, ranked |
1153
+ | **Code Generation** | Large codebases across multiple windows; each sees full architecture via envelopes |
1154
+ | **Research & Analysis** | Long-form analysis exceeding any single window; information flow detects genuine completion |
1155
+ | **Small Model Amplification** | Meta-learning scaffolds enable 2B–7B models to perform reasoning they cannot do natively |
1156
+ | **Legal Document Analysis** | Million-token contracts auto-ingested; cross-reference tracking via fact graph |
1157
+ | **Medical Literature Review** | Cross-session knowledge accumulates across papers; community detection groups related findings |
1158
+
1159
+ ---
1160
+
1161
+ ## Roadmap
1162
+
1163
+ ### Phase 1: Open Specification ← **We are here**
1164
+ - [x] Publish CRP v2.0 specification (9 documents, ~19,200 lines)
1165
+ - [x] JSON Schema definitions for all API types
1166
+ - [ ] Reference SDK: Python (`pip install crprotocol`)
1167
+ - [ ] Benchmark results: CRP on vs. off across tasks and models
1168
+ - [ ] arXiv technical report with empirical evaluation
1169
+
1170
+ ### Phase 2: Ecosystem
1171
+ - [ ] JSON-RPC server mode — any language can use CRP over HTTP
1172
+ - [ ] TypeScript/JavaScript reference implementation
1173
+ - [ ] Integration guides: LangChain, LlamaIndex, AutoGen, CrewAI
1174
+ - [ ] MCP + CRP integration example
1175
+ - [ ] A2A + CRP integration example
1176
+
1177
+ ### Phase 3: Meta-Learning & Advanced Features
1178
+ - [ ] Source-Grounded Envelope engine
1179
+ - [ ] LLM-Driven Context Curation with progressive understanding
1180
+ - [ ] Reasoning Template Library (RTL)
1181
+ - [ ] Orchestrated Reasoning Chains (ORC)
1182
+ - [ ] Domain-specialized GLiNER models (cybersecurity, biomedical, legal, financial, regulatory)
1183
+ - [ ] Benchmark: reasoning amplification on 2B/7B vs. baseline
1184
+
1185
+ ### Phase 4: Adoption & Standards
1186
+ - [ ] IETF Internet-Draft submission
1187
+ - [ ] W3C Community Group: "Context Management for AI"
1188
+ - [ ] LF AI & Data project hosting
1189
+ - [ ] Conformance test suite
1190
+ - [ ] Community benchmark suite for context management quality
1191
+
1192
+ ---
1193
+
1194
+ ## Contributing
1195
+
1196
+ We welcome contributions! See [CONTRIBUTING.md](CONTRIBUTING.md) for:
1197
+
1198
+ - How to submit issues, spec clarifications, and pull requests
1199
+ - The RFC process for non-trivial specification changes
1200
+ - Code of conduct
1201
+ - Contributor License Agreement (CLA)
1202
+
1203
+ ---
1204
+
1205
+ ## Governance
1206
+
1207
+ CRP follows an open governance model inspired by the Apache Software Foundation. See [GOVERNANCE.md](GOVERNANCE.md) for:
1208
+
1209
+ - Roles: Maintainers, Committers, Contributors
1210
+ - Decision-making process (consensus-seeking, lazy consensus for minor changes, formal vote for breaking changes)
1211
+ - Specification versioning and deprecation policy
1212
+
1213
+ ---
1214
+
1215
+ ## Security
1216
+
1217
+ See [SECURITY.md](SECURITY.md) for:
1218
+
1219
+ - Responsible disclosure policy
1220
+ - Security contact information
1221
+ - What constitutes a security vulnerability in CRP
1222
+ - How security issues in reference implementations are handled
1223
+
1224
+ The protocol's security architecture is documented in [07_SECURITY.md](specification/07_SECURITY.md) — covering threat modeling, input validation, fact integrity, RBAC, encryption at rest, OWASP mapping, and quantum resistance planning.
1225
+
1226
+ ---
1227
+
1228
+ ## Community
1229
+
1230
+ - **GitHub Discussions**: [Join the conversation](https://github.com/Constantinos-uni/context-relay-protocol/discussions)
1231
+ - **GitHub Issues**: Bug reports, spec clarifications, feature requests
1232
+ - **General enquiries**: [info@crprotocol.io](mailto:info@crprotocol.io)
1233
+ - **Enterprise & licensing**: [contact@crprotocol.io](mailto:contact@crprotocol.io)
1234
+
1235
+ ---
1236
+
1237
+ ## Built With
1238
+
1239
+ | Component | Technology |
1240
+ |-----------|-----------|
1241
+ | **Knowledge Layer** | CKF — graph walk + pattern query + semantic fallback + community summaries, event-sourced history |
1242
+ | **Extraction** | 6-stage graduated blackboard-reactive pipeline (regex → TextRank → GLiNER → UIE → RST discourse → LLM-relational) |
1243
+ | **Source Grounding** | Dual-layer envelopes — extracted facts paired with original text passages |
1244
+ | **Meta-Learning** | ORC + ICML + RTL — structured reasoning scaffolding for small models |
1245
+ | **Embeddings** | sentence-transformers/all-MiniLM-L6-v2 (~80MB, CPU) |
1246
+ | **Reranking** | cross-encoder/ms-marco-MiniLM-L6-v2 (~80MB, ~500 pairs/sec on CPU) |
1247
+ | **Indexing** | HNSW approximate nearest neighbor — O(log N) retrieval |
1248
+ | **Storage** | Warm state (in-memory fact graph + event log) + CKF cold storage (SQLite WAL + vector DB + graph) |
1249
+ | **Coherence** | Voice profiles, progressive document maps, degradation-triggered re-grounding |
1250
+ | **Validation** | Pydantic v2 / JSON Schema Draft 2020-12 |
1251
+
1252
+ ---
1253
+
1254
+ ## Positioning Statement
1255
+
1256
+ **For developers building LLM-powered applications** who need reliable context management across multiple LLM invocations, **CRP (Context Relay Protocol)** is an open protocol that provides structured knowledge extraction, cross-session persistence, and honest quality guarantees. **Unlike** ad-hoc prompt chaining, proprietary context APIs, or vector-only RAG, CRP offers a **formally specified, LLM-agnostic, embedded-library protocol** with a graduated extraction pipeline, graph-structured knowledge fabric, and transparent degradation model — all deployable with zero infrastructure overhead.
1257
+
1258
+ ---
1259
+
1260
+ ## License
1261
+
1262
+ Context Relay Protocol (CRP) is the original work of **Constantinos Vidiniotis**, created in 2026.
1263
+
1264
+ ### Specification
1265
+
1266
+ The protocol specification documents are licensed under the **Creative Commons Attribution-ShareAlike 4.0 International License (CC BY-SA 4.0)**. You may read, share, and adapt the specification with attribution. Full terms: https://creativecommons.org/licenses/by-sa/4.0/
1267
+
1268
+ ### Implementation Code
1269
+
1270
+ SDK and implementation code is licensed under the **Elastic License 2.0 (ELv2)**. You may use CRP freely in your own applications. You may NOT offer CRP as a hosted/managed service without a commercial license.
1271
+
1272
+ ### Commercial Licensing
1273
+
1274
+ For enterprise licensing, managed-service rights, or OEM inquiries:
1275
+
1276
+ **AutoCyber AI Pty Ltd** · ABN 22 697 087 166
1277
+ Email: [contact@crprotocol.io](mailto:contact@crprotocol.io) · General: [info@crprotocol.io](mailto:info@crprotocol.io) · Web: [crprotocol.io](https://crprotocol.io)
1278
+
1279
+ ### Trademark
1280
+
1281
+ "Context Relay Protocol" is a trademark of Constantinos Vidiniotis (application pending, Class 9 — IP Australia).
1282
+ Use of the name to refer to this project is welcomed; use implying endorsement or affiliation without authorization is not permitted.
1283
+
1284
+ See [LICENSE.md](LICENSE.md) for the full license text.
1285
+
1286
+ **Copyright (c) 2026 Constantinos Vidiniotis. All rights reserved.**
1287
+
1288
+ ---
1289
+
1290
+ <p align="center">
1291
+ <strong>Context Relay Protocol v2.0</strong><br>
1292
+ Zero configuration. Unbounded input. Unbounded output. Amplified reasoning.<br>
1293
+ Better context at every scale. Honest degradation. Quality-tiered.<br>
1294
+ Peak quality. Every window.
1295
+ </p>