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
crp/cli/startup.py ADDED
@@ -0,0 +1,272 @@
1
+ # Copyright © 2025 Constantinos Vidiniotis. All rights reserved.
2
+ # Licensed under Elastic License 2.0 — see LICENSE.md for details.
3
+ """CRP startup sequence — 6 steps per §09 §9.5.
4
+
5
+ Step 1: Resolve config (5-layer, ~1 ms)
6
+ Step 2: Validate config (type checks, ~5 ms)
7
+ Step 3: Authenticate app (HMAC handshake, ~1 ms)
8
+ Step 4: Connect to LLM (health check, ~200–500 ms cloud)
9
+ Step 5: Init session state (warm store + event log, ~5–50 ms)
10
+ Step 6: Start event emitter (~1 ms)
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ import time
17
+ from dataclasses import dataclass, field
18
+ from typing import Any
19
+
20
+ logger = logging.getLogger("crp.startup")
21
+
22
+
23
+ # ---------------------------------------------------------------------------
24
+ # Result container
25
+ # ---------------------------------------------------------------------------
26
+
27
+
28
+ @dataclass
29
+ class StartupStep:
30
+ """Result of one startup step."""
31
+
32
+ step: int
33
+ name: str
34
+ ok: bool = True
35
+ latency_ms: float = 0.0
36
+ detail: str = ""
37
+
38
+
39
+ @dataclass
40
+ class StartupResult:
41
+ """Aggregate result of the startup sequence."""
42
+
43
+ steps: list[StartupStep] = field(default_factory=list)
44
+ total_ms: float = 0.0
45
+
46
+ @property
47
+ def ok(self) -> bool:
48
+ return all(s.ok for s in self.steps)
49
+
50
+ @property
51
+ def summary(self) -> dict[str, Any]:
52
+ return {
53
+ "ok": self.ok,
54
+ "total_ms": round(self.total_ms, 2),
55
+ "steps": [
56
+ {"step": s.step, "name": s.name, "ok": s.ok,
57
+ "ms": round(s.latency_ms, 2)}
58
+ for s in self.steps
59
+ ],
60
+ }
61
+
62
+
63
+ # ---------------------------------------------------------------------------
64
+ # Startup runner
65
+ # ---------------------------------------------------------------------------
66
+
67
+
68
+ def run_startup(
69
+ *,
70
+ provider: Any | None = None,
71
+ config_overrides: dict[str, Any] | None = None,
72
+ binding_secret: bytes | None = None,
73
+ skip_auth: bool = False,
74
+ skip_health: bool = False,
75
+ ) -> tuple[StartupResult, dict[str, Any]]:
76
+ """Execute the 6-step startup sequence.
77
+
78
+ Returns ``(result, context)`` where *context* is a dict of resolved
79
+ objects: ``config``, ``provider``, ``binding``, ``warm_store``,
80
+ ``emitter``, ``session``.
81
+ """
82
+ ctx: dict[str, Any] = {}
83
+ steps: list[StartupStep] = []
84
+ t0 = time.monotonic()
85
+
86
+ # ------------------------------------------------------------------
87
+ # Step 1 — Resolve config (5-layer hierarchy)
88
+ # ------------------------------------------------------------------
89
+ t = time.monotonic()
90
+ try:
91
+ from crp.core.config import ConfigurationResolver
92
+
93
+ config = ConfigurationResolver().resolve(**(config_overrides or {}))
94
+ ctx["config"] = config
95
+ steps.append(StartupStep(
96
+ step=1, name="resolve_config",
97
+ latency_ms=_elapsed(t),
98
+ ))
99
+ except Exception as exc:
100
+ steps.append(StartupStep(
101
+ step=1, name="resolve_config", ok=False,
102
+ latency_ms=_elapsed(t), detail=str(exc),
103
+ ))
104
+ return StartupResult(steps=steps, total_ms=_elapsed(t0)), ctx
105
+
106
+ # ------------------------------------------------------------------
107
+ # Step 2 — Validate config
108
+ # ------------------------------------------------------------------
109
+ t = time.monotonic()
110
+ try:
111
+ _validate_config(config)
112
+ steps.append(StartupStep(
113
+ step=2, name="validate_config",
114
+ latency_ms=_elapsed(t),
115
+ ))
116
+ except Exception as exc:
117
+ steps.append(StartupStep(
118
+ step=2, name="validate_config", ok=False,
119
+ latency_ms=_elapsed(t), detail=str(exc),
120
+ ))
121
+ return StartupResult(steps=steps, total_ms=_elapsed(t0)), ctx
122
+
123
+ # ------------------------------------------------------------------
124
+ # Step 3 — Authenticate (HMAC session binding)
125
+ # ------------------------------------------------------------------
126
+ t = time.monotonic()
127
+ if skip_auth:
128
+ steps.append(StartupStep(
129
+ step=3, name="authenticate", latency_ms=_elapsed(t),
130
+ detail="skipped",
131
+ ))
132
+ else:
133
+ try:
134
+ from crp.security.binding import SessionBindingManager
135
+
136
+ secret = binding_secret or config.get("binding_secret", "").encode()
137
+ mgr = SessionBindingManager(master_secret=secret or None)
138
+ binding = mgr.create_session()
139
+ ctx["binding"] = binding
140
+ steps.append(StartupStep(
141
+ step=3, name="authenticate",
142
+ latency_ms=_elapsed(t),
143
+ ))
144
+ except Exception as exc:
145
+ steps.append(StartupStep(
146
+ step=3, name="authenticate", ok=False,
147
+ latency_ms=_elapsed(t), detail=str(exc),
148
+ ))
149
+
150
+ # ------------------------------------------------------------------
151
+ # Step 4 — Connect to LLM (health check)
152
+ # ------------------------------------------------------------------
153
+ t = time.monotonic()
154
+ if provider is None or skip_health:
155
+ ctx["provider"] = provider
156
+ steps.append(StartupStep(
157
+ step=4, name="connect_llm", latency_ms=_elapsed(t),
158
+ detail="skipped" if skip_health else "no provider",
159
+ ))
160
+ else:
161
+ try:
162
+ from crp.providers.diagnostic import ProviderDiagnostic
163
+
164
+ report = ProviderDiagnostic().diagnose(provider)
165
+ ctx["provider"] = provider
166
+ ctx["diagnostic"] = report
167
+ steps.append(StartupStep(
168
+ step=4, name="connect_llm",
169
+ ok=report.all_passed,
170
+ latency_ms=_elapsed(t),
171
+ detail="" if report.all_passed else "health check failed",
172
+ ))
173
+ except Exception as exc:
174
+ ctx["provider"] = provider
175
+ steps.append(StartupStep(
176
+ step=4, name="connect_llm", ok=False,
177
+ latency_ms=_elapsed(t), detail=str(exc),
178
+ ))
179
+
180
+ # ------------------------------------------------------------------
181
+ # Step 5 — Initialize session state (warm store + event log)
182
+ # ------------------------------------------------------------------
183
+ t = time.monotonic()
184
+ try:
185
+ from crp.state.event_log import FactEventLog
186
+ from crp.state.warm_store import WarmStateStore
187
+
188
+ store = WarmStateStore()
189
+ event_log = FactEventLog()
190
+ ctx["warm_store"] = store
191
+ ctx["event_log"] = event_log
192
+ steps.append(StartupStep(
193
+ step=5, name="init_session_state",
194
+ latency_ms=_elapsed(t),
195
+ ))
196
+ except Exception as exc:
197
+ steps.append(StartupStep(
198
+ step=5, name="init_session_state", ok=False,
199
+ latency_ms=_elapsed(t), detail=str(exc),
200
+ ))
201
+
202
+ # ------------------------------------------------------------------
203
+ # Step 6 — Start event emitter
204
+ # ------------------------------------------------------------------
205
+ t = time.monotonic()
206
+ try:
207
+ from crp.observability.events import EventEmitter
208
+
209
+ emitter = EventEmitter()
210
+ emitter.start()
211
+ ctx["emitter"] = emitter
212
+ steps.append(StartupStep(
213
+ step=6, name="start_event_emitter",
214
+ latency_ms=_elapsed(t),
215
+ ))
216
+ except Exception as exc:
217
+ steps.append(StartupStep(
218
+ step=6, name="start_event_emitter", ok=False,
219
+ latency_ms=_elapsed(t), detail=str(exc),
220
+ ))
221
+
222
+ result = StartupResult(steps=steps, total_ms=_elapsed(t0))
223
+ logger.info(
224
+ "Startup %s in %.1f ms (%d steps)",
225
+ "OK" if result.ok else "FAILED",
226
+ result.total_ms,
227
+ len(steps),
228
+ )
229
+ return result, ctx
230
+
231
+
232
+ # ---------------------------------------------------------------------------
233
+ # Helpers
234
+ # ---------------------------------------------------------------------------
235
+
236
+
237
+ def _elapsed(start: float) -> float:
238
+ return (time.monotonic() - start) * 1000
239
+
240
+
241
+ # JSON-Schema-style validation rules for CRP config.
242
+ _CONFIG_SCHEMA: list[dict] = [
243
+ {"field": "session_timeout", "type": (int, float), "min_exclusive": 0,
244
+ "error": "session_timeout must be positive"},
245
+ {"field": "max_continuations", "type": (int,), "min": 0,
246
+ "error": "max_continuations must be non-negative int"},
247
+ {"field": "max_ram_mb", "type": (int, float), "min_exclusive": 0,
248
+ "default": 512, "error": "max_ram_mb must be positive"},
249
+ ]
250
+
251
+
252
+ def _validate_config(config: Any) -> None:
253
+ """Schema-driven config validation (step 2).
254
+
255
+ Each rule in ``_CONFIG_SCHEMA`` is checked in order. This keeps
256
+ validation declarative and easy to extend.
257
+ """
258
+ for rule in _CONFIG_SCHEMA:
259
+ fname = rule["field"]
260
+ value = config.get(fname, rule.get("default"))
261
+ if value is None:
262
+ continue # optional field not provided
263
+
264
+ # Type check
265
+ if not isinstance(value, rule["type"]):
266
+ raise ValueError(f"{rule['error']}: got {value!r}")
267
+
268
+ # Range checks
269
+ if "min_exclusive" in rule and value <= rule["min_exclusive"]:
270
+ raise ValueError(f"{rule['error']}: got {value!r}")
271
+ if "min" in rule and value < rule["min"]:
272
+ raise ValueError(f"{rule['error']}: got {value!r}")
@@ -0,0 +1,103 @@
1
+ # Copyright © 2025 Constantinos Vidiniotis. All rights reserved.
2
+ # Licensed under Elastic License 2.0 — see LICENSE.md for details.
3
+ """Continuation engine — wall detection, gap analysis, stitch, completion."""
4
+
5
+ from crp.continuation.completion import (
6
+ CompletionConfig,
7
+ CompletionDetector,
8
+ CompletionResult,
9
+ CompletionSignal,
10
+ SignalState,
11
+ )
12
+ from crp.continuation.degradation import (
13
+ ChainDegradation,
14
+ DegradationMetrics,
15
+ RegroundingResult,
16
+ )
17
+ from crp.continuation.document_map import DocumentMap, HeadingEntry
18
+ from crp.continuation.flow import (
19
+ FlowMetrics,
20
+ InformationFlowMonitor,
21
+ )
22
+ from crp.continuation.gap import (
23
+ GapResult,
24
+ Requirement,
25
+ clear_requirement_cache,
26
+ extract_task_requirements,
27
+ gap_analysis,
28
+ )
29
+ from crp.continuation.manager import (
30
+ ContinuationConfig,
31
+ ContinuationManager,
32
+ ContinuationState,
33
+ DispatchResult,
34
+ )
35
+ from crp.continuation.quality_monitor import (
36
+ GenerationQualityMonitor,
37
+ QualityConfig,
38
+ QualityScore,
39
+ )
40
+ from crp.continuation.stitch import (
41
+ ContentBoundary,
42
+ StitchConfig,
43
+ StitchResult,
44
+ detect_echo,
45
+ stitch_many,
46
+ stitch_outputs,
47
+ )
48
+ from crp.continuation.trigger import (
49
+ TriggerConfig,
50
+ TriggerResult,
51
+ detect_wall_hit,
52
+ evaluate_continuation,
53
+ )
54
+ from crp.continuation.voice import VoiceProfile, extract_voice_profile
55
+
56
+ __all__ = [
57
+ # Trigger
58
+ "TriggerConfig",
59
+ "TriggerResult",
60
+ "detect_wall_hit",
61
+ "evaluate_continuation",
62
+ # Gap
63
+ "GapResult",
64
+ "Requirement",
65
+ "extract_task_requirements",
66
+ "gap_analysis",
67
+ "clear_requirement_cache",
68
+ # Flow
69
+ "InformationFlowMonitor",
70
+ "FlowMetrics",
71
+ # Quality
72
+ "GenerationQualityMonitor",
73
+ "QualityConfig",
74
+ "QualityScore",
75
+ # Completion
76
+ "CompletionDetector",
77
+ "CompletionConfig",
78
+ "CompletionResult",
79
+ "CompletionSignal",
80
+ "SignalState",
81
+ # Stitch
82
+ "StitchConfig",
83
+ "StitchResult",
84
+ "ContentBoundary",
85
+ "detect_echo",
86
+ "stitch_outputs",
87
+ "stitch_many",
88
+ # Voice
89
+ "VoiceProfile",
90
+ "extract_voice_profile",
91
+ # Document Map
92
+ "DocumentMap",
93
+ "HeadingEntry",
94
+ # Degradation
95
+ "ChainDegradation",
96
+ "DegradationMetrics",
97
+ "RegroundingResult",
98
+ # Manager
99
+ "ContinuationManager",
100
+ "ContinuationConfig",
101
+ "ContinuationState",
102
+ "DispatchResult",
103
+ ]