@ictechgy/context-guard 0.4.15 → 0.5.1
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 +80 -0
- package/README.ko.md +128 -2
- package/README.md +144 -3
- package/docs/distribution.md +100 -0
- package/package.json +4 -1
- package/plugins/context-guard/.claude-plugin/plugin.json +1 -1
- package/plugins/context-guard/README.ko.md +43 -1
- package/plugins/context-guard/README.md +44 -1
- package/plugins/context-guard/bin/bash_reference_policy.py +967 -0
- package/plugins/context-guard/bin/context-guard-artifact +90 -9
- package/plugins/context-guard/bin/context-guard-audit +169 -66
- package/plugins/context-guard/bin/context-guard-bench +9865 -211
- package/plugins/context-guard/bin/context-guard-compress +90 -8
- package/plugins/context-guard/bin/context-guard-diet +1 -7
- package/plugins/context-guard/bin/context-guard-experiments +5 -1
- package/plugins/context-guard/bin/context-guard-failed-nudge +777 -83
- package/plugins/context-guard/bin/context-guard-guard-read +496 -57
- package/plugins/context-guard/bin/context-guard-mcp +2 -1
- package/plugins/context-guard/bin/context-guard-pack +1570 -150
- package/plugins/context-guard/bin/context-guard-read-symbol +7 -2
- package/plugins/context-guard/bin/context-guard-rewrite-bash +2669 -236
- package/plugins/context-guard/bin/context-guard-sanitize-output +723 -92
- package/plugins/context-guard/bin/context-guard-setup +1944 -222
- package/plugins/context-guard/bin/context-guard-statusline +163 -55
- package/plugins/context-guard/bin/context-guard-statusline-merged +78 -23
- package/plugins/context-guard/bin/context-guard-tool-prune +44 -11
- package/plugins/context-guard/bin/context-guard-trim-output +795 -48
- package/plugins/context-guard/brief/README.md +19 -0
- package/plugins/context-guard/brief/narration-mode.quiet.md +21 -0
- package/plugins/context-guard/lib/context_guard_commands.py +10 -2
- package/plugins/context-guard/lib/credential_policy.py +185 -0
- package/plugins/context-guard/lib/transcript_usage_reducer.py +378 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ictechgy/context-guard",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"description": "ContextGuard CLI helpers for keeping AI coding agent context focused and local-first.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"homepage": "https://github.com/ictechgy/context-guard#readme",
|
|
@@ -12,6 +12,9 @@
|
|
|
12
12
|
"url": "https://github.com/ictechgy/context-guard/issues"
|
|
13
13
|
},
|
|
14
14
|
"type": "commonjs",
|
|
15
|
+
"dependencies": {
|
|
16
|
+
"@ictechgy/context-guard-receipt": "0.2.1"
|
|
17
|
+
},
|
|
15
18
|
"bin": {
|
|
16
19
|
"context-guard": "plugins/context-guard/bin/context-guard",
|
|
17
20
|
"context-guard-setup": "plugins/context-guard/bin/context-guard-setup",
|
|
@@ -46,6 +46,15 @@ context-guard setup --agent codex --scope project --brief-mode standard --plan
|
|
|
46
46
|
npx @ictechgy/context-guard --version
|
|
47
47
|
```
|
|
48
48
|
|
|
49
|
+
짧은 `bash_reference_v1` Bash 출력 경로는 이 marketplace plugin/소스 배치에서
|
|
50
|
+
의도적으로 활성화되지 않습니다. 정확한 프로젝트 로컬
|
|
51
|
+
`@ictechgy/context-guard@0.5.1` npm 설치와
|
|
52
|
+
`@ictechgy/context-guard-receipt@0.2.1` 의존성이 필요하며, 그 뒤
|
|
53
|
+
`setup --agent claude --scope project --bash-reference-v1`로 명시적으로
|
|
54
|
+
활성화해야 합니다. Plugin setup은 동작하지 않는 reference flag를 설치하지 않고
|
|
55
|
+
legacy trim을 유지하며 경고합니다. 활성화·비활성화, 7일 handle, 상태 보존은
|
|
56
|
+
저장소의 배포 문서를 참고하세요.
|
|
57
|
+
|
|
49
58
|
이 저장소 루트에서는 경로를 직접 지정해 실행하세요.
|
|
50
59
|
|
|
51
60
|
```bash
|
|
@@ -78,6 +87,8 @@ context-guard-read-symbol path/to/file.py TargetSymbol
|
|
|
78
87
|
context-guard-sanitize-output -- rg -n "TOKEN|SECRET" .
|
|
79
88
|
context-guard-sanitize-output -- git diff
|
|
80
89
|
context-guard-pack auto --root . --query "failing tests review" --diff HEAD --manifest-out suggested-pack.json --pack-out context-pack.md --budget-bytes 12000 --json --explain --adaptive-k --adaptive-k-policy recall
|
|
90
|
+
context-guard-pack auto --root . --files src/app.py --query "entrypoint 검토" --top 1 --budget-bytes 12000 --json --no-artifact --apply-symbol-memory
|
|
91
|
+
context-guard-pack auto --root . --query "실패 테스트 검토" --top 8 --budget-bytes 12000 --json --no-artifact --apply-adaptive-k
|
|
81
92
|
context-guard-pack build --root . --manifest suggested-pack.json --budget-bytes 12000 --json
|
|
82
93
|
context-guard-pack build --root . --manifest suggested-pack.json --budget-bytes 12000 --json --no-artifact --delta-from-pack-id 0123456789abcdef0123
|
|
83
94
|
context-guard-pack slice --root . --path README.md --lines 1:40 --json
|
|
@@ -99,8 +110,9 @@ context-guard-statusline-merged
|
|
|
99
110
|
- **컨텍스트 관리 스캐너**는 누락된 `permissions.deny` 가드레일, Bash 출력 축약 훅, 상태표시줄 설정, 넓은 읽기 허용, 비용이 큰 기본 모델/추론 강도, 많은 MCP 서버, 크거나 민감해 보이는 에이전트 규칙 파일, 부피가 크거나 민감해 보이는 로컬 경로에 대한 자문형 context-exclusion 추천을 확인합니다.
|
|
100
111
|
- **대용량 읽기 가드와 심볼 리더**는 파일 전체 읽기 전에 검색, 심볼 구간, 작은 줄 범위 읽기 순서로 에이전트를 안내합니다. Python, JavaScript/TypeScript, Go, Rust 소스 구간 읽기를 지원합니다.
|
|
101
112
|
- **로컬 로그 보관소**는 큰 명령 출력을 기본적으로 `.context-guard/artifacts`에 가림 처리해 저장하고, 줄 번호가 있는 top error, 중복 라인 그룹, 가림 처리된 bounded suggested query, 안정적인 `contextguard-artifact:<id>` 핸들이 담긴 `output_sandbox` 요약 기록이나 요청한 정확한 줄 범위만 반환합니다. `receipt <artifact_id> --json`은 본문 없이 핸들과 재조회 명령만 다시 출력합니다. `get`과 `list`는 리브랜딩 이전의 `.claude-token-optimizer/artifacts` 요약 기록도 읽을 수 있습니다.
|
|
102
|
-
- **예산 기반 컨텍스트 패커**는 우선순위가 있는 로컬 파일 근거를 렌더링된 바이트 예산 안의 Markdown pack으로 조립하고, 포함·부분 포함·누락 source 메타데이터, bounded `.context-guard/packs` 요약 기록, 안전할 때만 정확한 가림 처리 `slice` 명령, 안전하지 않을 때의 `retrieval_omitted_reason`을 남깁니다. 추가된 `auto` 하위 명령은 추천과 pack build를 한 번에 실행하고, `auto --explain`은 manifest, pack 본문, receipt, byte budget을 바꾸지 않으면서 결정적 로컬 선택/build 이유를 짧게 추가합니다. JSON explain의 bounded repo-map은 sampled byte/token-proxy tree, category-only secret risk count, signature-first hint, explain-only graph rank, 기존 `slice`/symbol 재조회 힌트를 제공하지만 pack 선택이나 provider savings claim은 아닙니다. `suggest`는 로컬 query, diff, 명시 파일, 가림 처리된 output/test-output 신호를 `build`와 호환되는 manifest로 순위화하며 네트워크·모델 호출·임베딩·provider 비용 추정은 하지 않습니다. `suggest/auto --adaptive-k`는 `--adaptive-k-policy balanced|recall|precision` 및 선택적 recall/precision proxy gate, capped selected/omitted evidence, 구조화된 source-verification hint를 제공하지만 추천값을 자동 적용하거나 manifest/pack/receipt를 바꾸지 않습니다. 토큰 수는 측정된 provider token 절감이 아니라 추정 `chars_div_4` proxy입니다.
|
|
113
|
+
- **예산 기반 컨텍스트 패커**는 우선순위가 있는 로컬 파일 근거를 렌더링된 바이트 예산 안의 Markdown pack으로 조립하고, 포함·부분 포함·누락 source 메타데이터, bounded `.context-guard/packs` 요약 기록, 안전할 때만 정확한 가림 처리 `slice` 명령, 안전하지 않을 때의 `retrieval_omitted_reason`을 남깁니다. 추가된 `auto` 하위 명령은 추천과 pack build를 한 번에 실행하고, `auto --explain`은 manifest, pack 본문, receipt, byte budget을 바꾸지 않으면서 결정적 로컬 선택/build 이유를 짧게 추가합니다. JSON explain의 bounded repo-map은 sampled byte/token-proxy tree, category-only secret risk count, signature-first hint, explain-only graph rank, 기존 `slice`/symbol 재조회 힌트를 제공하지만 pack 선택이나 provider savings claim은 아닙니다. `suggest`는 로컬 query, diff, 명시 파일, 가림 처리된 output/test-output 신호를 `build`와 호환되는 manifest로 순위화하며 네트워크·모델 호출·임베딩·provider 비용 추정은 하지 않습니다. `suggest/auto --adaptive-k`는 `--adaptive-k-policy balanced|recall|precision` 및 선택적 recall/precision proxy gate, capped selected/omitted evidence, 구조화된 source-verification hint를 제공하지만 추천값을 자동 적용하거나 manifest/pack/receipt를 바꾸지 않습니다. 명시적 `auto --apply-symbol-memory`는 안전한 direct import neighbor slice를 최대 4개 manifest에 추가하고 동일 byte budget으로 다시 build합니다. explicit/query seed의 우선순위를 보존하고 secret-risk neighbor를 제외하며 exact fallback과 닫힌 `graph_application` 근거를 남깁니다. 토큰 수는 측정된 provider token 절감이 아니라 추정 `chars_div_4` proxy입니다.
|
|
103
114
|
- **Tool/MCP schema pruner**는 로컬 tool catalog를 bounded top-k 자문 리포트로 순위화하고, compact 요약 기록과 payload integrity check로 전체 가림 처리된 schema 재조회를 보존합니다. `defer-report`는 core inline tool과 deferred stub/namespace 요약을 나누고 gross deferred-schema 및 net initial-report `chars_div_4` proxy 회계를 보여주지만, deferred tool을 쓰기 전에는 전체 schema를 다시 조회해야 합니다.
|
|
115
|
+
- **적용형 adaptive breadth**는 명시적 `auto --apply-adaptive-k`에서만 동작합니다. 로컬 회귀 gate 통과 뒤 heuristic source를 줄이고 caller가 지정한 file/output/test-output 및 diff source는 항상 보존하며, 같은 byte budget으로 다시 build하고 `adaptive_k_application`을 기록합니다. 로컬 proxy는 provider token/cost 절감 주장을 허용하지 않습니다.
|
|
104
116
|
- **보수적 압축기**는 가림 처리된 stdin을 JSON, diff, 로그, 검색 출력, 코드, 산문으로 분류하고, 관측 바이트 근거와 추정 토큰 proxy를 함께 노출합니다.
|
|
105
117
|
- **정적 cache-score lint와 Anthropic 비용 가드/route advisor**는 `context-guard-cache-score`로 로컬 prompt/request cache layout과 사용자 제공 cache write/read multiplier 기반 amortization 위험을 안내하고, `context-guard cost preflight/observe/ledger/compile`로 호출 전 비용 추정, provider usage 대조, keyed-HMAC cache 위험 기록, 안정적인 prefix 배치 안내를 제공합니다. `context-guard route-advisor`는 caller가 제공한 workload JSON, provider feature 선언, usage telemetry, 외부·로컬 shifted cost를 읽는 local-only passive advisor이며 queue를 시작하거나 provider를 호출하거나 pricing 문서를 새로 가져오거나 provider feature 지식을 authoritative하게 취급하지 않고 total-cost accounting, batchability blocker, route 후보를 출력합니다. 원문 프롬프트를 저장하지 않고 Anthropic/provider prompt cache를 대체하지 않으며, 추천은 matched successful task, 비열등 quality evidence, shifted-cost accounting 없이는 hosted token/cost 절감 주장이 아닙니다.
|
|
106
118
|
- **출력 축약기**는 감싼 명령의 종료 코드를 보존하면서 긴 로그를 줄이고, `--digest markdown` 또는 `--digest json`으로 실행기 실패 정보, 가림 처리된 failure signature, 중복 라인 그룹, 다음 조회 제안이 담긴 요약을 만들 수 있습니다. `--artifact-receipt`를 digest mode와 함께 쓰면 sanitized 전체 출력을 로컬 artifact receipt로 저장하고 `contextguard-artifact:<id>` 핸들과 `context-guard-artifact receipt/get/search ...` 재조회 명령으로 누락된 slice를 다시 확장할 수 있습니다.
|
|
@@ -110,6 +122,12 @@ context-guard-statusline-merged
|
|
|
110
122
|
- **반복 실패 알림**은 Bash 실패가 반복될 때 같은 경로를 계속 재시도하지 않고 전략을 바꾸도록 안내합니다.
|
|
111
123
|
- **벤치마크 헬퍼**는 기준/변형 실행을 대응해 실제 토큰·비용 필드, 별도의 바이트 감소 간접 증거, 진단용 `wall_time_seconds`, `provider_cached_tokens`, provider-cache 사용 가능성 텔레메트리, report-level measurement-baseline contract, 파일 기반 `variant_prompt_files`, 선택적 run별 `self_hosted_metrics` JSONL ledger sidecar를 기록합니다. 이 sidecar는 hosted API 절감 주장에 합치지 않습니다.
|
|
112
124
|
|
|
125
|
+
### Claude Read의 정확한 적용 범위
|
|
126
|
+
|
|
127
|
+
설치되는 가드는 Claude Code `PreToolUse`의 `Read` matcher 훅입니다. 이 가드를 선택하면 setup은 기존 deny 값 중 정확히 `Read(./.env)`와 `Read(./.env.*)`만 제거하고, 비슷한 항목과 상대적 순서는 유지합니다. 훅은 제한된 대용량 파일 범위를 검사하고, root 또는 중첩 경로의 basename이 `.env`로 시작하면 차단합니다. 단, 정확히 `.env.example`, `.env.sample`, `.env.template`인 템플릿 이름은 허용하며 symlink 여부가 모호하면 차단합니다. `Glob`은 이름을 나열할 수 있습니다. `Grep`과 `Bash`는 파일 내용을 읽을 수 있고 이 훅의 범위 밖입니다. 이는 범용 `.env` 보호나 Bash 보호가 아닙니다.
|
|
128
|
+
|
|
129
|
+
훅은 symlink를 따라가지 않고 파일을 열어 같은 descriptor의 identity, size, modification time을 다시 검증합니다. 실제 Claude `Read`는 훅 반환 뒤 별도로 파일을 열기 때문에, 그 post-hook 구간의 파일 교체 가능성은 문서화된 TOCTOU 한계로 남습니다.
|
|
130
|
+
|
|
113
131
|
비용 가드의 로컬 HMAC 키는 기본적으로 `.context-guard/cost-ledger/hmac.key`에 자동 생성됩니다. 관리자가 직접 주입하는 경우 파일에는 필수 padding을 포함한 canonical URL-safe base64 32바이트 키만 정확히 들어 있어야 하며, trailing newline이나 공백은 허용하지 않습니다. 리포트는 키와 원문 프롬프트를 출력하지 않고, 로컬 ledger는 Anthropic/provider prompt cache를 대체하지 않습니다.
|
|
114
132
|
|
|
115
133
|
## brief 모드 (안내용)
|
|
@@ -118,6 +136,18 @@ brief 모드는 코딩 에이전트가 군더더기를 줄이도록 요청하되
|
|
|
118
136
|
|
|
119
137
|
세 가지 고정 레벨(`lite`, `standard`, `ultra`)이 [`brief/`](brief/)에 있습니다. 각 레벨은 에이전트 규칙·지시 파일(`AGENTS.md`, `CLAUDE.md`, Cursor 규칙 파일, Copilot 지시 등)에 들어가는 마커 구분 블록입니다. `context-guard setup --agent codex --scope project --brief-mode standard --plan`으로 미리 보고, `--yes`로 적용하며, 제거는 `--brief-mode off`를 사용하세요. 자세한 내용은 [`brief/README.md`](brief/README.md)를 참고하세요.
|
|
120
138
|
|
|
139
|
+
## Claude 조용한 진행 설명 (안내용)
|
|
140
|
+
|
|
141
|
+
조용한 진행 설명은 기본적으로 꺼져 있는 별도의 Claude 전용 규칙입니다. 선택적 사전 설명, 도구별 진행 중계, 군더기, 반복 중간 요약은 줄이되 승인·결정, 차단 요인, 실패, 파괴적 작업·보안 경고, 필수 진행 보고, 최종 결과, 변경 파일, 검증 결과는 유지합니다.
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
context-guard setup --rules-only --agent claude --scope project --narration-mode quiet --plan
|
|
145
|
+
context-guard setup --rules-only --agent claude --scope project --narration-mode quiet --yes
|
|
146
|
+
context-guard setup --rules-only --agent claude --scope project --narration-mode default --yes
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
이 격리된 작업은 프로젝트 `CLAUDE.md`의 ContextGuard narration 구간만 관리하며 settings, hook 또는 다른 에이전트 파일을 읽거나 바꾸지 않고 일반 setup 작업과 함께 사용할 수 없습니다. 최종 답변의 간결성·추론 깊이와 별개인 최선 노력 규칙이며, Gate C는 모델 준수나 절감 효과를 주장하지 않습니다.
|
|
150
|
+
|
|
121
151
|
## 절감 수치를 과장하지 않습니다
|
|
122
152
|
|
|
123
153
|
이 헬퍼들은 흔히 컨텍스트를 불필요하게 키우는 원인을 줄이지만, 고정된 절감률을 보장하지 않습니다. 실제 전후 비교 증거가 필요하면 `context-guard-bench --ledger-jsonl ... --report-json ... --dashboard-md ...`로 본인 작업에서 측정하세요. `--evidence-jsonl ...`는 deterministic local replay용이며 provider-export provenance가 완전하지 않으면 public claim 불가로 표시됩니다. 토큰 절감 주장은 대응 태스크 양쪽 모두에 `primary_tokens_measured`가 있을 때만 계산하며, report의 `matched_pair_evidence`가 성공한 baseline/variant task bucket을 transform, quality gate, 측정 가능 여부, claim boundary와 연결합니다. report의 `default_matrix`는 같은 evidence에서 trimming, artifact escrow, tool pruning, cache advice, adaptive-k, optional compression을 `default-on`/`advisory`/`experimental`/`reject/rework`로 분류하지만 report 전용이며 runtime default나 hosted savings claim을 바꾸지 않습니다. report의 `public_claim_readiness`는 release/public claim의 최종 gate로, matched successful task, provider-measured primary token/cost, quality non-inferiority, shifted-cost accounting, 명시적 confidence/failure note, complete provider-export provenance가 모두 통과해야 `claim_allowed=true`가 되며 그 외 hosted savings claim은 금지됩니다. wall-time과 provider-cache 필드는 진단용 텔레메트리이지 단독 절감 증거가 아닙니다. 감사의 `cache_friendliness`, [`cache_diagnostics`](https://github.com/ictechgy/context-guard/blob/main/docs/cache-diagnostics-schema.md), `cache_layout_advice`는 관측/추론/가설/불가 경계를 둔 휴리스틱 배치·cache-read 신호와 순위화된 확인/실험이며 청구 기준이나 provider-cache 증명이 아닙니다. 벤치마크 CSV 스키마는 엄격하므로 헬퍼 업그레이드 후에는 새 CSV를 시작하거나 헤더를 마이그레이션하세요. 작업 유형별 합성 예시는 [`docs/benchmark-workflow-examples.md`](https://github.com/ictechgy/context-guard/blob/main/docs/benchmark-workflow-examples.md)에 있고, fixture-only 실험 시작 예시는 [`docs/experimental-benchmark-fixtures.md`](https://github.com/ictechgy/context-guard/blob/main/docs/experimental-benchmark-fixtures.md)에 있습니다.
|
|
@@ -142,6 +172,18 @@ context-guard experiments verify proof-carrying-context --artifact-dir ./artifac
|
|
|
142
172
|
|
|
143
173
|
`context-guard mcp`와 `context-guard-mcp`는 의존성 없는 로컬 stdio MCP 자식 프로세스를 실행합니다. 프로세스는 root와 namespace 하나로 격리되고 sanitization된 compression, 정확한 sanitization artifact fallback, 로컬 통계만 제공합니다. HTTP, 네트워크, provider, model, proxy 통합이나 client 설정 변경은 없습니다. artifact는 namespace 사이에서 접근할 수 없고 hosted token/cost 절감도 주장하지 않습니다.
|
|
144
174
|
|
|
175
|
+
설치된 Receipt companion도
|
|
176
|
+
`context-guard-receipt-mcp --root /absolute/repository`로 명시적으로 실행할 수
|
|
177
|
+
있습니다. `receipt_context` 도구는 사용자가 `eligible`이라고 명시한 상대
|
|
178
|
+
파일·로그를 보수적 byte router가 유리하다고 판단할 때 compact process-local
|
|
179
|
+
exact reference로 저장하고, 같은 live reference를 재사용하며, 한 번에 최대
|
|
180
|
+
65,536바이트의 exact slice를 조회합니다. 선택적 task scope와 명시적 release는
|
|
181
|
+
process-local context GC를 제공하고, content-free history에는 keyed digest와
|
|
182
|
+
결정만 남습니다. `receipt_diagnose`는 비적용 firewall/router와 prefix 재사용
|
|
183
|
+
scout/surgeon 안내를 제공하며, 명시적 private `--state-dir`는 authenticated
|
|
184
|
+
advisory `receipt_twin`만 활성화합니다. 자동 등록, prompt 가로채기, capability의
|
|
185
|
+
재시작 후 지속 저장, provider 호출, hosted 절감 주장은 하지 않습니다.
|
|
186
|
+
|
|
145
187
|
## 로컬 배포 테스트
|
|
146
188
|
|
|
147
189
|
마켓플레이스 저장소 루트에서 실행합니다.
|
|
@@ -46,6 +46,15 @@ context-guard setup --agent codex --scope project --brief-mode standard --plan
|
|
|
46
46
|
npx @ictechgy/context-guard --version
|
|
47
47
|
```
|
|
48
48
|
|
|
49
|
+
The compact `bash_reference_v1` Bash-output route is intentionally not
|
|
50
|
+
available from this marketplace-plugin/source layout. It requires an exact
|
|
51
|
+
project-local npm installation of `@ictechgy/context-guard@0.5.0` and its
|
|
52
|
+
`@ictechgy/context-guard-receipt@0.2.0` dependency, then explicit
|
|
53
|
+
`setup --agent claude --scope project --bash-reference-v1`. Plugin setup keeps
|
|
54
|
+
legacy trimming and warns instead of installing a no-op reference flag. See the
|
|
55
|
+
repository distribution guide for activation, disablement, seven-day handle,
|
|
56
|
+
and preserved-state details.
|
|
57
|
+
|
|
49
58
|
From this repository root, run helpers by path:
|
|
50
59
|
|
|
51
60
|
```bash
|
|
@@ -84,6 +93,8 @@ context-guard-sanitize-output -- git diff
|
|
|
84
93
|
context-guard-filter validate --config .context-guard/filter-dsl.json
|
|
85
94
|
context-guard-filter run --config .context-guard/filter-dsl.json -- git status --short
|
|
86
95
|
context-guard-pack auto --root . --query "review failing tests" --diff HEAD --manifest-out suggested-pack.json --pack-out context-pack.md --budget-bytes 12000 --json --explain --adaptive-k --adaptive-k-policy recall --symbol-memory
|
|
96
|
+
context-guard-pack auto --root . --files src/app.py --query "review entrypoint" --top 1 --budget-bytes 12000 --json --no-artifact --apply-symbol-memory
|
|
97
|
+
context-guard-pack auto --root . --query "review failing tests" --top 8 --budget-bytes 12000 --json --no-artifact --apply-adaptive-k
|
|
87
98
|
context-guard-pack build --root . --manifest suggested-pack.json --budget-bytes 12000 --json
|
|
88
99
|
context-guard-pack build --root . --manifest suggested-pack.json --budget-bytes 12000 --json --no-artifact --delta-from-pack-id 0123456789abcdef0123
|
|
89
100
|
context-guard-pack slice --root . --path README.md --lines 1:40 --json
|
|
@@ -108,8 +119,9 @@ Opt-in `build`/`auto --sketch-duplicate-veto` applies a rank-stable pre-budget g
|
|
|
108
119
|
- **Large-read guard and symbol reader** guide the agent from search to symbol slices to small line ranges before attempting a whole-file read. Supported source slices include Python, JavaScript/TypeScript, Go, and Rust.
|
|
109
120
|
- **Declarative output filter** validates user-owned JSON filter files outside package code and applies the first matching line filter only as an explicit `run --config ... -- <command>` wrapper. Invalid configs, no-match commands, filter errors, empty filtered output, and protected `git`/test/lint/`gh` command failures preserve original stdout/stderr and exit code. Filtered mode applies line rules to combined stdout+stderr and writes the filtered result to stdout; `--json-report` diagnostics go to stderr, except protected nonzero passthrough suppresses reports to keep stderr raw. It is local and opt-in, with no savings guarantee.
|
|
110
121
|
- **Artifact store** saves large sanitized command output under `.context-guard/artifacts` by default and returns compact receipts, local sandbox search results, or exact requested slices. JSON receipts include line-numbered top errors, duplicate-line groups, sanitized bounded suggested queries, and an `output_sandbox` envelope with a stable `contextguard-artifact:<id>` handle. `receipt <artifact_id> --json` rehydrates metadata-only handles without content. `search` scans sanitized local artifacts by literal substring, emits capped match/context records, and includes `get --lines START:END` rehydration commands without hosted token/cost savings claims. Custom `--dir` raw paths stay redacted by default; reuse the same `--dir` or opt into `search --show-paths` for a directly executable local command. In suggested `--lines START:END` queries, `--max-lines` is only the returned-line cap for that selected range, not a wider selector. `get`, `list`, and `search` can also read legacy `.claude-token-optimizer/artifacts` receipts.
|
|
111
|
-
- **Budgeted context packer** assembles prioritized local file evidence into a rendered byte-budgeted Markdown pack with included/partial/omitted source metadata, bounded `.context-guard/packs` receipts, exact sanitized `slice` commands when safe, and `retrieval_omitted_reason` when a path/root should not be echoed. The additive `auto` subcommand runs that recommendation and pack build in one step, and `auto --explain` adds compact deterministic local selection/build reasons without changing the manifest, pack body, receipt, or byte budget. JSON explain also includes bounded repo-map metadata: sampled byte/token-proxy tree entries, category-only secret-risk counts, signature-first hints, explain-only graph ranks, and exact `slice`/symbol retrieval hints. `suggest` remains available to rank local query, diff, explicit file, and sanitized output/test-output signals into a build-compatible manifest without network, model, embedding, or provider-cost calls. `suggest/auto --adaptive-k` adds advisory-only shrink/expand top-k metadata from local score distribution, byte-budget fit, and clamped score-mass recall/precision proxies. `--adaptive-k-policy balanced|recall|precision` plus optional recall/precision proxy gates selects the local recommendation policy; gate failures are metadata-only. The adaptive block includes capped selected/omitted evidence and structured source-verification hints, and it never applies the recommendation automatically or changes the manifest, pack body, receipt, or byte budget. `auto --symbol-memory` adds repo-map-derived symbol/graph advisory metadata with exact `slice`/`read-symbol` verification hints and still does not change selection or pack output. Token counts are estimated `chars_div_4` proxies, not measured provider-token savings.
|
|
122
|
+
- **Budgeted context packer** assembles prioritized local file evidence into a rendered byte-budgeted Markdown pack with included/partial/omitted source metadata, bounded `.context-guard/packs` receipts, exact sanitized `slice` commands when safe, and `retrieval_omitted_reason` when a path/root should not be echoed. The additive `auto` subcommand runs that recommendation and pack build in one step, and `auto --explain` adds compact deterministic local selection/build reasons without changing the manifest, pack body, receipt, or byte budget. JSON explain also includes bounded repo-map metadata: sampled byte/token-proxy tree entries, category-only secret-risk counts, signature-first hints, explain-only graph ranks, and exact `slice`/symbol retrieval hints. `suggest` remains available to rank local query, diff, explicit file, and sanitized output/test-output signals into a build-compatible manifest without network, model, embedding, or provider-cost calls. `suggest/auto --adaptive-k` adds advisory-only shrink/expand top-k metadata from local score distribution, byte-budget fit, and clamped score-mass recall/precision proxies. `--adaptive-k-policy balanced|recall|precision` plus optional recall/precision proxy gates selects the local recommendation policy; gate failures are metadata-only. The adaptive block includes capped selected/omitted evidence and structured source-verification hints, and it never applies the recommendation automatically or changes the manifest, pack body, receipt, or byte budget. `auto --symbol-memory` adds repo-map-derived symbol/graph advisory metadata with exact `slice`/`read-symbol` verification hints and still does not change selection or pack output. Explicit `auto --apply-symbol-memory` instead adds at most four safe direct import-neighbor slices, keeps explicit/query seeds at higher priority, excludes secret-risk neighbors, and rebuilds within the same byte budget while retaining exact fallback and a closed `graph_application` record. Token counts are estimated `chars_div_4` proxies, not measured provider-token savings.
|
|
112
123
|
- **Tool/MCP schema pruner** ranks local tool catalogs into bounded top-k advisory reports while preserving full sanitized schema fallback through compact receipts and payload integrity checks. `defer-report` additionally separates core inline tools from deferred stubs/namespaces and reports gross deferred-schema plus net initial-report char/4 proxy accounting; full schemas still must be retrieved before deferred tool use.
|
|
124
|
+
- **Applied adaptive breadth** is available only through explicit `auto --apply-adaptive-k`. It prunes heuristic-selected sources after local regression gates pass, always retains caller-declared file/output/test-output and diff sources, rebuilds within the same byte budget, and records `adaptive_k_application`; local proxies do not authorize provider-token or cost-savings claims.
|
|
113
125
|
- **Conservative compressor** classifies sanitized stdin as JSON, diff, log, search output, code, or prose and shrinks it with observed byte evidence plus estimated token proxies. Add `--protected-policy` for opt-in protected-zone class/count metadata that denies semantic rewrites for code fences, diffs, identifiers, numeric constants, hashes, paths, stack frames, quoted strings, and JSON keys while preserving exact-retrieval guidance. Add `--mode readable` only for sanitized prose previews: it uses deterministic sentence windows, blocks prompt-like/high-risk protected signals, stores no raw protected spans, and does not run learned compressors, models, embeddings, or rerankers.
|
|
114
126
|
- **Static cache-score lint plus Anthropic cost guard and route advisor** provides `context-guard-cache-score` for local prompt/request cache layout checks, with optional user-supplied cache write/read multiplier amortization risk, and `context-guard cost preflight/observe/ledger/compile` for passive pre-call estimates, provider-usage reconciliation, keyed-HMAC cache-risk history, and stable-prefix layout advice. `context-guard route-advisor` is a local-only passive advisor for caller-supplied workload JSON, provider feature declarations, usage telemetry, and shifted external/local costs; it emits total-cost accounting, batchability blockers, and route candidates without starting a queue, calling providers, refreshing pricing docs, or treating provider feature knowledge as authoritative. It stores no raw prompt text, does not replace Anthropic/provider prompt caching, and its recommendations are not hosted token/cost savings claims without matched successful tasks, non-inferior quality evidence, and shifted-cost accounting.
|
|
115
127
|
- **Output trimmer** preserves the wrapped command exit code, trims long logs, and can emit `--digest markdown` or `--digest json` summaries with runner failure facts, sanitized failure signatures, duplicate-line groups, and suggested next queries. Add `--artifact-receipt` with digest mode to store the exact sanitized full output as a local artifact receipt; keep the `contextguard-artifact:<id>` handle and re-expand omitted slices with emitted `context-guard-artifact receipt/get/search ...` commands.
|
|
@@ -119,6 +131,12 @@ Opt-in `build`/`auto --sketch-duplicate-veto` applies a rank-stable pre-budget g
|
|
|
119
131
|
- **Repeated-failure nudge** warns after repeated Bash failures so the agent switches strategy instead of retrying the same context-heavy path.
|
|
120
132
|
- **Benchmark helper** records matched baseline/variant runs with real token and cost fields, separate byte-reduction proxy evidence, diagnostic `wall_time_seconds`, `provider_cached_tokens`, provider-cache availability telemetry, a report-level measurement-baseline contract, file-backed `variant_prompt_files`, and optional per-run `self_hosted_metrics` JSONL ledger sidecars that stay out of hosted API savings claims.
|
|
121
133
|
|
|
134
|
+
### Exact Claude Read surface
|
|
135
|
+
|
|
136
|
+
The installed guard is a Claude Code `PreToolUse` hook with matcher `Read`. When selected, setup removes only the exact legacy deny values `Read(./.env)` and `Read(./.env.*)` while preserving similar entries and their relative order. The hook checks bounded large-file ranges and denies root or nested paths whose basename begins `.env`, except the exact template names `.env.example`, `.env.sample`, and `.env.template`; ambiguous symlink paths fail closed. `Glob` can still list names. `Grep` and `Bash` can read file contents and are outside this hook. This is not universal `.env` or Bash protection.
|
|
137
|
+
|
|
138
|
+
The hook opens without following symlinks and revalidates identity, size, and modification time on that descriptor. Claude performs the actual `Read` with a separate open after the hook returns, so replacement during that post-hook window remains a documented TOCTOU limitation.
|
|
139
|
+
|
|
122
140
|
Cost guard creates its local HMAC key automatically at `.context-guard/cost-ledger/hmac.key`. If you provision that file yourself, it must contain exactly one canonical URL-safe base64 32-byte key with required padding and no trailing newline or whitespace. Reports never emit the key or raw prompt text, and the local ledger does not replace Anthropic/provider prompt caching.
|
|
123
141
|
|
|
124
142
|
## Brief mode (advisory)
|
|
@@ -127,6 +145,18 @@ Brief mode ships agent-neutral, advisory rule snippets that ask a coding agent t
|
|
|
127
145
|
|
|
128
146
|
Three deterministic levels — `lite`, `standard`, `ultra` — live under [`brief/`](brief/). Each is a single marker-delimited block for an agent's rule/instruction file (such as `AGENTS.md`, `CLAUDE.md`, a Cursor rules file, or Copilot instructions). Use `context-guard setup --agent codex --scope project --brief-mode standard --plan`, apply with `--yes`, and remove with `--brief-mode off`. See [`brief/README.md`](brief/README.md).
|
|
129
147
|
|
|
148
|
+
## Quiet narration for Claude (advisory)
|
|
149
|
+
|
|
150
|
+
Quiet narration is a separate, default-off Claude-only rule that suppresses discretionary preambles, per-tool narration, filler, and repeated interim summaries while preserving approvals and decisions, blockers, failures, destructive or security warnings, required progress, the final result, changed files, and verification.
|
|
151
|
+
|
|
152
|
+
```bash
|
|
153
|
+
context-guard setup --rules-only --agent claude --scope project --narration-mode quiet --plan
|
|
154
|
+
context-guard setup --rules-only --agent claude --scope project --narration-mode quiet --yes
|
|
155
|
+
context-guard setup --rules-only --agent claude --scope project --narration-mode default --yes
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
The isolated operation manages only ContextGuard's narration span in project `CLAUDE.md`; it does not read or change settings, hooks, or other agents' files and cannot be combined with normal setup actions. The rule is best-effort, independent of final-answer brevity or reasoning depth, and Gate C makes no model-compliance or savings claim.
|
|
159
|
+
|
|
130
160
|
## Conservative claims
|
|
131
161
|
|
|
132
162
|
These helpers reduce common sources of context bloat, but they do not guarantee a fixed percentage savings. Use `context-guard-bench --ledger-jsonl ... --report-json ... --dashboard-md ...` when you need measured before/after evidence for your own tasks; add `--evidence-jsonl ...` only for deterministic local replay that remains non-claim-eligible unless provider-export provenance is complete; token-savings claims require `primary_tokens_measured` on both matched sides, and the report's `matched_pair_evidence` links each successful baseline/variant task bucket to the transform, quality gate, measurement availability, and claim boundary. The report's `default_matrix` classifies trimming, artifact escrow, tool pruning, cache advice, adaptive-k, and optional compression as `default-on`, `advisory`, `experimental`, or `reject/rework` from that evidence, but it is reporting-only and does not change runtime defaults or authorize hosted savings claims. The report's `public_claim_readiness` is the authoritative release/public-claim gate: matched successful tasks, provider-measured primary tokens/cost, quality non-inferiority, shifted-cost accounting, explicit confidence/failure notes, and complete provider-export provenance must all pass before `claim_allowed=true`; unsupported hosted savings claims are forbidden otherwise. Wall-time/provider-cache fields are diagnostic telemetry, not standalone savings proof. Audit `cache_friendliness`, [`cache_diagnostics`](https://github.com/ictechgy/context-guard/blob/main/docs/cache-diagnostics-schema.md), and `cache_layout_advice` findings are heuristic layout/cache-read signals and ranked checks/experiments with observed/inferred/hypothesis/unavailable boundaries, not billing authority or provider-cache proof. Benchmark CSV schemas are strict, so start a new CSV or migrate the header after helper upgrades. Workflow-specific synthetic examples live in [`docs/benchmark-workflow-examples.md`](https://github.com/ictechgy/context-guard/blob/main/docs/benchmark-workflow-examples.md), and fixture-only experimental task/variant starters live in [`docs/experimental-benchmark-fixtures.md`](https://github.com/ictechgy/context-guard/blob/main/docs/experimental-benchmark-fixtures.md).
|
|
@@ -178,6 +208,19 @@ Cross-agent rule snippets are advisory: the target agent may ignore them, so mea
|
|
|
178
208
|
|
|
179
209
|
`context-guard mcp` and `context-guard-mcp` launch a dependency-free local stdio MCP child process. A process is isolated to one root and namespace and exposes only sanitized compression, sanitized exact artifact fallback, and local statistics. It has no HTTP, network, provider, model, or proxy integration and never mutates client configuration. Artifacts are inaccessible across namespaces; no hosted token/cost savings are claimed.
|
|
180
210
|
|
|
211
|
+
The installed Receipt companion can also be launched explicitly as
|
|
212
|
+
`context-guard-receipt-mcp --root /absolute/repository`. Its
|
|
213
|
+
`receipt_context` tool stores one explicitly eligible relative file or log as a
|
|
214
|
+
compact process-local exact reference when the conservative byte router finds
|
|
215
|
+
that beneficial, reuses the live reference, and reads exact slices of at most
|
|
216
|
+
65,536 bytes. Optional task scopes and explicit release provide process-local
|
|
217
|
+
context GC; content-free history stores only keyed digests and decisions.
|
|
218
|
+
`receipt_diagnose` exposes non-applying firewall/router and prefix-reuse
|
|
219
|
+
scout/surgeon advice, while an explicit private `--state-dir` enables only the
|
|
220
|
+
authenticated advisory `receipt_twin`. It does not auto-register, intercept
|
|
221
|
+
prompts, persist capabilities across restart, call a provider, or make a hosted
|
|
222
|
+
savings claim.
|
|
223
|
+
|
|
181
224
|
## Local test before publishing
|
|
182
225
|
|
|
183
226
|
From the marketplace repository root:
|