contextgate-core 0.6.0__tar.gz
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.
- contextgate_core-0.6.0/LICENSE +21 -0
- contextgate_core-0.6.0/PKG-INFO +426 -0
- contextgate_core-0.6.0/README.md +395 -0
- contextgate_core-0.6.0/contextgate_core/__init__.py +48 -0
- contextgate_core-0.6.0/contextgate_core/ab_compare.py +566 -0
- contextgate_core-0.6.0/contextgate_core/bridge.py +345 -0
- contextgate_core-0.6.0/contextgate_core/cli.py +560 -0
- contextgate_core-0.6.0/contextgate_core/data_contracts.py +89 -0
- contextgate_core-0.6.0/contextgate_core/downstream.py +165 -0
- contextgate_core-0.6.0/contextgate_core/eval_retrieval.py +173 -0
- contextgate_core-0.6.0/contextgate_core/gate.py +430 -0
- contextgate_core-0.6.0/contextgate_core/gate_bench.py +148 -0
- contextgate_core-0.6.0/contextgate_core/gateway.py +442 -0
- contextgate_core-0.6.0/contextgate_core/hook.py +116 -0
- contextgate_core-0.6.0/contextgate_core/ledger.py +228 -0
- contextgate_core-0.6.0/contextgate_core/mcp_server.py +291 -0
- contextgate_core-0.6.0/contextgate_core/pipeline.py +1756 -0
- contextgate_core-0.6.0/contextgate_core/protocol.py +112 -0
- contextgate_core-0.6.0/contextgate_core/py.typed +0 -0
- contextgate_core-0.6.0/contextgate_core/registry.py +109 -0
- contextgate_core-0.6.0/contextgate_core/repo_indexer.py +1128 -0
- contextgate_core-0.6.0/contextgate_core/token_audit.py +242 -0
- contextgate_core-0.6.0/contextgate_core.egg-info/PKG-INFO +426 -0
- contextgate_core-0.6.0/contextgate_core.egg-info/SOURCES.txt +47 -0
- contextgate_core-0.6.0/contextgate_core.egg-info/dependency_links.txt +1 -0
- contextgate_core-0.6.0/contextgate_core.egg-info/entry_points.txt +5 -0
- contextgate_core-0.6.0/contextgate_core.egg-info/requires.txt +8 -0
- contextgate_core-0.6.0/contextgate_core.egg-info/top_level.txt +1 -0
- contextgate_core-0.6.0/pyproject.toml +49 -0
- contextgate_core-0.6.0/setup.cfg +4 -0
- contextgate_core-0.6.0/tests/test_ab_compare.py +362 -0
- contextgate_core-0.6.0/tests/test_claims.py +40 -0
- contextgate_core-0.6.0/tests/test_cli.py +250 -0
- contextgate_core-0.6.0/tests/test_extension_manifest.py +65 -0
- contextgate_core-0.6.0/tests/test_gate.py +313 -0
- contextgate_core-0.6.0/tests/test_gate_bench.py +93 -0
- contextgate_core-0.6.0/tests/test_gateway.py +286 -0
- contextgate_core-0.6.0/tests/test_gateway_anthropic.py +217 -0
- contextgate_core-0.6.0/tests/test_hook.py +87 -0
- contextgate_core-0.6.0/tests/test_ledger.py +142 -0
- contextgate_core-0.6.0/tests/test_mcp.py +154 -0
- contextgate_core-0.6.0/tests/test_package_layout.py +49 -0
- contextgate_core-0.6.0/tests/test_pipeline.py +41 -0
- contextgate_core-0.6.0/tests/test_protocol.py +78 -0
- contextgate_core-0.6.0/tests/test_public_api.py +104 -0
- contextgate_core-0.6.0/tests/test_release_hygiene.py +275 -0
- contextgate_core-0.6.0/tests/test_repo_indexer.py +531 -0
- contextgate_core-0.6.0/tests/test_security.py +120 -0
- contextgate_core-0.6.0/tests/test_token_audit.py +115 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 NLP-Smarty contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: contextgate-core
|
|
3
|
+
Version: 0.6.0
|
|
4
|
+
Summary: Deterministic, zero-LLM prompt optimizer and repo-intelligence layer (hooks + MCP) for coding agents
|
|
5
|
+
Author: NLP-Smarty contributors
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/KamVinTech/NLP-Smarty
|
|
8
|
+
Project-URL: Repository, https://github.com/KamVinTech/NLP-Smarty
|
|
9
|
+
Project-URL: Issues, https://github.com/KamVinTech/NLP-Smarty/issues
|
|
10
|
+
Keywords: prompt-optimization,token-savings,context-compression,llm-gateway,mcp,deterministic
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Provides-Extra: nlp
|
|
25
|
+
Requires-Dist: spacy; extra == "nlp"
|
|
26
|
+
Requires-Dist: flashtext; extra == "nlp"
|
|
27
|
+
Requires-Dist: rank-bm25; extra == "nlp"
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# ContextGate
|
|
33
|
+
|
|
34
|
+
**A deterministic, zero-LLM gate in front of your LLM calls.** It compresses prose safely, checks that required inputs are present, grounds the prompt in a strict XML structure, audits the response, and records what it saved in a local ledger. Every transform is classical NLP/IR (regex, BM25, TF-IDF, MMR, SimHash); no model, no network call and no `tiktoken` is used inside the engine.
|
|
35
|
+
|
|
36
|
+
> **Naming:** the product and the VS Code extension are **ContextGate**. The GitHub repository is still `NLP-Smarty`; the command-line tool (`smarty`), the Python modules and the `SMARTY_*` environment variables keep their current names until the Python package is renamed.
|
|
37
|
+
|
|
38
|
+
## Contents
|
|
39
|
+
|
|
40
|
+
1. [What it is, and what it is not](#what-it-is-and-what-it-is-not)
|
|
41
|
+
2. [Architecture](#architecture)
|
|
42
|
+
3. [Quickstart](#quickstart)
|
|
43
|
+
4. [Surface 1: gateway proxy](#surface-1-gateway-proxy-smarty-serve)
|
|
44
|
+
5. [Surface 2: repo intelligence for coding agents](#surface-2-repo-intelligence-for-coding-agents-smarty-init)
|
|
45
|
+
6. [Surface 3: VS Code extension](#surface-3-vs-code-extension)
|
|
46
|
+
7. [The optimizer pipeline](#the-optimizer-pipeline-pipelinepy)
|
|
47
|
+
8. [Measured results](#measured-results-what-we-can-and-cannot-claim)
|
|
48
|
+
9. [Safety guarantees](#safety-guarantees)
|
|
49
|
+
10. [Project layout](#project-layout) · [Dependencies](#dependencies) · [Tests](#tests) · [Extending](#extending-the-registry) · [Releasing](#releasing)
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## What it is, and what it is not
|
|
54
|
+
|
|
55
|
+
| It is | It is not |
|
|
56
|
+
|---|---|
|
|
57
|
+
| A deterministic pre-ingestion gate: same input, same output, no model in the loop | A way to cut an agent session's bill by large amounts on its own |
|
|
58
|
+
| Safe-by-default compression with verification and fail-open fallback | A tokenizer: token counts are **estimates** (median ~12% over `cl100k_base`) |
|
|
59
|
+
| A local, counts-only ledger that measures savings on **your** traffic | A guarantee of savings: on well-written text the strict profile saves about 1% |
|
|
60
|
+
|
|
61
|
+
Where the money is: in measured Claude Code sessions the fixed prefix (system prompt, tool definitions) was about 82% of weighted cost, appended context 7.6%, output 10.5% and the typed prompt 0.1%. Prompt-text compression can only touch the small remainder; avoiding whole API calls and shrinking bulky structure matter more. See [Measured results](#measured-results-what-we-can-and-cannot-claim).
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
## Architecture
|
|
66
|
+
|
|
67
|
+
One engine, three surfaces:
|
|
68
|
+
|
|
69
|
+
```
|
|
70
|
+
┌───────────────────────────────────────────────┐
|
|
71
|
+
OpenAI / Anthropic │ gateway.py (stdlib ThreadingHTTPServer) │
|
|
72
|
+
SDKs, Claude Code ───►│ route · parse · relay (SSE incremental) │──► upstream API
|
|
73
|
+
(base URL → :8787) │ │ │ │ (credentials forwarded
|
|
74
|
+
│ ▼ ▼ │ untouched, never stored)
|
|
75
|
+
│ gate.py ledger.py │
|
|
76
|
+
│ protected spans → SQLite, counts only │
|
|
77
|
+
│ compress → verify → est. vs provider │
|
|
78
|
+
│ fall back to original usage calibration │
|
|
79
|
+
└───────────────────────────────────────────────┘
|
|
80
|
+
|
|
81
|
+
Claude Code ─ UserPromptSubmit hook ─► smarty_hook.py ─┐
|
|
82
|
+
Claude Code ─ MCP (optional) ────────► mcp_server.py ──┼─► repo_indexer.py (symbols + line spans,
|
|
83
|
+
│ hash-checked, stdlib only)
|
|
84
|
+
VS Code ── extension.ts ─ JSON-Lines ─► bridge_server.py ─► pipeline.py (9-step optimizer)
|
|
85
|
+
│ ├─ data_contracts.py (typed contracts)
|
|
86
|
+
│ └─ registry.py (tools, few-shots, guardrails, slots)
|
|
87
|
+
└─► downstream.py (optional downstream HF consumer / offline simulator)
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
| Component | File | Responsibility |
|
|
91
|
+
|---|---|---|
|
|
92
|
+
| Gate | `contextgate_core/gate.py` | Protected-span detection, deterministic prose compression (`strict`/`balanced`/`aggressive`), verification with fallback, OpenAI and Anthropic request walkers |
|
|
93
|
+
| Gateway | `contextgate_core/gateway.py` | Local proxy: request validation, gating, streaming relay, response audit, ledger rows |
|
|
94
|
+
| Ledger | `contextgate_core/ledger.py` | Counts-only SQLite ledger; estimator calibration against provider `usage`; `stats` report |
|
|
95
|
+
| Offline bench | `contextgate_core/gate_bench.py` | Replays recorded requests through the gate and reports per-profile, per-transform savings |
|
|
96
|
+
| Optimizer | `contextgate_core/pipeline.py` | 9-step prompt compiler (budgeting, schema compression, MMR/BM25 pruning, intent routing, cache, history pruning), post-LLM `audit_agent_response()` |
|
|
97
|
+
| Contracts | `contextgate_core/data_contracts.py`, `registry.py`, `protocol.py` | Typed dataclasses; static tools, few-shots, guardrails, required slots; protocol and version constants |
|
|
98
|
+
| Repo intelligence | `contextgate_core/repo_indexer.py`, `hook.py`, `mcp_server.py`, `cli.py` | Symbol index, Claude Code hook, MCP server, and the `smarty` CLI (`init`, `doctor`, `uninstall`, `audit`, `serve`, `stats`, `bench`) |
|
|
99
|
+
| VS Code | `src/extension.ts`, `contextgate_core/bridge.py` | Extension client plus persistent JSON-Lines engine sidecar |
|
|
100
|
+
| Measurement | `contextgate_core/token_audit.py`, `ab_compare.py`, `eval_retrieval.py` | Session cost audit, A/B tooling, retrieval-quality evaluation |
|
|
101
|
+
| Downstream demo | `contextgate_core/downstream.py` | HuggingFace consumer with offline simulator, used by the extension's compare view |
|
|
102
|
+
|
|
103
|
+
**Hard rules.** No LLM or network calls and no `tiktoken` in `pipeline.py`, `data_contracts.py` or `registry.py`. The default install has **zero runtime dependencies**; `spacy`, `rank_bm25`, `flashtext` and `scikit-learn` are optional, each with a pure-Python fallback.
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
## Quickstart
|
|
108
|
+
|
|
109
|
+
Python ≥ 3.9. No dependencies are needed for the gateway, hook, MCP server or CLI.
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
git clone https://github.com/KamVinTech/NLP-Smarty && cd NLP-Smarty
|
|
113
|
+
python3 smarty_cli.py --help
|
|
114
|
+
python3 test_harness.py | tail -n 30 # optimizer benchmark + regression suite
|
|
115
|
+
python3 -m pytest -q --tb=short tests # unit and adversarial tests
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Optional extras for the full optimizer: `pip install spacy rank_bm25 flashtext scikit-learn && python -m spacy download en_core_web_sm`.
|
|
119
|
+
`pip install .` installs the distribution `contextgate-core` (import package `contextgate_core`) and the commands `smarty`, `smarty-mcp`, `smarty-hook` and `smarty-gateway`.
|
|
120
|
+
|
|
121
|
+
---
|
|
122
|
+
|
|
123
|
+
## Use as a library
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
from contextgate_core import RawRequest, estimate_tokens, gate_request, gate_text, optimize
|
|
127
|
+
|
|
128
|
+
# 1. Text: deterministic prose compression. Level 1-3 or a profile name ("strict", "balanced", "aggressive").
|
|
129
|
+
text, ok = gate_text("Could you please basically fix `get_user()`, do not use recursion.", "balanced")
|
|
130
|
+
assert ok and text == "Fix `get_user()`, do not use recursion." # ok=False means: `text` is the ORIGINAL, unchanged
|
|
131
|
+
|
|
132
|
+
# 2. Requests: OpenAI-compatible or Anthropic Messages bodies (auto-detected). Never raises, never larger.
|
|
133
|
+
body = {"model": "m", "messages": [{"role": "user", "content": "Could you please basically explain this, in order to be safe?"}]}
|
|
134
|
+
result = gate_request(body, "strict")
|
|
135
|
+
print(result.body, result.saved, result.applied, result.protected_ok) # estimated tokens saved; result.error names a failure
|
|
136
|
+
|
|
137
|
+
# 3. The 9-step prompt compiler: returns a strict XML payload for a downstream agent.
|
|
138
|
+
compiled = optimize(RawRequest(text="Could you please write a Python function to reverse a string without using slicing?"))
|
|
139
|
+
print(compiled.status, compiled.trace.query_token_savings_pct) # "OK" | "NEEDS_CLARIFICATION" | "INSUFFICIENT_CONTEXT"
|
|
140
|
+
|
|
141
|
+
print(estimate_tokens("hello world")) # an estimate (median ~12% over cl100k_base), not a provider count
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
| Name | Does | Notes |
|
|
145
|
+
|---|---|---|
|
|
146
|
+
| `gate_text(text, level=1)` | Compress prose, protected spans verbatim | Returns `(text, ok)`; `ValueError` only for an unknown level |
|
|
147
|
+
| `gate_request(body, profile="strict", api=None)` | Gate a chat request body | Returns `GateResult` (`body`, `raw_tokens`, `fwd_tokens`, `saved`, `applied`, `protected_ok`, `fallbacks`, `error`) |
|
|
148
|
+
| `optimize(RawRequest, few_shot_k=2)` | Compile an XML prompt | `payload_token_savings_pct` is vs a modeled baseline, see [the pipeline](#what-payload_token_savings_pct-means) |
|
|
149
|
+
| `estimate_tokens(text)` | Token estimate | Deterministic, pure Python |
|
|
150
|
+
| `audit_agent_response(text, trace)` | Score a response against the extracted negations and entities | Post-LLM, deterministic |
|
|
151
|
+
| `RawRequest`, `TokenBudget`, `CompiledPrompt`, `OptimizationTrace`, `GateResult`, `PROFILES` | Types and constants | |
|
|
152
|
+
|
|
153
|
+
The package is typed (`py.typed`). `import contextgate_core` is instant: the public names load lazily. The PyPI distribution is
|
|
154
|
+
`contextgate-core` (the unrelated `contextgate` on PyPI also installs an import package named `contextgate`, so we use `contextgate_core` to avoid
|
|
155
|
+
overwriting each other). Not published yet; install from a clone: `pip install .`. Console scripts: `smarty`, `smarty-gateway`, `smarty-mcp`, `smarty-hook`.
|
|
156
|
+
The public names are pinned by `tests/test_public_api.py`, which also executes the example above.
|
|
157
|
+
|
|
158
|
+
---
|
|
159
|
+
|
|
160
|
+
## Surface 1: gateway proxy (`smarty serve`)
|
|
161
|
+
|
|
162
|
+
An OpenAI- and Anthropic-compatible local proxy for any SDK or pipeline.
|
|
163
|
+
|
|
164
|
+
```bash
|
|
165
|
+
python3 smarty_cli.py serve --upstream https://api.openai.com --profile strict # base_url=http://127.0.0.1:8787/v1
|
|
166
|
+
python3 smarty_cli.py serve --upstream https://api.anthropic.com # ANTHROPIC_BASE_URL=http://127.0.0.1:8787
|
|
167
|
+
python3 smarty_cli.py stats [--prices prices.json] [--since 24h] # measured savings ledger
|
|
168
|
+
python3 smarty_cli.py bench traffic.jsonl # offline replay of recorded requests
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Options (`python3 gateway.py -h`): `--host` (default `127.0.0.1`), `--port` (`8787`), `--profile`, `--ledger PATH` / `--no-ledger`, `--record FILE`, `--force-usage` (OpenAI streaming only), `--no-audit`, `--timeout`, `--verbose`, `--allow-remote`.
|
|
172
|
+
|
|
173
|
+
**Profiles**
|
|
174
|
+
|
|
175
|
+
| Profile | Does |
|
|
176
|
+
|---|---|
|
|
177
|
+
| `strict` (default) | Prose of user messages and tool-schema `description` strings only |
|
|
178
|
+
| `balanced` | + hedging words and causal duplicate collapse |
|
|
179
|
+
| `aggressive` | + articles in long prose |
|
|
180
|
+
|
|
181
|
+
**What is rewritten, per API**
|
|
182
|
+
|
|
183
|
+
- OpenAI: user message text and tool-schema descriptions. Tool schemas keep their exact JSON structure.
|
|
184
|
+
- Anthropic `/v1/messages`: only the user's plain-text blocks (not `<system-reminder>` wrappers) and tool/`input_schema` descriptions. `system`, signed `thinking`, `tool_use`, `tool_result` (strict) and `cache_control` are forwarded verbatim. Usage is normalised as fresh + cache read + cache write. `count_tokens` and batches are relayed ungated.
|
|
185
|
+
- Verified by tests against the documented formats and block shapes seen in real request recordings; **not yet verified against live Claude Code traffic**. Per the [Claude Code gateway docs](https://code.claude.com/docs/en/llm-gateway-connect), a base URL alone does not replace a subscription login, and the desktop app ignores `ANTHROPIC_BASE_URL`/`settings.json`; use the CLI or the VS Code extension setting.
|
|
186
|
+
|
|
187
|
+
**Ledger** (`~/.smarty/ledger.db`): counts only, never prompt text, responses, headers or credentials. Savings are original vs forwarded request size with the same estimator, calibrated against the provider's exact `usage`; USD uses a price table you supply. The row is written after the response is sent, so it adds no latency.
|
|
188
|
+
|
|
189
|
+
**Hardening (each has a test in `tests/test_security.py`)**: loopback bind unless `--allow-remote`; origin-form request targets only (no `..`, encoded dot-segments, CR/LF, NUL, backslash); validated `Content-Length` and chunk sizes (size limit checked before reading); `Transfer-Encoding` + `Content-Length` together rejected; 60 s client socket timeout; deeply nested JSON forwarded verbatim; bounded gate work (pathological input skips compression and forwards the original); `--record` file forced to mode 0600; log lines sanitised; warning for plain-http non-loopback upstreams; SIGTERM drains in-flight requests so no ledger row is lost.
|
|
190
|
+
|
|
191
|
+
**Measure before you claim.** Run `serve --record traffic.jsonl`, then `bench traffic.jsonl` on your own traffic to see which transforms apply. `--record` stores original prompts: keep the file private.
|
|
192
|
+
|
|
193
|
+
---
|
|
194
|
+
|
|
195
|
+
## Surface 2: repo intelligence for coding agents (`smarty init`)
|
|
196
|
+
|
|
197
|
+
Zero-LLM, stdlib-only. Indexes your repo (symbols with line spans, hash-checked so spans never go stale) and delivers a small, budgeted `<retrieved_context>` capsule to the agent through a Claude Code `UserPromptSubmit` hook and an optional MCP server.
|
|
198
|
+
|
|
199
|
+
```bash
|
|
200
|
+
python3 smarty_cli.py init --dry-run # preview every change as a diff
|
|
201
|
+
python3 smarty_cli.py init --agents-md # hooks + MCP + index (+ static CLAUDE.md/AGENTS.md block)
|
|
202
|
+
python3 smarty_cli.py doctor # verify end to end
|
|
203
|
+
python3 smarty_cli.py uninstall [--purge] # remove only what init added
|
|
204
|
+
python3 smarty_cli.py audit --last 10 # where do your sessions' tokens go? (reads Claude Code transcripts)
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
- **Two install modes, same command.** From a clone, `init` registers the launcher scripts (`<clone>/smarty_hook.py`); from a pip install it registers `python -m contextgate_core.hook` / `-m contextgate_core.mcp_server` using the interpreter that has the package. `doctor` and `uninstall` recognise both.
|
|
208
|
+
- Hooks go to `.claude/settings.local.json` (machine-specific, git-excluded); `--scope project` shares them. `init` is idempotent, merges into existing JSON (aborts on unparseable files) and keeps one-time backups in `.smarty/backups/`.
|
|
209
|
+
- The hook is fail-open (always exits 0), stdlib-only, never injects the same symbol twice in a session, and stays silent below a confidence gate.
|
|
210
|
+
- MCP tools: `smarty_get_context`, `smarty_find_symbol`, `smarty_find_references`, `smarty_repo_map`, `smarty_get_slice`, plus the optimizer tools (`smarty_optimize`, `smarty_audit_response`, `smarty_compress_context`, `smarty_compress_tool_schema`). The server's agent-facing instructions are **off by default** (in a live test the agent never used the tools even with them); opt in with `SMARTY_MCP_INSTRUCTIONS=on` in the `env` of `.mcp.json`.
|
|
211
|
+
- Retrieval quality: `python3 eval_retrieval.py --golden` (hand-labelled queries) or without flags (git history). Cost audit: `smarty audit` (`token_audit.py`, weights `--w-cw/--w-cr/--w-out`). A/B tooling: `ab_compare.py` (`simulate` and `transcripts`).
|
|
212
|
+
|
|
213
|
+
---
|
|
214
|
+
|
|
215
|
+
## Surface 3: VS Code extension
|
|
216
|
+
|
|
217
|
+
Side-by-side comparison of a raw prompt against the optimized one, plus inline tools. Extension ID `KamVinTech-contextgate.contextgate`; requires VS Code ≥ 1.90.
|
|
218
|
+
|
|
219
|
+
```bash
|
|
220
|
+
npm install && npm run compile # tsc -p ./ ; then press F5 for the Extension Development Host
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
| Command | Mac | Win/Linux | Does |
|
|
224
|
+
|---|---|---|---|
|
|
225
|
+
| `ContextGate: Optimize Prompt & Active File Context` | `Cmd+Alt+O` | `Ctrl+Alt+O` | Runs the optimizer on the selection or a typed prompt, copies the compiled XML, opens the telemetry view |
|
|
226
|
+
| `ContextGate: Open Prompt Diff` | `Cmd+Alt+D` | `Ctrl+Alt+D` | Native diff of old prompt vs optimized core prompt |
|
|
227
|
+
| `ContextGate: Compare Raw vs. Optimized LLM Output` | `Cmd+Alt+C` | `Ctrl+Alt+C` | Runs both prompts on `vscode.lm` (Copilot) or HuggingFace and audits both responses |
|
|
228
|
+
| `ContextGate: Compress Selected Prompt Inline` | `Cmd+Alt+I` | `Ctrl+Alt+I` | Replaces the selection with the compressed `<core_task>` |
|
|
229
|
+
| `ContextGate: Show Logs` | `Cmd+Alt+L` | `Ctrl+Alt+L` | Opens the Output channel |
|
|
230
|
+
|
|
231
|
+
Chat participant: `@contextgate /optimize <prompt>`, `@contextgate /compare <prompt>`, or `@contextgate <prompt>` (defaults to side-by-side comparison).
|
|
232
|
+
|
|
233
|
+
| Setting | Default | Description |
|
|
234
|
+
|---|---|---|
|
|
235
|
+
| `contextGate.pythonPath` | `python3` | Interpreter used for the engine sidecar |
|
|
236
|
+
| `contextGate.engineDirectory` | `""` | Directory containing `bridge_server.py`, `pipeline.py` (empty = the extension root, which bundles the engine) |
|
|
237
|
+
| `contextGate.downstreamBackend` | `auto` | `auto` \| `vscode-lm` \| `huggingface` |
|
|
238
|
+
| `contextGate.huggingFaceToken` / `huggingFaceModel` | `""` / `Qwen/Qwen2.5-Coder-32B-Instruct` | HuggingFace credentials and model |
|
|
239
|
+
| `contextGate.compressionIntensity` | `AUTO` | `AUTO` \| `LIGHT` \| `MEDIUM` \| `AGGRESSIVE` |
|
|
240
|
+
| `contextGate.maxTokenBudget` | `512` | Advisory `max_total_tokens` (not enforced as a total ceiling) |
|
|
241
|
+
| `contextGate.autoShowLogs` / `optimizeOnSave` | `true` / `false` | Reveal the Output panel; refresh the inspector on save |
|
|
242
|
+
| `contextGate.auditLogFile` | `""` | Optional file copy of the audit log. It contains **previews of your prompts**, so nothing is written to disk unless you set this (the Output stream is always on) |
|
|
243
|
+
|
|
244
|
+
**Bridge sidecar (`bridge_server.py`).** A persistent process speaking one JSON object per line on stdin/stdout. Commands: `optimize`, `compare_hf` (pipeline + Raw and Compiled prompts to `contextgate_core/downstream.py`; offline simulator without `HF_TOKEN`), `audit_pair` (audits responses produced by `vscode.lm`), `clear_cache`, `capabilities`, `ping`. Open workspace files are split into chunks of at most 45 words on blank lines and `def`/`class`/`function`/`export`/`interface` boundaries before MMR pruning. Smoke test: `echo '{"id":"1","command":"ping"}' | python3 bridge_server.py`.
|
|
245
|
+
|
|
246
|
+
The extension ships exactly the launcher `bridge_server.py`, the package files `contextgate_core/{__init__,bridge,pipeline,data_contracts,registry,protocol}.py` and the compiled extension (allowlist in `.vscodeignore`, enforced by a test).
|
|
247
|
+
|
|
248
|
+
**Reading the numbers in the UI.** "est. tokens" are the built-in estimator, not provider counts. "vs unpruned template" is measured against a *modeled baseline*, not against the request you would otherwise have sent (see below).
|
|
249
|
+
|
|
250
|
+
---
|
|
251
|
+
|
|
252
|
+
## The optimizer pipeline (`pipeline.py`)
|
|
253
|
+
|
|
254
|
+
`optimize(RawRequest) -> CompiledPrompt` runs a deterministic four-stage flow and compiles a fixed XML template.
|
|
255
|
+
|
|
256
|
+
```python
|
|
257
|
+
from data_contracts import RawRequest, TokenBudget
|
|
258
|
+
from pipeline import optimize
|
|
259
|
+
|
|
260
|
+
result = optimize(RawRequest(
|
|
261
|
+
text="Could you please write a Python function to reverse a string without using slicing?",
|
|
262
|
+
token_budget=TokenBudget(), # per-section budgets
|
|
263
|
+
))
|
|
264
|
+
print(result.status, result.payload) # payload: compiled XML for the downstream agent
|
|
265
|
+
print(result.trace) # OptimizationTrace
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
`status` is `OK`, `NEEDS_CLARIFICATION` (a required slot is missing, so no model call is needed) or `INSUFFICIENT_CONTEXT` (see `data_contracts.py`).
|
|
269
|
+
|
|
270
|
+
| Step | What it does |
|
|
271
|
+
|---|---|
|
|
272
|
+
| 1. Budgeting | `estimate_tokens` (pure-Python BPE-style estimate) and per-section budgets: `core_query_budget`, `context_budget`, `history_budget`, `tools_budget`, `few_shot_budget`. **`max_total_tokens` is advisory, not enforced as a total ceiling** (measured: the compiled payload stays ~629 est. tokens for caps 80–512) |
|
|
273
|
+
| 2. Tool schema compression | Verbose JSON Schema to compact signatures: `tool_name(param:str, opt?:int=5) // desc`. Measured saving 95–120 est. tokens per registry tool (median 97) |
|
|
274
|
+
| 3. MMR + BM25 + TF-IDF pruning | Relevance `0.65 × normalized BM25 + 0.35 × TF-IDF cosine`, then MMR for diversity. Applied to few-shots, tools, RAG chunks, history, workspace chunks |
|
|
275
|
+
| 4. Sentence compressor | `45% BM25 + 35% TF-IDF centroid + 20% positional`; negations, constraints, code, URLs, emails are never pruned. Active only above `core_query_budget` words |
|
|
276
|
+
| 5. Lexical normalization | NFKC, smart quotes, 14 contraction expansions, 10 verbose-idiom rewrites, deterministic stemmer |
|
|
277
|
+
| Stage 2. Intent router | Weighted keywords (multi-word phrases 2.5×, lead-verb bonus), secondary intents, `task_hint` override. Intents: `CODE_GENERATION`, `DATA_EXTRACTION`, `TOOL_EXECUTION`, `FACTUAL_QA`, `AMBIGUOUS_QUERY` |
|
|
278
|
+
| 6. Prompt cache | SHA-256 exact cache plus 64-bit SimHash near-duplicate cache (Hamming ≤ 2), gated on matching intent, negations, entities and context length; 256-entry LRU; `enable_cache=False` bypasses |
|
|
279
|
+
| 7. History pruning | Newest turn always kept; older turns ranked by recency-weighted MMR `(relevance + 0.15) × 0.85^steps_back` within `history_budget` |
|
|
280
|
+
| 8. Adaptive intensity | `AUTO` picks `LIGHT/MEDIUM/AGGRESSIVE` from token pressure; `MEDIUM` strips hedging adverbs; `AGGRESSIVE` strips articles above 25 words |
|
|
281
|
+
| 9. Telemetry | `OptimizationTrace` with query-level and payload-level token counts, savings and per-section detail |
|
|
282
|
+
|
|
283
|
+
**Pre-LLM slot check.** If a required parameter for the detected intent is missing (`REQUIRED_SLOTS`), the pipeline short-circuits before any model call. **Post-LLM audit.** `audit_agent_response()` scores a response against the extracted negations and entities.
|
|
284
|
+
|
|
285
|
+
### Defaults (`TokenBudget`)
|
|
286
|
+
|
|
287
|
+
| Field | Default | Controls |
|
|
288
|
+
|---|---|---|
|
|
289
|
+
| `max_total_tokens` | 512 | Advisory only |
|
|
290
|
+
| `core_query_budget` | 120 | Max words in the compressed query |
|
|
291
|
+
| `context_budget` | 160 | Max tokens of pruned RAG context |
|
|
292
|
+
| `history_budget` | 80 | Max tokens of pruned history |
|
|
293
|
+
| `tools_budget` | 60 | Max tokens of compressed tool schemas |
|
|
294
|
+
| `few_shot_budget` | 90 | Max tokens of selected few-shots |
|
|
295
|
+
|
|
296
|
+
### What `payload_token_savings_pct` means
|
|
297
|
+
|
|
298
|
+
It compares the compiled payload against a **modeled baseline**: the unpruned template containing every registry tool, every few-shot example, every guardrail and all context and history (`_estimate_unoptimized_baseline_tokens`). It is **not** savings versus the request you would otherwise have sent. For short prompts the compiled payload is *larger* than the raw prompt (9–31 raw tokens compile to roughly 350–430 tokens because of the template, guardrails, tools and examples). The prompt-text figure (`query_token_savings_pct`) is the honest per-prompt number.
|
|
299
|
+
|
|
300
|
+
---
|
|
301
|
+
|
|
302
|
+
## Measured results (what we can and cannot claim)
|
|
303
|
+
|
|
304
|
+
| Claim | Evidence |
|
|
305
|
+
|---|---|
|
|
306
|
+
| Strict gate on RAG built from real docs (synthetic framing) | ≈0.9–1.1% request savings |
|
|
307
|
+
| Claude Code hook pilot | ≈-20% weighted cost, 95% CI -44%..+4%, n=4 (**not significant**); -57..60% exploration calls |
|
|
308
|
+
| MCP tools in agent runs | used in 0 of 8 runs |
|
|
309
|
+
| Gate overhead | ≈1 ms mean, ≈5 ms p95 on RAG-sized requests |
|
|
310
|
+
| Optimizer payload vs raw request (8 chunks + 6 turns) | -64% (1868 → 677 est. tokens) |
|
|
311
|
+
| Optimizer payload vs raw short prompt | larger: the template adds ~350–430 tokens |
|
|
312
|
+
| Token estimator vs `cl100k_base` (151 samples) | median +12% over-count (code ~13–16%, JSON ~29%, prose ~7%); ~16% within 3% |
|
|
313
|
+
| Session cost structure | fixed prefix ≈82%, appended context 7.6%, output 10.5%, typed prompt 0.1%; one avoided API call ≈9.3% of a session; cold cache +76% |
|
|
314
|
+
|
|
315
|
+
Cost model used by `smarty audit`: weighted cost = input + 1.25×cache_write + 0.10×cache_read + 5×output (the weights are assumptions; override them on the command line).
|
|
316
|
+
|
|
317
|
+
---
|
|
318
|
+
|
|
319
|
+
## Safety guarantees
|
|
320
|
+
|
|
321
|
+
Each has tests.
|
|
322
|
+
|
|
323
|
+
| Mechanism | Prevents |
|
|
324
|
+
|---|---|
|
|
325
|
+
| Protected spans (fenced/inline code, URLs, emails, paths, identifiers, quoted strings, JSON, digit tokens, negation clauses) | The gate altering anything load-bearing; spans are re-verified after compression, with fallback to the original text |
|
|
326
|
+
| Deterministic, causal transforms | Breaking provider prompt-cache prefixes |
|
|
327
|
+
| Fail-open | A gate bug blocking or corrupting a request: the exact original bytes are forwarded |
|
|
328
|
+
| Never forward a larger request | Negative savings |
|
|
329
|
+
| Negation-safe compression; negation spans kept verbatim in `<task_metadata>` | Dropping `not`, `never`, `without`, `unless`, `neither`, `nor` |
|
|
330
|
+
| `<extracted_entities>` block | Mutation of exact dates, emails, URLs, quoted strings |
|
|
331
|
+
| Pre-LLM slot check | Spending tokens when a required parameter is missing |
|
|
332
|
+
| SimHash cache safety gate | Near-duplicate hits when intent, negations or entities differ |
|
|
333
|
+
| Abstention rule in the template (`STATUS: INSUFFICIENT_CONTEXT`) | The agent fabricating when data is missing |
|
|
334
|
+
| XML tag sanitization | User input injecting or overriding reserved template tags |
|
|
335
|
+
| Credentials forwarded untouched, never logged or stored; counts-only ledger | Secret and prompt leakage through the gateway |
|
|
336
|
+
|
|
337
|
+
---
|
|
338
|
+
|
|
339
|
+
## Project layout
|
|
340
|
+
|
|
341
|
+
```
|
|
342
|
+
NLP-Smarty/
|
|
343
|
+
├── contextgate_core/ # the importable package (this is all the wheel installs)
|
|
344
|
+
│ ├── gate.py gateway.py ledger.py gate_bench.py # gateway surface
|
|
345
|
+
│ ├── pipeline.py data_contracts.py registry.py protocol.py # optimizer + contracts
|
|
346
|
+
│ ├── repo_indexer.py hook.py mcp_server.py cli.py # repo-intelligence surface
|
|
347
|
+
│ ├── bridge.py downstream.py # VS Code sidecar, optional HF consumer
|
|
348
|
+
│ └── token_audit.py ab_compare.py eval_retrieval.py # measurement
|
|
349
|
+
├── smarty_cli.py smarty_hook.py mcp_server.py bridge_server.py gateway.py ... # thin root launchers (see below)
|
|
350
|
+
├── src/extension.ts # VS Code extension
|
|
351
|
+
├── test_harness.py tests/ # benchmark + pytest suites
|
|
352
|
+
├── tools/ (bump_version.py, check_release.py) · docs/RESTRUCTURE.md
|
|
353
|
+
├── .github/workflows/ (ci.yml, release.yml)
|
|
354
|
+
└── package.json pyproject.toml tsconfig.json .vscodeignore
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
The root scripts are 10-line launchers that call the package (`python smarty_hook.py` runs `contextgate_core.hook`). They exist because `smarty init`
|
|
358
|
+
registers absolute script paths and recognises its own entries by filename, and the extension spawns `bridge_server.py`; they keep existing installs working.
|
|
359
|
+
They are not part of the wheel. Rationale and remaining phases: [`docs/RESTRUCTURE.md`](docs/RESTRUCTURE.md).
|
|
360
|
+
|
|
361
|
+
## Dependencies
|
|
362
|
+
|
|
363
|
+
| Package | Purpose | Fallback |
|
|
364
|
+
|---|---|---|
|
|
365
|
+
| none (stdlib) | Gateway, gate, ledger, hook, MCP, CLI, indexer | n/a |
|
|
366
|
+
| `spacy` + `en_core_web_sm` (NER disabled) | POS tagging, root verb extraction | Regex sentence splitting + `_KNOWN_TASK_VERBS` |
|
|
367
|
+
| `rank_bm25` | BM25 scoring | Built-in `_FastBM25Okapi` |
|
|
368
|
+
| `scikit-learn` | TF-IDF utilities | Built-in sparse TF-IDF + cosine |
|
|
369
|
+
| `flashtext` | Keyword matching | Weighted regex patterns |
|
|
370
|
+
| `huggingface_hub` | Live HF calls in `contextgate_core/downstream.py` | `urllib` HTTP, then offline simulator |
|
|
371
|
+
|
|
372
|
+
Extension build: `typescript ^5.4.0`, `@types/vscode ^1.90.0`, `@types/node ^20.0.0`.
|
|
373
|
+
|
|
374
|
+
## Tests
|
|
375
|
+
|
|
376
|
+
| Command | Covers |
|
|
377
|
+
|---|---|
|
|
378
|
+
| `python3 -m pytest -q --tb=short tests` | Gate fuzzing and prefix stability, gateway (OpenAI + Anthropic), adversarial inputs (`test_security.py`), ledger, hook, MCP, CLI, release hygiene, extension manifest, README claims guard (`test_claims.py`) |
|
|
379
|
+
| `python3 test_harness.py \| tail -n 30` | Optimizer benchmark (5 baseline prompts) and 7 regression checks: normalization, extractive compression, MMR context pruning, history pruning, schema compression, cache hit on paraphrase, missing-slot short-circuit |
|
|
380
|
+
| `python3 tools/check_release.py` | Version alignment, no junk tracked, packaging audit |
|
|
381
|
+
| `npm run compile` | Extension type-check |
|
|
382
|
+
|
|
383
|
+
## Extending the registry
|
|
384
|
+
|
|
385
|
+
Edit `registry.py`; `pipeline.py` needs no changes. The registry currently holds 4 tools, 6 few-shot examples and 3 guardrails.
|
|
386
|
+
|
|
387
|
+
```python
|
|
388
|
+
TOOL_REGISTRY.append({
|
|
389
|
+
"id": "query_database",
|
|
390
|
+
"trigger_keywords": ["database", "db", "table", "select", "insert"],
|
|
391
|
+
"schema": json.dumps({
|
|
392
|
+
"name": "query_database",
|
|
393
|
+
"description": "Executes a read-only SQL query against the database.",
|
|
394
|
+
"parameters": {"type": "object",
|
|
395
|
+
"properties": {"sql": {"type": "string", "description": "SQL SELECT statement"},
|
|
396
|
+
"limit": {"type": "integer", "description": "Max rows to return", "default": 100}},
|
|
397
|
+
"required": ["sql"]},
|
|
398
|
+
}),
|
|
399
|
+
})
|
|
400
|
+
|
|
401
|
+
FEW_SHOT_EXAMPLES.append({
|
|
402
|
+
"id": "ex_code_gen_3", "intent": "CODE_GENERATION",
|
|
403
|
+
"input": "Write a binary search function in Python",
|
|
404
|
+
"output": "def binary_search(arr, target):\n lo, hi = 0, len(arr)-1\n ...",
|
|
405
|
+
})
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
## Releasing
|
|
409
|
+
|
|
410
|
+
Versions live in four places (`pyproject.toml`, `protocol.py`, `package.json`, `package-lock.json`); never edit them by hand:
|
|
411
|
+
|
|
412
|
+
```bash
|
|
413
|
+
python3 tools/bump_version.py 0.7.0 # updates all four and verifies them
|
|
414
|
+
git commit -am "release 0.7.0" && git tag v0.7.0 && git push origin main v0.7.0
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
Pushing the tag runs [`release.yml`](.github/workflows/release.yml): verify (versions match the tag, no junk tracked, tests) → build wheel + sdist and the `.vsix` (audited by `tools/check_release.py`; the packaged engine is smoke-tested) → GitHub Release with all artifacts attached. **Actions → Release → Run workflow** is a dry run that builds and checks everything and publishes nothing.
|
|
418
|
+
|
|
419
|
+
One-time setup for publishing (nothing publishes until you do these):
|
|
420
|
+
|
|
421
|
+
- **VS Code Marketplace:** the publisher ID must equal `publisher` in `package.json` (`KamVinTech-contextgate`) and is permanent once created. Add a credential as the repository secret `VSCE_PAT` (scope *Marketplace > Manage*). Global Azure DevOps tokens retire on 2026-12-01; later releases need Microsoft Entra ID (`vsce publish --azure-credential`). The Marketplace step is **opt-in**: it runs only when the repository variable `PUBLISH_MARKETPLACE=true` is set (and `VSCE_PAT` exists); otherwise it is skipped and the `.vsix` is still attached to the GitHub Release.
|
|
422
|
+
- **PyPI (opt-in):** the distribution is `contextgate-core`. One-time setup on pypi.org: *Publishing → Add a pending publisher* (project `contextgate-core`, owner `KamVinTech`, repository `NLP-Smarty`, workflow `release.yml`, environment `pypi`); create the GitHub environment `pypi`; set the repository variable `PUBLISH_PYPI=true`. No API token is stored anywhere. The first tag after that publishes it.
|
|
423
|
+
|
|
424
|
+
## Privacy and license
|
|
425
|
+
|
|
426
|
+
The engine writes an audit log of prompt previews only when `SMARTY_AUDIT_LOG=<path>` is set; by default nothing is persisted. The gateway ledger stores counts only. License: MIT (see `LICENSE`).
|