@ictechgy/context-guard 0.4.9 → 0.4.10
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.
- package/CHANGELOG.md +16 -0
- package/README.ko.md +41 -24
- package/README.md +66 -26
- package/docs/benchmark-fixtures/token-savings-12task-baseline.prompt.example.md +7 -0
- package/docs/benchmark-fixtures/token-savings-12task-contextguard.prompt.example.md +7 -0
- package/docs/benchmark-fixtures/token-savings-12task.tasks.example.json +182 -0
- package/docs/benchmark-fixtures/token-savings-12task.variants.example.json +10 -0
- package/docs/distribution.md +10 -7
- package/docs/experimental-benchmark-fixtures.md +8 -1
- package/package.json +3 -6
- package/packaging/homebrew/context-guard.rb.template +1 -1
- package/plugins/context-guard/.claude-plugin/plugin.json +1 -1
- package/plugins/context-guard/README.ko.md +9 -6
- package/plugins/context-guard/README.md +21 -13
- package/plugins/context-guard/bin/context-guard +113 -26
- package/plugins/context-guard/bin/context-guard-artifact +542 -46
- package/plugins/context-guard/bin/context-guard-cache-score +380 -0
- package/plugins/context-guard/bin/context-guard-compress +146 -1
- package/plugins/context-guard/bin/context-guard-cost +783 -4
- package/plugins/context-guard/bin/context-guard-experiments +99 -18
- package/plugins/context-guard/bin/context-guard-failed-nudge +3 -0
- package/plugins/context-guard/bin/context-guard-filter +163 -7
- package/plugins/context-guard/bin/context-guard-guard-read +3 -0
- package/plugins/context-guard/bin/context-guard-pack +602 -43
- package/plugins/context-guard/bin/context-guard-rewrite-bash +3 -0
- package/plugins/context-guard/bin/context-guard-setup +165 -31
- package/plugins/context-guard/bin/context-guard-statusline +490 -283
- package/plugins/context-guard/bin/context-guard-statusline-merged +5 -0
- package/plugins/context-guard/bin/context-guard-tool-prune +241 -1
- package/plugins/context-guard/lib/context_guard_commands.py +206 -0
- package/plugins/context-guard/skills/setup/SKILL.md +1 -0
- package/context-guard-kit/README.md +0 -91
- package/context-guard-kit/benchmark_runner.py +0 -2401
- package/context-guard-kit/claude_transcript_cost_audit.py +0 -2346
- package/context-guard-kit/context_compress.py +0 -695
- package/context-guard-kit/context_escrow.py +0 -935
- package/context-guard-kit/context_filter.py +0 -637
- package/context-guard-kit/context_guard_cli.py +0 -325
- package/context-guard-kit/context_guard_diet.py +0 -1711
- package/context-guard-kit/context_pack.py +0 -2713
- package/context-guard-kit/cost_guard.py +0 -2349
- package/context-guard-kit/experimental_registry.py +0 -4348
- package/context-guard-kit/failed_attempt_nudge.py +0 -567
- package/context-guard-kit/guard_large_read.py +0 -690
- package/context-guard-kit/hook_secret_patterns.py +0 -43
- package/context-guard-kit/read_symbol.py +0 -483
- package/context-guard-kit/rewrite_bash_for_token_budget.py +0 -501
- package/context-guard-kit/sanitize_output.py +0 -725
- package/context-guard-kit/settings.example.json +0 -67
- package/context-guard-kit/setup_wizard.py +0 -2515
- package/context-guard-kit/statusline.sh +0 -362
- package/context-guard-kit/statusline_merged.sh +0 -157
- package/context-guard-kit/tool_schema_pruner.py +0 -837
- package/context-guard-kit/trim_command_output.py +0 -1449
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,22 @@ All notable changes for the ContextGuard plugin are documented here.
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [0.4.10] - 2026-06-14
|
|
8
|
+
|
|
9
|
+
- Added `context-guard-artifact search`, a local sanitized artifact sandbox search that returns capped literal matches with exact `get --lines` rehydration commands and no hosted savings claims.
|
|
10
|
+
- Added `context-guard-pack suggest/auto --adaptive-k`, an opt-in local shrink/expand top-k advisory that reports score-distribution, byte-budget fit, and score-mass recall/precision proxies without changing manifests, packs, receipts, or claiming provider-token savings.
|
|
11
|
+
- Added `context-guard-pack auto --symbol-memory`, an opt-in repo-map-derived symbol/graph advisory with exact source verification hints that does not change manifests, packs, receipts, or provider-savings claims.
|
|
12
|
+
- Added `context-guard-compress --mode readable`, an opt-in sanitized-prose readable preview mode with high-risk protected/prompt-like signal blocking, exact fallback guidance, and no learned compressor/model/embedding/reranker execution.
|
|
13
|
+
- Added `context-guard-cache-score`, a static local prompt cacheability lint with char/4 proxy labeling, provider caveats, dynamic-prefix warnings, and no provider calls, ledger writes, or savings claims.
|
|
14
|
+
- Extended `context-guard-tool-prune` with `defer-report` for core-vs-deferred tool schema planning backed by the existing sanitized receipt/payload retrieval path.
|
|
15
|
+
- Added a fixture-only token-savings 12-task benchmark starter and executable report-shape tests that preserve matched-task, shifted-cost, and proxy-byte claim boundaries.
|
|
16
|
+
- Hardened release gates with isolated npm install smoke, CI Node setup, full unittest discovery, Homebrew template stale-version checks, and explicit CI/subprocess timeouts.
|
|
17
|
+
- Hardened `context-guard experiments serve local-proxy` with a private ready-file nonce handoff that rejects missing, duplicate, or invalid nonce headers before forwarding and keeps the raw nonce out of public output and upstream requests.
|
|
18
|
+
- Hardened `context-guard-filter` config loading with bounded no-follow regular-file reads, nonblocking FIFO/device rejection, and fail-closed unsupported-platform checks.
|
|
19
|
+
- Hardened artifact escrow writes with parent-traversal rejection, dir-fd/no-follow private directories, 0600 temp files before atomic replace, and explicit pre/post-replace fsync failure semantics.
|
|
20
|
+
- Disabled setup helper `PATH` fallback by default; trusted fallback now requires `--allow-path-helper-fallback`, canonical no-symlink executable paths, and a bounded helper identity probe.
|
|
21
|
+
- Polished README, Korean README, and GitHub Pages copy after Claude review while preserving local-only/passive boundaries, install-vs-activation separation, and conservative token/cost claim wording.
|
|
22
|
+
|
|
7
23
|
## [0.4.9] - 2026-06-12
|
|
8
24
|
|
|
9
25
|
- Added `context-guard experiments plan local-proxy-external-forwarding`, a design-only dry-run gate for future external forwarding proposals with explicit intent, HTTPS allowlist, threat model notes, credential redaction policy, provider-evidence boundary, and no DNS lookup, external service call, traffic forwarding, credential persistence, or hosted savings claim.
|
package/README.ko.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# ContextGuard
|
|
2
2
|
|
|
3
|
-
ContextGuard는 AI 코딩·도구 에이전트를 위한 로컬 우선 컨텍스트 관리 도구 모음입니다. Claude Code 플러그인으로 먼저
|
|
3
|
+
ContextGuard는 AI 코딩·도구 에이전트를 위한 로컬 우선 컨텍스트 관리 도구 모음입니다. Claude Code 플러그인으로 먼저 제공되며, 한 번 설치한 뒤 프로젝트별로 명시적으로 활성화하고 필요하면 되돌릴 수 있습니다. 출력 축약, 심볼 단위 읽기, 반복 실패 알림, 민감정보 패턴 가림, 사용량 측정 가드레일은 로컬 헬퍼 명령과 brief 모드 안내 규칙 스니펫을 통해 다른 에이전트에서도 재사용할 수 있습니다.
|
|
4
4
|
|
|
5
5
|
- 영문 문서: [`README.md`](README.md)
|
|
6
6
|
- HTML 랜딩 페이지: [GitHub Pages](https://ictechgy.github.io/context-guard/) ([소스](docs/index.html))
|
|
@@ -13,7 +13,7 @@ ContextGuard는 AI 코딩·도구 에이전트를 위한 로컬 우선 컨텍스
|
|
|
13
13
|
| --- | --- | --- |
|
|
14
14
|
| Claude Code | `/plugin marketplace add ictechgy/context-guard` 후 `/plugin install context-guard@context-guard` | 프로젝트에서 `/context-guard:setup` 실행 |
|
|
15
15
|
| Codex CLI 또는 터미널 기반 에이전트 | `npm install -g @ictechgy/context-guard` 또는 일회성 `npx @ictechgy/context-guard ...` | `context-guard setup --agent codex --scope project --with-init --with-skill --plan` 확인 후 `--yes`로 적용 |
|
|
16
|
-
| Gemini/Cursor/Windsurf/Cline/Copilot | npm/npx 설치 | 원하는 에이전트만 `context-guard setup --agent ... --scope project --with-init --plan`으로 확인 후 적용 |
|
|
16
|
+
| Gemini/Cursor/Windsurf/Cline/Copilot | 위 npm/npx 설치 경로 사용 | 원하는 에이전트만 `context-guard setup --agent ... --scope project --with-init --plan`으로 확인 후 적용 |
|
|
17
17
|
| macOS/Homebrew 사용자 | 배포 경로: `brew install ictechgy/tap/context-guard` | 설치 후 같은 `context-guard setup ...` 명령 사용 |
|
|
18
18
|
|
|
19
19
|
자주 쓰는 명령은 다음과 같습니다.
|
|
@@ -27,13 +27,13 @@ context-guard setup --agent claude --scope user --verify --json # 읽기 전용
|
|
|
27
27
|
context-guard setup --agent claude --scope user --plan
|
|
28
28
|
```
|
|
29
29
|
|
|
30
|
-
기본값은 프로젝트 단위 설정입니다. 사용자 단위 설정은 명시적으로 선택해야 하며, 실제 변경을 적용하려면 `--yes`와 명시적인 `--agent`가 필요합니다. 지원되는 사용자 단위 변경은 백업과 되돌리기 기록을 남기며, 패키지 설치 중에는 실행되지 않습니다.
|
|
30
|
+
기본값은 프로젝트 단위 설정입니다. 사용자 단위 설정은 명시적으로 선택해야 하며, 실제 변경을 적용하려면 `--yes`와 명시적인 `--agent`가 필요합니다. 지원되는 사용자 단위 변경은 백업과 되돌리기 기록을 남기며, 패키지 설치 중에는 실행되지 않습니다. setup은 먼저 패키지/체크아웃 내부 헬퍼를 찾습니다. 신뢰할 수 있는 설치임을 확인한 경우에만 `--allow-path-helper-fallback`으로 `PATH` 헬퍼 fallback을 허용하세요.
|
|
31
31
|
|
|
32
32
|
ContextGuard는 절감 수치를 과장하지 않습니다. 흔히 컨텍스트를 불필요하게 키우는 원인을 줄이고, 실제 전후 비교 결과는 각자의 작업에서 측정할 수 있도록 벤치마크 도구를 제공합니다. 저장소마다 효과는 달라질 수 있으며, 고정된 토큰·비용 절감률은 보장하지 않습니다.
|
|
33
33
|
|
|
34
34
|
## Claude Code 우선, 다른 에이전트도 함께
|
|
35
35
|
|
|
36
|
-
|
|
36
|
+
Claude 사용자는 Claude Code 플러그인으로 시작하는 것이 가장 빠릅니다. 설치 후에는 같은 로컬 우선 가드레일을 다음 방식으로 다른 AI 코딩·도구 에이전트에서도 재사용할 수 있습니다.
|
|
37
37
|
|
|
38
38
|
- **로컬 헬퍼 명령**(`context-guard-*`)은 특정 에이전트에 묶이지 않은 일반 셸 명령으로 실행됩니다.
|
|
39
39
|
- **brief 모드 스니펫**은 에이전트의 지시 파일(`AGENTS.md`, `GEMINI.md`, `.cursorrules`, Copilot 지시 파일 등)에 마커 블록으로 설치하고, 블록을 지우면 제거됩니다.
|
|
@@ -73,10 +73,10 @@ ContextGuard는 provider 캐시, semantic cache, 프롬프트 압축 도구를
|
|
|
73
73
|
|
|
74
74
|
| 도구 유형 | 줄이는 방식 | ContextGuard와의 관계 |
|
|
75
75
|
| --- | --- | --- |
|
|
76
|
-
| Provider prompt/context caching | 안정적인 프롬프트 앞부분을 재사용합니다. | 보완 관계입니다. ContextGuard는 자주 바뀌는 컨텍스트 뒷부분을 더 작고 깨끗하게 유지하도록 돕고, `context-guard-audit`로 배치를
|
|
76
|
+
| Provider prompt/context caching | 안정적인 프롬프트 앞부분을 재사용합니다. | 보완 관계입니다. ContextGuard는 자주 바뀌는 컨텍스트 뒷부분을 더 작고 깨끗하게 유지하도록 돕고, `context-guard-audit`로 프롬프트 배치를 점검하며, `context-guard cost`로 Anthropic 요청이 cache read 대신 cache write가 될 가능성을 미리 알릴 수 있습니다. |
|
|
77
77
|
| Semantic response cache | 같거나 비슷한 요청의 이전 답변을 재사용합니다. | 보완 관계입니다. ContextGuard는 AI 답변 캐시를 제공하지 않습니다. |
|
|
78
78
|
| 프롬프트/컨텍스트 압축 | 이미 선택된 텍스트를 더 짧게 만듭니다. | 인접한 역할입니다. ContextGuard는 로컬 출력 축약과 요약을 제공하지만, 무손실 의미 압축을 보장하지 않습니다. |
|
|
79
|
-
| 실험 planner/runtime | local proxy
|
|
79
|
+
| 실험 planner/runtime | local proxy는 dry-run plan, external-forwarding design plan, gate record, one-shot loopback forwarding MVP로만 검토합니다. context-diff, visual evidence-pack, learned-compression, self-hosted metrics도 명시적 로컬 런타임만 지원합니다. | 모두 기본 비활성이며 명시적 명령이 필요합니다. `record`는 listener·traffic forwarding·DNS lookup을 시작하지 않고, `serve local-proxy`는 literal loopback IP로 제한된 1회 요청만 bind/forward합니다. 별도 근거 gate와 future PR gate 없이는 model/compressor 실행, OCR/crop service, external forwarding, credential persistence, hosted API 절감 주장으로 보지 않습니다. 자세한 내용은 “실험 기능 opt-in 관리” 섹션을 참고하세요. |
|
|
80
80
|
| ContextGuard | 불필요한 파일, 로그, 반복 실패, 과도한 출력이 에이전트 컨텍스트에 들어가기 전에 줄어들도록 돕습니다. | 로컬 가드레일, 되돌릴 수 있는 로컬 보관본, 측정 도구입니다. |
|
|
81
81
|
|
|
82
82
|
설계에 참고한 관련 패턴은 다음과 같습니다.
|
|
@@ -87,7 +87,7 @@ ContextGuard는 provider 캐시, semantic cache, 프롬프트 압축 도구를
|
|
|
87
87
|
| 여러 에이전트의 간결 출력 규칙 | 여러 에이전트에 brief 모드 출력 규칙을 한꺼번에 설치합니다. | ContextGuard는 안내용 brief 모드 스니펫과 dry-run 에이전트 간 설정을 제공합니다. 프로젝트별 opt-in이며, 절감을 보장하지 않습니다. |
|
|
88
88
|
| ContextGuard | 불필요한 파일·로그·출력이 컨텍스트에 들어가기 전에 줄어들도록 돕고 보수적으로 측정합니다. | 로컬 가드레일, 되돌릴 수 있는 로컬 보관본·재조회, 직접 측정하는 벤치마크 근거입니다. |
|
|
89
89
|
|
|
90
|
-
## brief 모드 (
|
|
90
|
+
## brief 모드 (안내용)
|
|
91
91
|
|
|
92
92
|
brief 모드는 코딩 에이전트가 군더더기를 줄이도록 요청하되, 리뷰에 필요한 증거(파일 경로, 명령, 명령 출력과 오류, 코드 블록, 검증 상태, 변경 파일, 남은 과제, 주의사항)는 유지하게 돕는 에이전트 중립·안내용 규칙 스니펫 모음입니다. 강제가 아니라 최선 노력 안내이며, 토큰·비용 절감을 **보장하지 않습니다.**
|
|
93
93
|
|
|
@@ -112,8 +112,8 @@ brief 모드는 코딩 에이전트가 군더더기를 줄이도록 요청하되
|
|
|
112
112
|
- 모델 토큰을 줄이기 위해 작업을 외부 AI 서비스로 전송하지 않습니다.
|
|
113
113
|
- 설치만으로 전역 Claude 설정을 변경하지 않습니다.
|
|
114
114
|
- 절감 수치가 필요할 때 직접 전후 비교 측정을 대신하지 않습니다.
|
|
115
|
-
- 로컬 RAM/디스크 보관본은 다음에 보낼 컨텍스트를 줄이는 데
|
|
116
|
-
- 실험 헬퍼는 대부분 dry-run 안전성 checker/planner이며 design-only external-forwarding opt-in gate를 포함합니다. 명시적 로컬 runtime은 caller-supplied context-diff replacement payload, caller-supplied visual crop/OCR evidence pack, caller-supplied learned-compression prose candidate, self-hosted metrics JSONL sidecar 기록, local-proxy runtime-gate JSONL 기록, one-shot `serve local-proxy` loopback forwarding과 successful forwarded request용 optional shifted-cost diagnostic JSONL row만 제공합니다.
|
|
115
|
+
- 로컬 RAM/디스크 보관본은 다음에 보낼 컨텍스트를 줄이는 데 도움이 될 수 있지만 Anthropic provider prompt cache를 대체하거나 cache hit를 보장하지 않습니다. 배포나 청구 설명 전에는 Anthropic prompt caching/pricing 문서를 다시 확인하세요: https://docs.anthropic.com/en/build-with-claude/prompt-caching 및 https://platform.claude.com/docs/en/about-claude/pricing.
|
|
116
|
+
- 실험 헬퍼는 대부분 dry-run 안전성 checker/planner이며 design-only external-forwarding opt-in gate를 포함합니다. 명시적 로컬 runtime은 caller-supplied context-diff replacement payload, caller-supplied visual crop/OCR evidence pack, caller-supplied learned-compression prose candidate, self-hosted metrics JSONL sidecar 기록, local-proxy runtime-gate JSONL 기록, private ready-file nonce가 필요한 one-shot `serve local-proxy` loopback forwarding과 successful forwarded request용 optional shifted-cost diagnostic JSONL row만 제공합니다.
|
|
117
117
|
- ContextGuard는 learned/synthetic compressor 실행·embedding·reranker·model call·생성형 replacement, screenshot 캡처·image crop·OCR 실행·image parsing·외부 OCR/image service, 명시적 local metrics 기록을 넘어선 self-hosted KV/latent inference optimization runtime, literal-loopback 1회 HTTP forwarding과 credential 차단을 넘어선 proxy forwarding은 제공하지 않습니다.
|
|
118
118
|
- 예전 `/claude-token-optimizer:*` Claude Code 슬래시 명령을 별칭으로 제공하지 않습니다. 설치 후에는 `/context-guard:*`를 사용하세요.
|
|
119
119
|
|
|
@@ -131,17 +131,17 @@ brief 모드는 코딩 에이전트가 군더더기를 줄이도록 요청하되
|
|
|
131
131
|
| 출력 축약과 민감정보 가림 | 테스트·빌드·검색·diff 출력을 작게 만들고, 에이전트 컨텍스트에 들어가기 전에 민감해 보이는 값을 가립니다. |
|
|
132
132
|
| 선언형 출력 필터 | 사용자 정의 JSON DSL로 성공 출력만 명시적으로 줄이고, 보호해야 하는 실패 출력은 원문 stdout/stderr와 종료 코드를 보존합니다. |
|
|
133
133
|
| 로컬 로그 보관소 | 큰 로그를 대화 밖 로컬 저장소에 보관하고, 요약 정보나 요청한 줄 범위만 다시 가져옵니다. |
|
|
134
|
-
| Anthropic 비용 가드 | `context-guard cost preflight/observe/ledger/compile`이 cache 위험과 비용 범위를
|
|
135
|
-
| 예산 기반 컨텍스트 패커 | 우선순위가 있는 로컬 파일 근거를 바이트 예산 안의 Markdown 팩으로 조립하고, 로컬 신호에서 `build`용 manifest를 추천하며, `--explain
|
|
134
|
+
| Anthropic 비용 가드 | `context-guard cost preflight/observe/ledger/compile`이 cache 위험과 비용 범위를 추정합니다. `context-guard route-advisor`는 로컬 총비용과 batchability route 후보를 요약하며, ledger를 쓸 때도 원문 대신 keyed HMAC fingerprint만 저장합니다. `--enforce`를 명시하지 않으면 경고만 합니다. |
|
|
135
|
+
| 예산 기반 컨텍스트 패커 | 우선순위가 있는 로컬 파일 근거를 바이트 예산 안의 Markdown 팩으로 조립하고, 로컬 신호에서 `build`용 manifest를 추천하며, `--explain`, `--adaptive-k`, `--symbol-memory`로 로컬 자문 메타데이터를 덧붙일 수 있습니다. |
|
|
136
136
|
| Tool/MCP schema pruner | 로컬 catalog에서 bounded top-k tool/schema 자문 리포트를 만들고, compact 요약 기록과 전체 가림 처리된 payload 재조회 경로를 남깁니다. |
|
|
137
|
-
| 보수적 stdin 압축기 | 선택한 JSON, diff, 로그, 검색 출력, 코드, 산문을 줄이고, 관측 바이트 근거와 추정 토큰 proxy를 함께 표시합니다. |
|
|
137
|
+
| 보수적 stdin 압축기 | 선택한 JSON, diff, 로그, 검색 출력, 코드, 산문을 줄이고, 관측 바이트 근거와 추정 토큰 proxy를 함께 표시합니다. `--mode readable`은 exact fallback 안내가 있는 opt-in 산문 preview를 추가합니다. |
|
|
138
138
|
| 보호 영역 정책 기록 | `context-guard-compress --protected-policy`와 `context-guard cost compile`이 코드·diff·path·hash·JSON/literal zone을 structural-only 변환 대상으로 표시하고 정확한 재조회 경계를 남깁니다. |
|
|
139
139
|
| 반복 실패 알림 | Bash 실패가 반복되면 실패 로그가 컨텍스트를 채우기 전에 전략을 바꾸도록 안내합니다. |
|
|
140
140
|
| 상태표시줄, 감사, 벤치마크 | 컨텍스트·캐시·비용 신호를 보여주고, 사용량과 캐시 친화성 집중 지점을 찾고, 보수적인 전후 비교 증거를 남깁니다. |
|
|
141
141
|
|
|
142
142
|
### 비용 가드 키 준비
|
|
143
143
|
|
|
144
|
-
비용 가드의 로컬 HMAC 키는 기본적으로 `.context-guard/cost-ledger/hmac.key`에 자동 생성됩니다. 관리자가 직접 주입하는 경우 파일에는 필수 padding을 포함한 canonical URL-safe base64 32바이트 키만 정확히 들어 있어야 하며, trailing newline이나 공백은
|
|
144
|
+
비용 가드의 로컬 HMAC 키는 기본적으로 `.context-guard/cost-ledger/hmac.key`에 자동 생성됩니다. 관리자가 직접 주입하는 경우 파일에는 필수 padding을 포함한 canonical URL-safe base64 32바이트 키만 정확히 들어 있어야 하며, trailing newline이나 공백은 허용되지 않습니다. 리포트는 키와 원문 프롬프트를 출력하지 않으며, 로컬 ledger는 Anthropic/provider prompt cache를 대체하지 않습니다.
|
|
145
145
|
|
|
146
146
|
## Claude Code에서 설치
|
|
147
147
|
|
|
@@ -166,11 +166,11 @@ brief 모드는 코딩 에이전트가 군더더기를 줄이도록 요청하되
|
|
|
166
166
|
| `/context-guard:optimize` | 컨텍스트 가드레일을 점검하고 조정합니다. |
|
|
167
167
|
| `/context-guard:audit` | 로컬 Claude 대화 기록의 토큰·비용 집중 지점을 확인합니다. |
|
|
168
168
|
|
|
169
|
-
설정은 명시적이며, 프로젝트 단위로 적용되고, 되돌릴 수 있습니다. ContextGuard는 외부
|
|
169
|
+
설정은 명시적이며, 프로젝트 단위로 적용되고, 되돌릴 수 있습니다. ContextGuard는 외부 모델로 작업을 위임하거나 외부에서 실행되도록 설정하지 않으며, 모든 헬퍼 명령은 로컬에서 동작합니다. 예시 설정은 [`plugins/context-guard/examples/settings.example.json`](plugins/context-guard/examples/settings.example.json)을 참고하세요.
|
|
170
170
|
|
|
171
171
|
## npm/npx로 설치
|
|
172
172
|
|
|
173
|
-
npm 패키지는 단일 `context-guard` 명령과 기존 `context-guard-*` 헬퍼 명령을 함께 제공합니다. 설치는 수동적입니다. `postinstall`로 설정을 쓰지 않으며, 사용자가 직접 `context-guard setup`을 실행할 때만 프로젝트나 사용자 설정을 변경합니다.
|
|
173
|
+
npm 패키지는 단일 `context-guard` 명령과 기존 `context-guard-*` 헬퍼 명령을 함께 제공합니다. 설치는 수동적입니다. `postinstall`로 설정을 쓰지 않으며, 사용자가 직접 `context-guard setup`을 실행할 때만 프로젝트나 사용자 설정을 변경합니다. setup이 패키지/체크아웃 내부 헬퍼를 찾지 못해도 `PATH` fallback은 기본적으로 꺼져 있습니다. `context-guard doctor` 또는 `setup --verify`로 계획을 확인한 뒤 신뢰하는 헬퍼 디렉터리에 한해서만 `--allow-path-helper-fallback`을 사용하세요.
|
|
174
174
|
|
|
175
175
|
```bash
|
|
176
176
|
npm install -g @ictechgy/context-guard
|
|
@@ -234,10 +234,11 @@ context-guard setup --agent claude --scope user --verify --json
|
|
|
234
234
|
|
|
235
235
|
```bash
|
|
236
236
|
long-command 2>&1 | ./plugins/context-guard/bin/context-guard-artifact store --command "long-command" --json
|
|
237
|
+
./plugins/context-guard/bin/context-guard-artifact search "ERROR" --json
|
|
237
238
|
./plugins/context-guard/bin/context-guard-artifact get <artifact_id> --lines 1:80
|
|
238
239
|
```
|
|
239
240
|
|
|
240
|
-
로컬 보관 모드는
|
|
241
|
+
로컬 보관 모드는 캡처·sandbox 검색·조회 용도입니다. 기본 저장 위치는 `.context-guard/artifacts`이며, 리브랜딩 이전의 `.claude-token-optimizer/artifacts` 요약 기록도 계속 읽을 수 있습니다. JSON 요약 기록에는 줄 번호가 포함된 top-error 요약 기록, 중복 라인 그룹, 가림 처리된 범위 제한 `suggested_queries`가 들어가므로 에이전트가 전체 로그를 다시 넣지 않고 필요한 최소 범위만 정확하게 조회할 수 있습니다. `search`는 로컬 sanitized artifact sandbox를 literal substring으로 검색하고, bounded match/context record와 `context-guard-artifact get ... --lines START:END` 재조회 명령을 함께 반환합니다. custom `--dir` 값의 raw private path는 기본적으로 가림 처리되므로 같은 `--dir`로 다시 실행하거나, 직접 실행 가능한 local command가 꼭 필요할 때만 `search --show-paths`를 명시하세요. 이 검색 리포트는 local-only이며 hosted token/cost savings claim으로 해석하면 안 됩니다. 릴리스 확인처럼 종료 코드가 중요한 파이프라인에서는 원래 명령의 종료 코드를 직접 보존하세요. 종료 코드 보존이 핵심이면 `context-guard-trim-output -- ...`을 사용하는 편이 안전합니다.
|
|
241
242
|
|
|
242
243
|
### 예산 기반 컨텍스트 팩 만들기
|
|
243
244
|
|
|
@@ -248,11 +249,11 @@ long-command 2>&1 | ./plugins/context-guard/bin/context-guard-artifact store --c
|
|
|
248
249
|
--diff HEAD \
|
|
249
250
|
--manifest-out suggested-pack.json \
|
|
250
251
|
--pack-out context-pack.md \
|
|
251
|
-
--budget-bytes 12000 --json --explain
|
|
252
|
+
--budget-bytes 12000 --json --explain --adaptive-k --symbol-memory
|
|
252
253
|
# 또는 명시적인 두 단계로 실행:
|
|
253
254
|
./plugins/context-guard/bin/context-guard-pack suggest \
|
|
254
255
|
--root . --query "failing tests review" --diff HEAD \
|
|
255
|
-
--manifest-out suggested-pack.json --budget-bytes 12000 --json
|
|
256
|
+
--manifest-out suggested-pack.json --budget-bytes 12000 --json --adaptive-k
|
|
256
257
|
./plugins/context-guard/bin/context-guard-pack build \
|
|
257
258
|
--root . --manifest suggested-pack.json --budget-bytes 12000 --json
|
|
258
259
|
./plugins/context-guard/bin/context-guard-pack slice --root . --path README.md --lines 1:40 --json
|
|
@@ -264,7 +265,9 @@ long-command 2>&1 | ./plugins/context-guard/bin/context-guard-artifact store --c
|
|
|
264
265
|
|
|
265
266
|
- `--explain`을 추가하면 JSON 또는 텍스트 출력에 결정적 로컬 선택/build 이유를 짧게 포함합니다.
|
|
266
267
|
- JSON explain에는 bounded `repo_map`이 포함될 수 있습니다. 예시는 sampled byte/token-proxy tree, category-only secret risk count, signature-first hint, explain-only graph rank, 기존 `slice`/symbol 재조회 힌트입니다.
|
|
267
|
-
- repo-map은 manifest, pack 본문, receipt, byte budget을 바꾸지 않고 네트워크·모델 호출·임베딩을 쓰지
|
|
268
|
+
- repo-map은 manifest, pack 본문, receipt, byte budget을 바꾸지 않고 네트워크·모델 호출·임베딩을 쓰지 않습니다. 토큰 값은 provider-token이나 savings claim이 아닌 추정 `chars_div_4` proxy입니다.
|
|
269
|
+
- `suggest` 또는 `auto`에 `--adaptive-k`를 추가하면 로컬 score distribution, byte-budget fit, score-mass 기반 recall/precision proxy에서 나온 advisory-only top-k shrink/expand metadata를 포함합니다. 추천값은 자동 적용되지 않으며 manifest, pack 본문, receipt, byte budget을 바꾸지 않습니다.
|
|
270
|
+
- `auto`에 `--symbol-memory`를 추가하면 repo-map 기반 symbol/graph advisory metadata와 정확한 `slice` / `read-symbol` 검증 힌트를 포함합니다. 이는 source verification 안내일 뿐이며 manifest, pack 본문, receipt, byte budget을 바꾸지 않습니다.
|
|
268
271
|
- `--manifest-out`은 `build`가 읽을 수 있는 manifest를 저장하고, `--pack-out`은 렌더링된 팩 본문을 저장합니다.
|
|
269
272
|
- `context-guard-pack suggest`는 더 낮은 수준의 로컬 전용 준비 단계입니다. `--query`, `--diff`, 반복 `--files`, 그리고 `--root` 아래의 선택적 `--output` / `--test-output` 텍스트 파일을 가림 처리한 신호에서 후보 파일과 줄 범위를 순위화한 뒤 `build --manifest`가 바로 읽을 수 있는 manifest를 씁니다.
|
|
270
273
|
- `context-guard-pack build`는 우선순위가 있는 로컬 파일 근거를 렌더링된 UTF-8 바이트 기준 `--budget-bytes` 안의 Markdown 팩으로 조립합니다. JSON 출력은 포함·부분 포함·중복·unsafe·missing·예산 초과로 누락된 source를 기록합니다.
|
|
@@ -284,18 +287,30 @@ long-command 2>&1 | ./plugins/context-guard/bin/context-guard-artifact store --c
|
|
|
284
287
|
|
|
285
288
|
`context-guard-tool-prune`은 로컬 tool 또는 MCP catalog를 결정적 lexical heuristic(어휘 기반 휴리스틱)으로 순위화해 제한된 top-k 자문 리포트를 만듭니다. inline schema는 관측된 UTF-8 바이트 예산을 지키고, 누락되거나 예산 때문에 생략된 schema는 `.context-guard/tool-prune`의 compact 요약 기록과 별도 가림 처리 payload로 다시 조회할 수 있습니다. 이 기능은 안내용이며 MCP 설정을 변경하지 않습니다. 토큰 값은 provider가 측정한 절감 수치가 아니라 추정 proxy입니다.
|
|
286
289
|
|
|
290
|
+
### 총비용, batchability, routing 후보 자문
|
|
291
|
+
|
|
292
|
+
```bash
|
|
293
|
+
./plugins/context-guard/bin/context-guard route-advisor --workload workload.json --json
|
|
294
|
+
./plugins/context-guard/bin/context-guard-cost route-advisor --feature batch_api=true --feature structured_outputs=true --json < workload.json
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
`context-guard route-advisor`는 로컬 passive advisor입니다. caller가 제공한 workload JSON, provider feature 선언, usage telemetry, 외부·로컬 shifted cost를 읽고 total-cost accounting, batchability blocker, batch API·prompt-cache prefix 보존·structured outputs·저비용 모델 평가 같은 route 후보를 출력합니다. queue를 시작하거나 provider를 호출하거나 pricing 문서를 새로 가져오지 않으며, provider feature는 caller-supplied 또는 unknown/recheck-required로 표시합니다. 추천은 후보일 뿐입니다. hosted token/cost 절감을 주장하려면 matched successful task, 비열등 quality gate, shifted-cost evidence가 필요합니다.
|
|
298
|
+
|
|
287
299
|
### 선택한 로컬 텍스트를 보수적으로 압축하기
|
|
288
300
|
|
|
289
301
|
```bash
|
|
290
302
|
git diff | ./plugins/context-guard/bin/context-guard-compress --json
|
|
291
303
|
pytest -q 2>&1 | ./plugins/context-guard/bin/context-guard-compress --type log
|
|
292
304
|
cat evidence.txt | ./plugins/context-guard/bin/context-guard-compress --json --protected-policy
|
|
305
|
+
cat sanitized-prose.txt | ./plugins/context-guard/bin/context-guard-compress --json --type prose --mode readable
|
|
293
306
|
```
|
|
294
307
|
|
|
295
308
|
`context-guard-compress`는 가림 처리된 stdin을 JSON, diff, 로그, 검색 출력, 코드, 산문으로 분류한 뒤 JSON compact, diff 컨텍스트 접기, 중복 로그·검색 라인 제거, 공백 정규화 같은 결정적 축소를 적용합니다. 모델 토큰 절감을 관측했다고 주장하지 않으며, 바이트 수는 관측값으로, 토큰 수는 추정치로만 표시합니다. 손실형 요약 기록은 정확한 재조회를 위해 `context-guard-artifact store` 사용을 안내합니다.
|
|
296
309
|
|
|
297
310
|
입력에 코드 펜스, diff, 식별자, 숫자 상수, 해시, 경로, 스택 프레임, 따옴표 문자열, JSON 키처럼 의미 보존이 중요한 구역이 있을 때는 `--protected-policy`를 추가하세요. 이 플래그는 기본 압축 동작을 바꾸지 않고, 의미·표현 변환을 거부하며 구조적 변환과 보관본 재조회만 허용하는 `protected_zone_policy`와 `transform_policy` 메타데이터를 추가합니다. 원문 보호 구간 대신 class/count 정책 메타데이터만 저장합니다.
|
|
298
311
|
|
|
312
|
+
`--mode readable`은 가림 처리된 산문 preview에만 사용하세요. 결정적 sentence window를 쓰고, prompt-like 또는 high-risk protected signal이 있으면 차단하며, raw protected span을 저장하지 않고 edit/claim 전에 exact fallback retrieval이 필요하다고 표시합니다. learned compressor, model, embedding, reranker는 실행하지 않습니다.
|
|
313
|
+
|
|
299
314
|
### 명령 출력을 줄이거나 요약하기
|
|
300
315
|
|
|
301
316
|
```bash
|
|
@@ -375,7 +390,7 @@ context-guard experiments record self-hosted-metrics-ledger --ledger-jsonl .cont
|
|
|
375
390
|
context-guard experiments plan local-proxy --json --bind-host 127.0.0.1 --target-host 127.0.0.1 --runtime-gate-ack
|
|
376
391
|
context-guard experiments plan local-proxy-external-forwarding --external-forwarding-intent --external-forwarding-design-ack --allow-host api.example.com --allow-scheme https --credential-redaction-policy strip-sensitive-headers --provider-evidence-boundary diagnostic-only-provider-measured-required --threat-model-note "Only user-owned HTTPS endpoint; sensitive headers are stripped before any future forwarding." --json
|
|
377
392
|
context-guard experiments record local-proxy-runtime-gate --ledger-jsonl .context-guard/local-proxy-gates.jsonl --bind-host 127.0.0.1 --target-host 127.0.0.1 --runtime-gate-ack --json
|
|
378
|
-
context-guard experiments serve local-proxy --bind-host 127.0.0.1 --bind-port 18080 --target-host 127.0.0.1 --target-port 18081 --runtime-gate-ack --forwarding-gate-ack --once --diagnostic-ledger-jsonl .context-guard/local-proxy-diagnostics.jsonl --json
|
|
393
|
+
context-guard experiments serve local-proxy --bind-host 127.0.0.1 --bind-port 18080 --target-host 127.0.0.1 --target-port 18081 --runtime-gate-ack --forwarding-gate-ack --once --ready-file .context-guard/local-proxy-ready.json --diagnostic-ledger-jsonl .context-guard/local-proxy-diagnostics.jsonl --json
|
|
379
394
|
context-guard experiments enable output-receipt-trim --root .
|
|
380
395
|
context-guard experiments disable output-receipt-trim --root .
|
|
381
396
|
```
|
|
@@ -384,7 +399,7 @@ local-proxy 예시는 side effect 기준으로 나뉩니다.
|
|
|
384
399
|
|
|
385
400
|
- `plan local-proxy`는 advisory metadata만 만들며 forwarding을 켜지 않습니다.
|
|
386
401
|
- `record local-proxy-runtime-gate`는 localhost-only gate row 하나만 append하고 listener 시작, traffic forwarding, API key 저장, hosted API 절감 주장을 하지 않습니다.
|
|
387
|
-
- `serve local-proxy`는 별도 MVP입니다. `--runtime-gate-ack --forwarding-gate-ack --once
|
|
402
|
+
- `serve local-proxy`는 별도 MVP입니다. `--runtime-gate-ack --forwarding-gate-ack --once`와 private `--ready-file` nonce handoff가 모두 필요하고 literal loopback IP에만 bind/forward하며 byte/time limit을 적용하고 credential-bearing 요청, hostname DNS target, external forwarding, CONNECT/TLS proxying, API-key persistence, hosted savings claim을 차단합니다.
|
|
388
403
|
- `--diagnostic-ledger-jsonl`을 지정하면 successful forwarded request 뒤에만 shifted-cost 진단 row를 append하며 raw header, request body, response body, hosted-savings evidence를 저장하지 않습니다.
|
|
389
404
|
- `plan local-proxy-external-forwarding`은 dry-run design gate일 뿐입니다. explicit external intent, design ack, HTTPS host allowlist, threat model note, credential redaction policy, provider-evidence boundary를 요구하지만 listener 시작, DNS lookup, external service call, traffic forwarding, credential persistence, external proxy forwarding runtime 제공, hosted savings claim을 하지 않습니다.
|
|
390
405
|
|
|
@@ -396,7 +411,7 @@ local-proxy 예시는 side effect 기준으로 나뉩니다.
|
|
|
396
411
|
| `visual-crop-ocr` | dry-run visual evidence 조언과 명시적 `emit visual-crop-ocr` 런타임으로 caller-supplied evidence pack을 출력합니다. | `emit`은 full visual evidence receipt, missed-context note, 완전한 user-supplied crop 및/또는 OCR evidence가 필요합니다. ContextGuard는 screenshot 캡처, image crop, OCR 실행, image parsing, 외부 service 호출, 파일 쓰기, hosted token/cost 절감 주장을 하지 않습니다. |
|
|
397
412
|
| `learned-compression` | deny-by-default 정책 검사와 명시적 `emit learned-compression` 런타임으로 verified exact fallback content가 있는 caller-supplied compact prose candidate를 출력합니다. | `emit`은 sanitized trusted prose, protected-signal denial, input과 일치하는 verified local fallback artifact, 더 작은 caller-supplied prose candidate가 필요합니다. ContextGuard는 compressor, embedding, reranker, model call, subprocess, external service, 생성형 replacement, hosted savings claim을 실행/생성하지 않습니다. |
|
|
398
413
|
| `self-hosted-metrics-ledger` | dry-run preview와 명시적 `record ... --ledger-jsonl` 런타임으로 local/model-server latency, memory, quality, energy, throughput, local-cost metric을 기록합니다. | dry-run preview는 ledger 파일을 쓰지 않습니다. 명시적 record 명령만 로컬 JSONL sidecar를 쓰며, hosted API token/cost 절감 주장 근거로는 쓰지 않습니다. |
|
|
399
|
-
| `local-proxy` | 미래 local proxy 후보에 대한 localhost-only advisory metadata, future external forwarding용 design-only `plan local-proxy-external-forwarding` review, 명시적 `record local-proxy-runtime-gate --ledger-jsonl` gate row runtime, 명시적 one-shot `serve local-proxy` loopback forwarding MVP, successful forwarded request용 optional `--diagnostic-ledger-jsonl` shifted-cost diagnostics. | `plan`은 ledger를 쓰지 않습니다. `record`는 localhost-only metadata와 `--runtime-gate-ack`가 있을 때만 로컬 JSONL row를 쓰며 listener 시작이나 traffic forwarding, DNS lookup을 하지 않습니다. `serve`는 `--forwarding-gate-ack --once`, literal loopback bind/target IP, nonzero port, byte/time limit, credential-free request가 필요하며 external forwarding, CONNECT/TLS proxying, API-key persistence, hosted API 절감 주장을 하지 않습니다. `--diagnostic-ledger-jsonl`은 successful-forward 진단 row만 쓰며 raw header/body와 hosted-savings claim을 저장하지 않습니다. `plan local-proxy-external-forwarding`은 threat model/allowlist/redaction/provider-evidence design metadata만 출력하고 DNS lookup, external service call, traffic forwarding, credential persistence, hosted savings claim을 하지 않습니다. |
|
|
414
|
+
| `local-proxy` | 미래 local proxy 후보에 대한 localhost-only advisory metadata, future external forwarding용 design-only `plan local-proxy-external-forwarding` review, 명시적 `record local-proxy-runtime-gate --ledger-jsonl` gate row runtime, 명시적 one-shot `serve local-proxy` loopback forwarding MVP, successful forwarded request용 optional `--diagnostic-ledger-jsonl` shifted-cost diagnostics. | `plan`은 ledger를 쓰지 않습니다. `record`는 localhost-only metadata와 `--runtime-gate-ack`가 있을 때만 로컬 JSONL row를 쓰며 listener 시작이나 traffic forwarding, DNS lookup을 하지 않습니다. `serve`는 `--forwarding-gate-ack --once`, private `--ready-file` nonce handoff, literal loopback bind/target IP, nonzero port, byte/time limit, credential-free request가 필요하며 external forwarding, CONNECT/TLS proxying, API-key persistence, hosted API 절감 주장을 하지 않습니다. `--diagnostic-ledger-jsonl`은 successful-forward 진단 row만 쓰며 raw header/body와 hosted-savings claim을 저장하지 않습니다. `plan local-proxy-external-forwarding`은 threat model/allowlist/redaction/provider-evidence design metadata만 출력하고 DNS lookup, external service call, traffic forwarding, credential persistence, hosted savings claim을 하지 않습니다. |
|
|
400
415
|
|
|
401
416
|
## 아직 제공하지 않는 기능
|
|
402
417
|
|
|
@@ -408,7 +423,7 @@ local-proxy 예시는 side effect 기준으로 나뉩니다.
|
|
|
408
423
|
|
|
409
424
|
- `.claude-plugin/marketplace.json` — Claude Code 마켓플레이스 매니페스트입니다.
|
|
410
425
|
- `plugins/context-guard/` — 설치형 Claude Code 플러그인 패키지입니다.
|
|
411
|
-
- `context-guard-kit/` —
|
|
426
|
+
- `context-guard-kit/` — 체크아웃 로컬 Python/Bash 헬퍼 소스입니다. npm 패키지는 이 소스 트리를 중복 포장하지 않고 동기화된 `plugins/context-guard/bin` 및 `plugins/context-guard/lib` 복사본을 배포합니다.
|
|
412
427
|
- `docs/index.html` — 프로젝트용 정적 랜딩 페이지입니다.
|
|
413
428
|
- `tests/` — 헬퍼 동작을 검증하는 회귀 테스트입니다.
|
|
414
429
|
|
|
@@ -442,6 +457,8 @@ export PATH="$PWD/plugins/context-guard/bin:$PATH"
|
|
|
442
457
|
context-guard-setup --plan
|
|
443
458
|
```
|
|
444
459
|
|
|
460
|
+
생성되는 hook 명령은 기본적으로 `PATH` 조회에 의존하지 않습니다. setup 마법사는 명시적인 패키지/체크아웃 헬퍼 경로를 기록하며, `--allow-path-helper-fallback`은 신뢰한 외부 설치를 사용할 때만 canonical 경로·symlink 없음·bounded identity probe 검증 후 허용됩니다.
|
|
461
|
+
|
|
445
462
|
## 릴리스 확인
|
|
446
463
|
|
|
447
464
|
릴리스에 민감한 변경을 배포하거나 머지하기 전에는 동기화 확인과 두 게이트를 모두 실행하세요.
|
|
@@ -452,7 +469,7 @@ python3 scripts/prepublish_check.py
|
|
|
452
469
|
python3 scripts/release_smoke.py
|
|
453
470
|
```
|
|
454
471
|
|
|
455
|
-
헬퍼가 `context-guard-kit/` 아래에서 바뀌었다면 게이트 전에 `python3 scripts/sync_plugin_copies.py --write`를 실행하세요. `sync_plugin_copies.py --check`는 exact-copy 계약을 먼저 확인합니다. `prepublish_check.py`는 패키지 불변식, 동기화된 플러그인 바이너리, 매니페스트, 진단 메시지 가림 처리, 회귀 테스트를 확인합니다. `release_smoke.py`는 임시 프로젝트에서 `plugins/context-guard/bin`의 대표 패키징 엔트리포인트를 실제로 실행해, 배포 전 깨진 CLI 연결을 잡습니다. 전체 릴리스 절차, 증거 체크리스트, quad-review 요구사항, 롤백 체크리스트는 [docs/release-runbook.md](docs/release-runbook.md)를 참고하세요.
|
|
472
|
+
헬퍼가 `context-guard-kit/` 아래에서 바뀌었다면 게이트 전에 `python3 scripts/sync_plugin_copies.py --write`를 실행하세요. `sync_plugin_copies.py --check`는 maintainer exact-copy 계약을 먼저 확인합니다. npm 패키지는 구현 payload 중복을 피하기 위해 동기화된 플러그인 로컬 `plugins/context-guard/bin` 엔트리포인트와 `plugins/context-guard/lib` 헬퍼만 배포합니다. `prepublish_check.py`는 패키지 불변식, 동기화된 플러그인 바이너리, 매니페스트, 진단 메시지 가림 처리, 회귀 테스트를 확인합니다. `release_smoke.py`는 임시 프로젝트에서 `plugins/context-guard/bin`의 대표 패키징 엔트리포인트를 실제로 실행해, 배포 전 깨진 CLI 연결을 잡습니다. 전체 릴리스 절차, 증거 체크리스트, quad-review 요구사항, 롤백 체크리스트는 [docs/release-runbook.md](docs/release-runbook.md)를 참고하세요.
|
|
456
473
|
|
|
457
474
|
버전별 릴리스 노트는 [CHANGELOG.md](CHANGELOG.md)에 기록하며, 사전 배포 게이트는 플러그인 매니페스트 버전과 일치하는 항목이 있는지 확인합니다.
|
|
458
475
|
|
package/README.md
CHANGED
|
@@ -1,19 +1,21 @@
|
|
|
1
1
|
# ContextGuard
|
|
2
2
|
|
|
3
|
-
ContextGuard is a local-first context management toolkit for AI coding and tool agents. It
|
|
3
|
+
ContextGuard is a local-first context management toolkit for AI coding and tool agents. It ships first as a Claude Code plugin: install it once, enable it per project, and roll it back when needed.
|
|
4
|
+
|
|
5
|
+
It trims noisy output, steers agents toward symbol-level reads, nudges repeated failures, redacts secret-like patterns, and measures usage. The same guardrails extend to other agents through local helper commands and advisory brief-mode rule snippets.
|
|
4
6
|
|
|
5
7
|
- Korean documentation: [`README.ko.md`](README.ko.md)
|
|
6
8
|
- Static landing page: [GitHub Pages](https://ictechgy.github.io/context-guard/) ([source](docs/index.html))
|
|
7
9
|
|
|
8
10
|
## TL;DR
|
|
9
11
|
|
|
10
|
-
|
|
12
|
+
Installation and activation are deliberately separate. Installing ContextGuard only makes local helpers or Claude plugin skills available. Configuration changes happen only when you run an explicit setup command.
|
|
11
13
|
|
|
12
14
|
| If you use... | Install | Activate |
|
|
13
15
|
| --- | --- | --- |
|
|
14
16
|
| Claude Code | `/plugin marketplace add ictechgy/context-guard` then `/plugin install context-guard@context-guard` | Run `/context-guard:setup` inside the project. |
|
|
15
17
|
| Codex CLI or any terminal-first agent | `npm install -g @ictechgy/context-guard` or one-shot `npx @ictechgy/context-guard ...` | `context-guard setup --agent codex --scope project --with-init --with-skill --plan`, then rerun with `--yes`. |
|
|
16
|
-
| Other rule-file agents | npm/npx install above | `context-guard setup --agent gemini,cursor,windsurf,cline,copilot --scope project --with-init --plan`, then apply only the agents you want. |
|
|
18
|
+
| Other rule-file agents | Use the npm/npx install path above. | `context-guard setup --agent gemini,cursor,windsurf,cline,copilot --scope project --with-init --plan`, then apply only the agents you want. |
|
|
17
19
|
| macOS/Homebrew users | release path: `brew install ictechgy/tap/context-guard` | Same `context-guard setup ...` commands after install. |
|
|
18
20
|
|
|
19
21
|
Common commands:
|
|
@@ -27,16 +29,16 @@ context-guard setup --agent claude --scope user --verify --json # read-only use
|
|
|
27
29
|
context-guard setup --agent claude --scope user --plan
|
|
28
30
|
```
|
|
29
31
|
|
|
30
|
-
Project scope is the default. User-level setup is opt-in, requires an explicit agent for writes, records backups and rollback metadata, and never runs during package installation. Use `context-guard doctor` or `context-guard setup --verify` for a read-only health check before applying setup
|
|
32
|
+
Project scope is the default. User-level setup is opt-in, requires an explicit agent for writes, records backups and rollback metadata, and never runs during package installation. Use `context-guard doctor` or `context-guard setup --verify` for a read-only health check before applying setup. `doctor` reports next commands and makes no changes. Setup resolves bundled or checkout-local helpers first; it does not trust arbitrary `PATH` helpers unless you explicitly pass `--allow-path-helper-fallback` for a known-good install.
|
|
31
33
|
|
|
32
34
|
ContextGuard is intentionally conservative about savings claims. It reduces common sources of context bloat and provides benchmark tooling so you can measure before/after results on your own tasks. It does **not** promise a fixed token or cost reduction for every repository.
|
|
33
35
|
|
|
34
36
|
## Claude Code first, other agents too
|
|
35
37
|
|
|
36
|
-
ContextGuard ships first as a Claude Code plugin, which is still the fastest path to value. After installation, the same local-first guardrails can be reused by other AI coding and tool agents through:
|
|
38
|
+
ContextGuard ships first as a Claude Code plugin, which is still the fastest path to value for Claude users. After installation, the same local-first guardrails can be reused by other AI coding and tool agents through:
|
|
37
39
|
|
|
38
40
|
- **Local helper commands** (`context-guard-*`) that run as plain shell commands, independent of any specific agent.
|
|
39
|
-
- **Advisory brief-mode rule snippets** you install into an agent's own instruction file (`AGENTS.md`, `GEMINI.md`, `.cursorrules`, Copilot instructions, and similar rule files) and remove by deleting the marker-delimited block.
|
|
41
|
+
- **Advisory brief-mode rule snippets** that you install into an agent's own instruction file (`AGENTS.md`, `GEMINI.md`, `.cursorrules`, Copilot instructions, and similar rule files) and remove by deleting the marker-delimited block.
|
|
40
42
|
- **Dry-run cross-agent setup** that writes only local files, backs up before changing anything, and applies only with explicit approval.
|
|
41
43
|
|
|
42
44
|
Current setup surfaces:
|
|
@@ -61,7 +63,7 @@ ContextGuard does not make the model cheaper by itself. It reduces avoidable con
|
|
|
61
63
|
| Whole-file reads for one function | Suggest search, symbol slices, bounded outlines, and small line ranges before a full read. |
|
|
62
64
|
| Long test, build, search, or diff output | Trim output, emit structured digests, or store large logs locally and return compact receipts. |
|
|
63
65
|
| Repeated failing commands | Warn after repeated Bash failures so the agent changes strategy before more stale logs enter context. |
|
|
64
|
-
| Secret-like or noisy terminal output | Apply best-effort
|
|
66
|
+
| Secret-like or noisy terminal output | Apply best-effort pattern-based redaction for common credential patterns and sensitive-looking paths before output is copied into context. |
|
|
65
67
|
| Unknown token/cost hotspots | Surface statusline signals, transcript audits, and matched benchmark reports for before/after evidence. |
|
|
66
68
|
| Anthropic API requests that may miss prompt cache | `context-guard cost preflight` estimates input size, breakpoint-level cache risk, and low/mid/high cost ranges before a call; default mode warns only. |
|
|
67
69
|
| Volatile context before stable prompt prefixes | Audit bounded redacted prompt-segment hashes and flag likely cache-unfriendly prompt layouts without exposing raw prompt text. |
|
|
@@ -76,7 +78,7 @@ ContextGuard complements provider and semantic caches, and sits next to prompt c
|
|
|
76
78
|
| Provider prompt/context caching | Reusing stable prompt prefixes. | Complementary; ContextGuard helps keep the changing tail of context smaller and cleaner, `context-guard-audit` can flag likely volatile prefix layouts, and `context-guard cost` can warn when an Anthropic request is likely to create/cache-write instead of read. |
|
|
77
79
|
| Semantic response cache | Reusing answers to identical or similar requests. | Complementary; ContextGuard does not serve cached AI answers. |
|
|
78
80
|
| Prompt/context compression | Shortening text that is already selected for the model. | Adjacent; ContextGuard trims and summarizes local output, but does not promise lossless semantic compression. |
|
|
79
|
-
| Experimental planners and local runtimes |
|
|
81
|
+
| Experimental planners and local runtimes | Default-off and explicit-command-only; covers local-proxy plans and gate records plus narrow local runtimes for caller-supplied context-diff, visual evidence-pack, learned-compression, and self-hosted metrics evidence. | The local proxy `record` command starts no listener and forwards no traffic; `serve local-proxy` binds and forwards only literal loopback IPs for one bounded request. Compressor/model execution, OCR/crop services, external forwarding, credential persistence, and hosted-savings claims stay out of scope until a separate evidence gate and future PR allow them. |
|
|
80
82
|
| ContextGuard | Avoiding unnecessary files, logs, repeated failures, and noisy output before they enter agent context. | Local guardrails, reversible artifacts, and measurement. |
|
|
81
83
|
|
|
82
84
|
Related patterns that informed the design:
|
|
@@ -102,6 +104,7 @@ When you need a savings claim, measure it on your own tasks:
|
|
|
102
104
|
- transcript hotspots reported by `context-guard-audit`, including `cache_friendliness` prompt-layout signals and `cache_layout_advice` experiment priorities
|
|
103
105
|
- statusline `cache` / `reuse` as observed transcript/provider-cache signals, not savings caused by ContextGuard
|
|
104
106
|
- `context-guard cost preflight` estimates for Anthropic request JSON, followed by `context-guard cost observe` using provider usage fields (`cache_creation_input_tokens`, `cache_read_input_tokens`) after the call
|
|
107
|
+
- static prompt/request cache layout checks from `context-guard-cache-score`; its char/4 token estimates and warnings are advisory only until provider usage fields confirm real cache hits
|
|
105
108
|
- matched successful baseline/variant runs from `context-guard-bench`
|
|
106
109
|
- large tool/MCP catalogs versus `context-guard-tool-prune` top-k reports plus receipt retrieval
|
|
107
110
|
- optional experimental lanes in [`research/experimental-token-reduction-radar.md`](research/experimental-token-reduction-radar.md); fixture-only starters in [`docs/experimental-benchmark-fixtures.md`](docs/experimental-benchmark-fixtures.md) use the same matched-task benchmark gates before any savings claim
|
|
@@ -113,7 +116,7 @@ When you need a savings claim, measure it on your own tasks:
|
|
|
113
116
|
- It does not mutate global Claude settings during install.
|
|
114
117
|
- It does not replace real before/after measurement when you need a savings claim.
|
|
115
118
|
- Local RAM/disk receipts can reduce what you send next, but they do **not** replace Anthropic's provider prompt cache or guarantee cache hits. Recheck Anthropic prompt-caching and pricing docs before release or billing claims: https://docs.anthropic.com/en/build-with-claude/prompt-caching and https://platform.claude.com/docs/en/about-claude/pricing.
|
|
116
|
-
- Experimental helpers are mostly dry-run checker/planner surfaces, including a design-only external-forwarding opt-in gate. Explicit local runtimes exist only for caller-supplied context-diff replacement payloads, caller-supplied visual crop/OCR evidence packs, caller-supplied learned-compression prose candidates, self-hosted metrics JSONL sidecar records, local-proxy runtime-gate JSONL records, and one-shot `serve local-proxy` loopback forwarding plus optional shifted-cost diagnostic JSONL rows for successful forwarded requests.
|
|
119
|
+
- Experimental helpers are mostly dry-run checker/planner surfaces, including a design-only external-forwarding opt-in gate. Explicit local runtimes exist only for caller-supplied context-diff replacement payloads, caller-supplied visual crop/OCR evidence packs, caller-supplied learned-compression prose candidates, self-hosted metrics JSONL sidecar records, local-proxy runtime-gate JSONL records, and one-shot `serve local-proxy` loopback forwarding with a private ready-file nonce plus optional shifted-cost diagnostic JSONL rows for successful forwarded requests.
|
|
117
120
|
- ContextGuard does not ship learned/synthetic compressor execution, embeddings, rerankers, model calls, generated replacement text, screenshot capture, image cropping, OCR execution, image parsing, external OCR/image services, self-hosted KV/latent inference optimization beyond explicit local metrics recording, or broader proxy forwarding beyond literal-loopback, one-request HTTP forwarding with credential material blocked.
|
|
118
121
|
- It does not alias the old `/claude-token-optimizer:*` Claude Code slash-command namespace. Use `/context-guard:*` after installing this plugin.
|
|
119
122
|
|
|
@@ -125,16 +128,16 @@ Legacy local CLI wrappers (`claude-token-*`, `claude-read-symbol`, `claude-trim-
|
|
|
125
128
|
| --- | --- |
|
|
126
129
|
| Claude Code plugin skills | Guided setup, optimization, and transcript usage audits. |
|
|
127
130
|
| Project-local setup wizard | Applies recommended `.claude/settings.json` options without touching global settings. |
|
|
128
|
-
| Context
|
|
131
|
+
| Context management scanner | Finds missing guardrails, noisy hooks, broad reads, large context files, secret-like files, excessive MCP servers, and expensive defaults. |
|
|
129
132
|
| Structural-waste doctor | Opt-in local diagnostics for duplicate rules, stale imports, unused skill candidates, oversized tool schemas, and repeated read/tool-call loops. |
|
|
130
133
|
| Large-read guard and symbol reader | Nudges the agent toward `rg`, symbol reads, and small line ranges instead of full-file reads. |
|
|
131
134
|
| Output trimming and sanitizing | Keeps test, build, search, and diff output compact while redacting likely secrets before they enter agent context. |
|
|
132
135
|
| Declarative output filter | Opt-in JSON DSL for user-owned command filters with protected failure passthrough and validation before use. |
|
|
133
136
|
| Local artifact store | Saves large sanitized logs outside the conversation and returns compact receipts or exact requested slices. |
|
|
134
|
-
| Anthropic cost guard | `context-guard cost preflight/observe/ledger/compile` estimates cache
|
|
135
|
-
| Budgeted context packer | Assembles prioritized local file evidence into a byte-budgeted Markdown pack, can suggest a build-compatible manifest from local signals,
|
|
137
|
+
| Anthropic cost guard | `context-guard cost preflight/observe/ledger/compile` estimates cache risk and cost ranges. `context-guard route-advisor` summarizes local total-cost and batchability route candidates, stores only keyed HMAC fingerprints where a ledger is used, and stays passive unless `--enforce` is explicit. |
|
|
138
|
+
| Budgeted context packer | Assembles prioritized local file evidence into a byte-budgeted Markdown pack, can suggest a build-compatible manifest from local signals, adds `--explain` for compact local selection reasons plus bounded repo-map metadata, and adds opt-in `--adaptive-k` / `--symbol-memory` advisory metadata. |
|
|
136
139
|
| Tool/MCP schema pruner | Emits bounded top-k tool/schema advisory reports from local catalogs with compact receipts and full sanitized payload retrieval. |
|
|
137
|
-
| Conservative stdin compressor | Shrinks selected JSON, diffs, logs, search output, code, and prose with observed byte evidence and estimated token proxies. |
|
|
140
|
+
| Conservative stdin compressor | Shrinks selected JSON, diffs, logs, search output, code, and prose with observed byte evidence and estimated token proxies; `--mode readable` adds an opt-in readable prose preview with exact fallback guidance. |
|
|
138
141
|
| Protected-zone policy receipts | Opt-in `context-guard-compress --protected-policy` and `context-guard cost compile` metadata mark code/diff/path/hash/JSON/literal zones as structural-only with exact retrieval guidance. |
|
|
139
142
|
| Repeated-failure nudge | Warns after repeated Bash failures so the agent changes strategy before stale logs fill the context. |
|
|
140
143
|
| Statusline, audit, and benchmarks | Shows context/cache/cost signals, finds usage and cache-friendliness hotspots, and records conservative before/after evidence. |
|
|
@@ -170,7 +173,7 @@ Setup is explicit, project-local, and reversible. The plugin does not configure
|
|
|
170
173
|
|
|
171
174
|
## Install with npm/npx
|
|
172
175
|
|
|
173
|
-
The npm package exposes a canonical `context-guard` command plus
|
|
176
|
+
The npm package exposes a canonical `context-guard` command plus backward-compatible `context-guard-*` helper commands. Package installation is passive: there is no `postinstall` setup hook and no config write until you run `context-guard setup` yourself. If setup cannot find bundled or checkout-local helpers, `PATH` fallback remains disabled by default; use `--allow-path-helper-fallback` only for trusted helper directories after `context-guard doctor` or `setup --verify` confirms the plan.
|
|
174
177
|
|
|
175
178
|
```bash
|
|
176
179
|
npm install -g @ictechgy/context-guard
|
|
@@ -214,7 +217,7 @@ context-guard setup --agent claude --scope user --verify --json
|
|
|
214
217
|
|
|
215
218
|
Both modes are read-only configuration checks. `doctor` reports recommended next commands, and `setup --verify` checks whether setup is complete without applying changes. With `--json`, the report is written to stdout.
|
|
216
219
|
|
|
217
|
-
### Scan context
|
|
220
|
+
### Scan context management
|
|
218
221
|
|
|
219
222
|
```bash
|
|
220
223
|
./plugins/context-guard/bin/context-guard-diet scan .
|
|
@@ -245,10 +248,11 @@ The optional Read guard uses a progressive path for oversized files: search firs
|
|
|
245
248
|
|
|
246
249
|
```bash
|
|
247
250
|
long-command 2>&1 | ./plugins/context-guard/bin/context-guard-artifact store --command "long-command" --json
|
|
251
|
+
./plugins/context-guard/bin/context-guard-artifact search "ERROR" --json
|
|
248
252
|
./plugins/context-guard/bin/context-guard-artifact get <artifact_id> --lines 1:80
|
|
249
253
|
```
|
|
250
254
|
|
|
251
|
-
Artifact mode is for capture and retrieval. It stores sanitized output under `.context-guard/artifacts` by default and can still read legacy `.claude-token-optimizer/artifacts` receipts from before the rebrand. JSON receipts include line-numbered top-error receipts, duplicate-line groups, and sanitized bounded `suggested_queries` so an agent can fetch the smallest useful exact slice instead of replaying the full log. When `--max-lines` accompanies a `--lines START:END` selector, it caps lines returned within that range; it does not expand the selector. Preserve the producer command's exit code yourself when using shell pipelines in release checks, or use `context-guard-trim-output -- ...` when exit-code preservation is the primary requirement.
|
|
255
|
+
Artifact mode is for capture, sandbox search, and retrieval. It stores sanitized output under `.context-guard/artifacts` by default and can still read legacy `.claude-token-optimizer/artifacts` receipts from before the rebrand. JSON receipts include line-numbered top-error receipts, duplicate-line groups, and sanitized bounded `suggested_queries` so an agent can fetch the smallest useful exact slice instead of replaying the full log. `search` scans the local sanitized artifact sandbox by literal substring, returns capped match/context records, and includes `context-guard-artifact get ... --lines START:END` rehydration commands for omitted detail. For custom `--dir` values, raw private paths stay redacted by default; rerun with the same `--dir`, or pass `search --show-paths` when you explicitly want a directly executable local command. The search report is local-only and does not make hosted token/cost savings claims. When `--max-lines` accompanies a `--lines START:END` selector, it caps lines returned within that range; it does not expand the selector. Preserve the producer command's exit code yourself when using shell pipelines in release checks, or use `context-guard-trim-output -- ...` when exit-code preservation is the primary requirement.
|
|
252
256
|
|
|
253
257
|
### Build a budgeted context pack
|
|
254
258
|
|
|
@@ -259,11 +263,11 @@ Artifact mode is for capture and retrieval. It stores sanitized output under `.c
|
|
|
259
263
|
--diff HEAD \
|
|
260
264
|
--manifest-out suggested-pack.json \
|
|
261
265
|
--pack-out context-pack.md \
|
|
262
|
-
--budget-bytes 12000 --json --explain
|
|
266
|
+
--budget-bytes 12000 --json --explain --adaptive-k --symbol-memory
|
|
263
267
|
# Or run the two explicit steps:
|
|
264
268
|
./plugins/context-guard/bin/context-guard-pack suggest \
|
|
265
269
|
--root . --query "review failing tests" --diff HEAD \
|
|
266
|
-
--manifest-out suggested-pack.json --budget-bytes 12000 --json
|
|
270
|
+
--manifest-out suggested-pack.json --budget-bytes 12000 --json --adaptive-k
|
|
267
271
|
./plugins/context-guard/bin/context-guard-pack build \
|
|
268
272
|
--root . --manifest suggested-pack.json --budget-bytes 12000 --json
|
|
269
273
|
./plugins/context-guard/bin/context-guard-pack slice --root . --path README.md --lines 1:40 --json
|
|
@@ -276,6 +280,8 @@ A few boundaries are intentional:
|
|
|
276
280
|
- Add `--explain` for compact deterministic local selection/build reasons in JSON or text output.
|
|
277
281
|
- `--explain` may include bounded `repo_map` metadata: sampled byte/token-proxy tree entries, category-only secret-risk counts, signature-first file hints, explain-only graph ranks, and exact `slice`/symbol retrieval hints.
|
|
278
282
|
- Explain metadata does not change the manifest, pack body, receipt, or byte budget. It does not use network/model/embedding calls, and token values remain local `chars_div_4` proxies rather than provider-token or savings claims.
|
|
283
|
+
- Add `--adaptive-k` to `suggest` or `auto` for advisory-only shrink/expand top-k metadata derived from local score distribution, byte-budget fit, and score-mass recall/precision proxies. It never applies the recommendation automatically and does not change the manifest, pack body, receipt, or byte budget.
|
|
284
|
+
- Add `--symbol-memory` to `auto` for repo-map-derived symbol/graph advisory metadata with exact `slice` / `read-symbol` verification hints. It is source-verification guidance only and does not change the manifest, pack body, receipt, or byte budget.
|
|
279
285
|
- `--manifest-out` writes a build-compatible manifest; `--pack-out` saves the rendered pack.
|
|
280
286
|
- `context-guard-pack suggest` is the lower-level additive local-only planning step. It ranks candidate files and line ranges from `--query`, `--diff`, repeated `--files`, and optional sanitized `--output` / `--test-output` files under `--root`, then writes a manifest that `build --manifest` can consume.
|
|
281
287
|
- `context-guard-pack build` assembles prioritized local file evidence into a Markdown body whose rendered UTF-8 bytes stay within `--budget-bytes`. JSON output records included, partial, duplicate, unsafe, missing, and budget-omitted sources.
|
|
@@ -290,10 +296,32 @@ The packer uses deterministic standard-library heuristics only: no network, mode
|
|
|
290
296
|
--catalog tools.json \
|
|
291
297
|
--query "review failing tests" \
|
|
292
298
|
--top 5 --budget-bytes 12000 --json
|
|
299
|
+
./plugins/context-guard/bin/context-guard-tool-prune defer-report \
|
|
300
|
+
--catalog tools.json \
|
|
301
|
+
--query "review failing tests" \
|
|
302
|
+
--core-top 3 --deferred-top 20 --json
|
|
293
303
|
./plugins/context-guard/bin/context-guard-tool-prune get <receipt_id> --tool read_file --json
|
|
294
304
|
```
|
|
295
305
|
|
|
296
|
-
`context-guard-tool-prune` ranks a local tool or MCP catalog with deterministic lexical heuristics and emits a bounded top-k advisory report. Inline selected schemas respect an observed UTF-8 byte budget, and omitted or budget-skipped schemas remain recoverable from a compact local receipt plus a separate sanitized payload under `.context-guard/tool-prune`. This is advisory only: it does not mutate MCP configuration, and token counts remain estimated proxies rather than measured provider savings.
|
|
306
|
+
`context-guard-tool-prune` ranks a local tool or MCP catalog with deterministic lexical heuristics and emits a bounded top-k advisory report. Inline selected schemas respect an observed UTF-8 byte budget, and omitted or budget-skipped schemas remain recoverable from a compact local receipt plus a separate sanitized payload under `.context-guard/tool-prune`. `defer-report` uses the same receipt path to split a catalog into core inline tools plus deferred tool stubs and namespace summaries. This is advisory only: it does not mutate MCP configuration, does not configure native provider tool search, and token counts remain estimated proxies rather than measured provider savings.
|
|
307
|
+
|
|
308
|
+
### Score static prompt cacheability
|
|
309
|
+
|
|
310
|
+
```bash
|
|
311
|
+
./plugins/context-guard/bin/context-guard-cache-score --input prompt.json --provider openai --json
|
|
312
|
+
./plugins/context-guard/bin/context-guard cache-score --input prompt.txt --provider anthropic --json
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
`context-guard-cache-score` is a local static lint for prompt/request layout. It estimates total and cacheable-prefix size with a tokenizer-free char/4 proxy, warns about dynamic-looking values near the prefix, and records provider caveats for OpenAI, Anthropic, Gemini, or a generic threshold. It does not call providers, store raw prompts, estimate prices, observe cache hits, or prove token/cost savings; verify real cache behavior with provider usage telemetry.
|
|
316
|
+
|
|
317
|
+
### Advise on total cost, batchability, and routing
|
|
318
|
+
|
|
319
|
+
```bash
|
|
320
|
+
./plugins/context-guard/bin/context-guard route-advisor --workload workload.json --json
|
|
321
|
+
./plugins/context-guard/bin/context-guard-cost route-advisor --feature batch_api=true --feature structured_outputs=true --json < workload.json
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
`context-guard route-advisor` is a local, passive advisor. It reads caller-supplied workload JSON, provider feature declarations, usage telemetry, and shifted external/local costs, then emits total-cost accounting, batchability blockers, and candidate routes such as batch API, prompt-cache prefix preservation, structured outputs, or cheaper-model evaluation. It does not start a queue, call providers, refresh pricing docs, or treat bundled provider feature knowledge as authoritative; unknown or caller-supplied features are marked recheck-required. Treat recommendations as candidates only. Hosted token or cost savings claims require matched successful tasks, non-inferior quality, and shifted-cost evidence.
|
|
297
325
|
|
|
298
326
|
### Compress selected local text conservatively
|
|
299
327
|
|
|
@@ -301,12 +329,15 @@ The packer uses deterministic standard-library heuristics only: no network, mode
|
|
|
301
329
|
git diff | ./plugins/context-guard/bin/context-guard-compress --json
|
|
302
330
|
pytest -q 2>&1 | ./plugins/context-guard/bin/context-guard-compress --type log
|
|
303
331
|
cat evidence.txt | ./plugins/context-guard/bin/context-guard-compress --json --protected-policy
|
|
332
|
+
cat sanitized-prose.txt | ./plugins/context-guard/bin/context-guard-compress --json --type prose --mode readable
|
|
304
333
|
```
|
|
305
334
|
|
|
306
335
|
`context-guard-compress` classifies sanitized stdin as JSON, diff, log, search output, code, or prose, then applies deterministic reductions such as JSON compaction, diff context folding, duplicate log/search line collapse, and whitespace normalization. It never claims observed model-token savings; byte counts are observed, token counts are labeled as estimates, and lossy receipts point you back to `context-guard-artifact store` for exact retrieval.
|
|
307
336
|
|
|
308
337
|
Add `--protected-policy` when the input may contain semantic-sensitive zones such as code fences, diffs, identifiers, numeric constants, hashes, paths, stack frames, quoted strings, or JSON keys. The flag does not change default compressor behavior; it adds `protected_zone_policy` and `transform_policy` metadata that denies semantic/paraphrase rewrites, allows only structural transforms plus artifact retrieval, and stores only class/count policy metadata rather than raw protected spans.
|
|
309
338
|
|
|
339
|
+
Add `--mode readable` only for sanitized prose previews. It uses a deterministic sentence window, blocks prompt-like or high-risk protected signals, stores no raw protected spans, and marks exact fallback retrieval as required before edits or claims. It does not run learned compressors, models, embeddings, or rerankers.
|
|
340
|
+
|
|
310
341
|
### Trim or summarize command output
|
|
311
342
|
|
|
312
343
|
```bash
|
|
@@ -408,7 +439,7 @@ context-guard experiments record self-hosted-metrics-ledger --ledger-jsonl .cont
|
|
|
408
439
|
context-guard experiments plan local-proxy --json --bind-host 127.0.0.1 --target-host 127.0.0.1 --runtime-gate-ack
|
|
409
440
|
context-guard experiments plan local-proxy-external-forwarding --external-forwarding-intent --external-forwarding-design-ack --allow-host api.example.com --allow-scheme https --credential-redaction-policy strip-sensitive-headers --provider-evidence-boundary diagnostic-only-provider-measured-required --threat-model-note "Only user-owned HTTPS endpoint; sensitive headers are stripped before any future forwarding." --json
|
|
410
441
|
context-guard experiments record local-proxy-runtime-gate --ledger-jsonl .context-guard/local-proxy-gates.jsonl --bind-host 127.0.0.1 --target-host 127.0.0.1 --runtime-gate-ack --json
|
|
411
|
-
context-guard experiments serve local-proxy --bind-host 127.0.0.1 --bind-port 18080 --target-host 127.0.0.1 --target-port 18081 --runtime-gate-ack --forwarding-gate-ack --once --diagnostic-ledger-jsonl .context-guard/local-proxy-diagnostics.jsonl --json
|
|
442
|
+
context-guard experiments serve local-proxy --bind-host 127.0.0.1 --bind-port 18080 --target-host 127.0.0.1 --target-port 18081 --runtime-gate-ack --forwarding-gate-ack --once --ready-file .context-guard/local-proxy-ready.json --diagnostic-ledger-jsonl .context-guard/local-proxy-diagnostics.jsonl --json
|
|
412
443
|
context-guard experiments enable output-receipt-trim --root .
|
|
413
444
|
context-guard experiments disable output-receipt-trim --root .
|
|
414
445
|
```
|
|
@@ -417,7 +448,7 @@ The local-proxy examples are intentionally split by side effect:
|
|
|
417
448
|
|
|
418
449
|
- `plan local-proxy` produces advisory metadata only; it does not enable forwarding.
|
|
419
450
|
- `record local-proxy-runtime-gate` appends one localhost-only gate row and still starts no listener, forwards no traffic, persists no API keys, and makes no hosted-savings claim.
|
|
420
|
-
- `serve local-proxy` is the separate MVP. It requires both runtime and forwarding acknowledgements plus `--once`, binds only a literal loopback IP, forwards only to a literal loopback IP target, blocks credential-bearing requests, uses byte/time limits, uses literal IPs instead of hostname DNS targets, does not persist API keys, and does not support external forwarding, CONNECT/TLS proxying, or hosted-savings claims.
|
|
451
|
+
- `serve local-proxy` is the separate MVP. It requires both runtime and forwarding acknowledgements plus `--once`, a private `--ready-file` nonce handoff for the forwarding client, binds only a literal loopback IP, forwards only to a literal loopback IP target, blocks credential-bearing requests, uses byte/time limits, uses literal IPs instead of hostname DNS targets, does not persist API keys, and does not support external forwarding, CONNECT/TLS proxying, or hosted-savings claims.
|
|
421
452
|
- With `--diagnostic-ledger-jsonl`, `serve` appends one shifted-cost diagnostic row only after a successful forwarded request. The row stores hashes/metadata rather than raw headers, request bodies, response bodies, or hosted-savings evidence.
|
|
422
453
|
- `plan local-proxy-external-forwarding` is a dry-run design gate only. It requires explicit external intent, design acknowledgement, HTTPS host allowlist, threat model notes, credential redaction policy, and provider-evidence boundary, but starts no listener, performs no DNS lookup, calls no external service, forwards no traffic, persists no credentials, and does not ship an external proxy forwarding runtime.
|
|
423
454
|
|
|
@@ -431,19 +462,26 @@ Shipped experimental checker/planner surfaces, plus explicit local context-diff,
|
|
|
431
462
|
| `visual-crop-ocr` | Dry-run visual evidence advice plus an explicit `emit visual-crop-ocr` runtime for caller-supplied evidence packs. | `emit` requires a full visual evidence receipt, missed-context note, and complete user-supplied crop and/or OCR evidence; ContextGuard does not capture screenshots, crop images, run OCR, parse images, call external services, write files, or support hosted token/cost savings claims. |
|
|
432
463
|
| `learned-compression` | Deny-by-default policy checks plus an explicit `emit learned-compression` runtime for caller-supplied compact prose candidates with verified exact fallback content. | `emit` requires sanitized trusted prose, protected-signal denial, a verified local fallback artifact matching the input, and a smaller caller-supplied prose candidate; ContextGuard does not run compressors, embeddings, rerankers, model calls, subprocesses, external services, generated replacement text, or hosted savings claims. |
|
|
433
464
|
| `self-hosted-metrics-ledger` | Dry-run preview plus an explicit `record ... --ledger-jsonl` runtime for local/model-server latency, memory, quality, energy, throughput, and local-cost metrics. | The dry-run preview does not write a ledger; the explicit record command writes only local JSONL sidecars and still does not support hosted API token/cost savings claims. |
|
|
434
|
-
| `local-proxy` | Localhost-only advisory metadata, design-only `plan local-proxy-external-forwarding` review for future external forwarding, an explicit `record local-proxy-runtime-gate --ledger-jsonl` runtime for one local gate row, an explicit one-shot `serve local-proxy` loopback forwarding MVP, and optional `--diagnostic-ledger-jsonl` shifted-cost diagnostics for successful forwarded requests. | `plan` writes no ledger. `record` writes only after localhost-only metadata and `--runtime-gate-ack`; it starts no listener, forwards no traffic, and performs no DNS lookup. `serve` additionally requires `--forwarding-gate-ack --once`, literal loopback bind/target IPs, nonzero ports, bounded bytes/timeouts, and credential-free requests; it performs no external forwarding, no CONNECT/TLS proxying, no API-key persistence, and no hosted-savings claim. `--diagnostic-ledger-jsonl` writes only successful-forward diagnostics with no raw headers/bodies and no hosted-savings claim. `plan local-proxy-external-forwarding` emits threat-model/allowlist/redaction/provider-evidence design metadata only and still performs no DNS lookup, external service call, traffic forwarding, credential persistence, or hosted-savings claim. |
|
|
465
|
+
| `local-proxy` | Localhost-only advisory metadata, design-only `plan local-proxy-external-forwarding` review for future external forwarding, an explicit `record local-proxy-runtime-gate --ledger-jsonl` runtime for one local gate row, an explicit one-shot `serve local-proxy` loopback forwarding MVP, and optional `--diagnostic-ledger-jsonl` shifted-cost diagnostics for successful forwarded requests. | `plan` writes no ledger. `record` writes only after localhost-only metadata and `--runtime-gate-ack`; it starts no listener, forwards no traffic, and performs no DNS lookup. `serve` additionally requires `--forwarding-gate-ack --once`, a private `--ready-file` nonce handoff, literal loopback bind/target IPs, nonzero ports, bounded bytes/timeouts, and credential-free requests; it performs no external forwarding, no CONNECT/TLS proxying, no API-key persistence, and no hosted-savings claim. `--diagnostic-ledger-jsonl` writes only successful-forward diagnostics with no raw headers/bodies and no hosted-savings claim. `plan local-proxy-external-forwarding` emits threat-model/allowlist/redaction/provider-evidence design metadata only and still performs no DNS lookup, external service call, traffic forwarding, credential persistence, or hosted-savings claim. |
|
|
435
466
|
|
|
436
467
|
## What is not yet shipped
|
|
437
468
|
|
|
438
|
-
These are directions the project has
|
|
469
|
+
These are directions the project has tracked, not committed features. Nothing here ships unless documented elsewhere in the repository.
|
|
470
|
+
|
|
471
|
+
ContextGuard does not yet ship:
|
|
439
472
|
|
|
440
|
-
-
|
|
473
|
+
- learned/synthetic compressor execution or generated replacement text beyond the caller-supplied learned candidate emitter
|
|
474
|
+
- generated crop/OCR or visual-token pruning runtime beyond the caller-supplied visual evidence-pack emitter
|
|
475
|
+
- self-hosted KV/latent optimization beyond explicit local metrics recording
|
|
476
|
+
- external, daemon, or credential-bearing proxy forwarding beyond the one-shot literal-loopback local proxy MVP
|
|
477
|
+
|
|
478
|
+
See the [experimental token-reduction radar](research/experimental-token-reduction-radar.md) and [fixture-only experimental benchmark starters](docs/experimental-benchmark-fixtures.md). Those lanes remain experimental/non-shipped under the later-roadmap gate until matched successful tasks, failure-rate guardrails, human-correction tracking, shifted-cost accounting, provider-measured token/cost evidence, and separate future PR gates justify any hosted API savings claim or broader runtime feature claim.
|
|
441
479
|
|
|
442
480
|
## Repository layout
|
|
443
481
|
|
|
444
482
|
- `.claude-plugin/marketplace.json` — Claude Code marketplace manifest.
|
|
445
483
|
- `plugins/context-guard/` — installable Claude Code plugin package.
|
|
446
|
-
- `context-guard-kit/` —
|
|
484
|
+
- `context-guard-kit/` — checkout-local Python/Bash helper sources. npm packages ship synchronized `plugins/context-guard/bin` and `plugins/context-guard/lib` copies instead of duplicating this source tree.
|
|
447
485
|
- `docs/index.html` — static landing page for the project.
|
|
448
486
|
- `tests/` — regression tests for helper behavior.
|
|
449
487
|
|
|
@@ -477,6 +515,8 @@ export PATH="$PWD/plugins/context-guard/bin:$PATH"
|
|
|
477
515
|
context-guard-setup --plan
|
|
478
516
|
```
|
|
479
517
|
|
|
518
|
+
Do not rely on `PATH` lookup for generated hooks by default. The setup wizard records explicit bundled or checkout-local helper paths; `--allow-path-helper-fallback` is only for trusted external installs and validates the resolved helper before writing commands.
|
|
519
|
+
|
|
480
520
|
## Release checks
|
|
481
521
|
|
|
482
522
|
Before publishing or merging release-sensitive changes, run the copy check and both gates:
|
|
@@ -487,7 +527,7 @@ python3 scripts/prepublish_check.py
|
|
|
487
527
|
python3 scripts/release_smoke.py
|
|
488
528
|
```
|
|
489
529
|
|
|
490
|
-
When a helper under `context-guard-kit/` changes, run `python3 scripts/sync_plugin_copies.py --write` before the gates. `sync_plugin_copies.py --check` verifies the exact-copy contract up front
|
|
530
|
+
When a helper under `context-guard-kit/` changes, run `python3 scripts/sync_plugin_copies.py --write` before the gates. `sync_plugin_copies.py --check` verifies the maintainer-facing exact-copy contract up front. npm packages intentionally ship only the synchronized plugin-local `plugins/context-guard/bin` entrypoints and `plugins/context-guard/lib` helpers to avoid duplicate implementation payloads. `prepublish_check.py` verifies package invariants, synchronized plugin binaries, manifests, diagnostic redaction, and the regression suite. `release_smoke.py` executes representative packaged entrypoints from `plugins/context-guard/bin` in a temporary project so broken CLI wiring is caught before publish. See [docs/release-runbook.md](docs/release-runbook.md) for the full release workflow, evidence checklist, quad-review requirement, and rollback checklist.
|
|
491
531
|
|
|
492
532
|
Versioned release notes live in [CHANGELOG.md](CHANGELOG.md); the prepublish gate requires an entry matching the plugin manifest version before publishing.
|
|
493
533
|
|