@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.
Files changed (32) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/README.ko.md +128 -2
  3. package/README.md +144 -3
  4. package/docs/distribution.md +100 -0
  5. package/package.json +4 -1
  6. package/plugins/context-guard/.claude-plugin/plugin.json +1 -1
  7. package/plugins/context-guard/README.ko.md +43 -1
  8. package/plugins/context-guard/README.md +44 -1
  9. package/plugins/context-guard/bin/bash_reference_policy.py +967 -0
  10. package/plugins/context-guard/bin/context-guard-artifact +90 -9
  11. package/plugins/context-guard/bin/context-guard-audit +169 -66
  12. package/plugins/context-guard/bin/context-guard-bench +9865 -211
  13. package/plugins/context-guard/bin/context-guard-compress +90 -8
  14. package/plugins/context-guard/bin/context-guard-diet +1 -7
  15. package/plugins/context-guard/bin/context-guard-experiments +5 -1
  16. package/plugins/context-guard/bin/context-guard-failed-nudge +777 -83
  17. package/plugins/context-guard/bin/context-guard-guard-read +496 -57
  18. package/plugins/context-guard/bin/context-guard-mcp +2 -1
  19. package/plugins/context-guard/bin/context-guard-pack +1570 -150
  20. package/plugins/context-guard/bin/context-guard-read-symbol +7 -2
  21. package/plugins/context-guard/bin/context-guard-rewrite-bash +2669 -236
  22. package/plugins/context-guard/bin/context-guard-sanitize-output +723 -92
  23. package/plugins/context-guard/bin/context-guard-setup +1944 -222
  24. package/plugins/context-guard/bin/context-guard-statusline +163 -55
  25. package/plugins/context-guard/bin/context-guard-statusline-merged +78 -23
  26. package/plugins/context-guard/bin/context-guard-tool-prune +44 -11
  27. package/plugins/context-guard/bin/context-guard-trim-output +795 -48
  28. package/plugins/context-guard/brief/README.md +19 -0
  29. package/plugins/context-guard/brief/narration-mode.quiet.md +21 -0
  30. package/plugins/context-guard/lib/context_guard_commands.py +10 -2
  31. package/plugins/context-guard/lib/credential_policy.py +185 -0
  32. package/plugins/context-guard/lib/transcript_usage_reducer.py +378 -0
package/CHANGELOG.md CHANGED
@@ -4,6 +4,86 @@ All notable changes for the ContextGuard plugin are documented here.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ - Added a provider-free `context-guard-receipt evaluate phase` surface with
8
+ closed P2-P6 input/result schemas. It computes shadow/canary/router/adjunct/
9
+ specialized-track readiness from bounded canonical local records while
10
+ keeping runtime activation, generalization, provider calls, and savings
11
+ claims disabled behind the existing sequential phase gates.
12
+ - Changed the discarded v2 Bash canary's fixed marker write from denied shell
13
+ output redirection to an existing MiniShell-v1-supported `python3 -c` route.
14
+ Both real hook modes now guard the exact command in provider-free tests, and
15
+ the offline fake host honors hook denials before creating any marker.
16
+ - Added an explicit `--study-v2-use-existing-login` gate for executable v2
17
+ provider actions. `prepare` now verifies and pseudonymously binds the exact
18
+ first-party Claude login plus its owned, non-writable HOME identity without
19
+ persisting email or organization text. Every provider reservation rechecks
20
+ that binding, keeps XDG/session paths isolated, excludes credential-shaped
21
+ environment variables, and omits `CLAUDE_CONFIG_DIR`; `analyze` remains
22
+ provider- and auth-independent.
23
+ - Bound both discarded v2 Bash-routing canary calls to the same hard `$0.75`
24
+ per-call Claude CLI budget as each analytic task. The value is part of the
25
+ immutable canary contract, so prepare/resume rejects drift; the frozen study's
26
+ 218 consumed/reserved identities imply a `$163.50` arithmetic maximum. The
27
+ CLI enforces each process cap; there is no separate aggregate CLI limiter.
28
+ - Published the sanitized result of the first frozen 12-task live study. The
29
+ study is explicitly `inconclusive`: one arm-unit exhausted its fixed retry,
30
+ no favorable subset or correction assessment was analyzed, and no token or
31
+ cost savings claim is allowed.
32
+
33
+ ## [0.5.1] - 2026-08-19
34
+
35
+ - Bounded context-pack source, diff, and non-Git traversal input before
36
+ allocation; made Markdown evidence fences content-derived; and reused one
37
+ immutable source snapshot across suggest/build so representative pack latency
38
+ falls from tens of seconds to sub-second without changing ordinary pack bytes.
39
+ - Pinned automatic hook and statusline runtimes instead of trusting ambient
40
+ `PATH`, Python startup variables, shell startup variables, or executable
41
+ overrides, while retaining setup-approved OMC integration.
42
+ - Added the backward-compatible Receipt external-approval v2 envelope whose
43
+ scope truthfully binds manual owner cleanup, plus bounded V4 authorization
44
+ lock waits, read-only ledger snapshots, cached immutable selection artifacts,
45
+ and shared V3/V4 failure conformance tests.
46
+ - Preserved sparse token availability in the Mac consumer and added the
47
+ provider-live test directory to the release gate.
48
+
49
+ ## [0.5.0] - 2026-08-06
50
+
51
+ - Added the default-off Claude Code `PreToolUse:Bash` reference route. After
52
+ strong local sanitization, long merged command output can stay in a private
53
+ project-local Receipt store while the transcript receives a compact,
54
+ exact-retrieval handle and an executable `context-guard reference` command.
55
+ Retrieval derives private state internally and pages exact UTF-8 output in
56
+ fixed 20,000-byte-or-smaller chunks, so resolving a handle cannot replay the
57
+ complete 10 MB capture in one turn. The legacy trim route and unchanged route
58
+ remain deterministic fallbacks; source/plugin-only installs cannot enable
59
+ this npm-only mode.
60
+ - Added the independently versioned `@ictechgy/context-guard-receipt@0.2.0`
61
+ exact dependency, fixed seven-day reference expiry, bounded authenticated
62
+ import recovery journal, 10,000,000-byte merged capture ceiling, and
63
+ expired/revoked reference refusal. Installation and disablement never erase
64
+ stored artifacts automatically.
65
+ - Added an executable three-arm study across `host_unmodified`, `legacy_trim`,
66
+ and `bash_reference_v1`, with an explicit `prepare` → `canary` → `run`/`resume`
67
+ → `analyze` lifecycle. `prepare` binds the CLI and runs local
68
+ `--version`/`--help` probes without a model request. Provider/model requests
69
+ occur only during canary and analytic execution. A separate provider-free
70
+ offline rehearsal exercises the lifecycle with a native fake CLI. The study
71
+ binds a fixed 12-task corpus and reports the legacy contrast diagnostically;
72
+ without an independent power model the result is descriptive-only and cannot
73
+ authorize a savings claim.
74
+ - Added build-once npm candidate manifests, exact cross-package hashes/SRI,
75
+ paired clean-install discovery smoke, separate trusted publication to
76
+ `next`, and preflight/rollback-aware promotion to `latest`. No package is
77
+ published or promoted automatically by this release.
78
+
79
+ ## [0.4.16] - 2026-08-01
80
+
81
+ - Sanitizer output-scanning is now one monotonic left-to-right pass. All nine location-prefix consumers previously re-parsed the same optional `path:line:` fragment at every offset, which made lines with few colons quadratic: a single 82,015-byte line took 2.62 s and a 100,014-byte line took 3.98 s. The leading prefix is identified once and the seven unanchored consumers run as fragment-free twins, while the two `^`-anchored header consumers keep their original patterns because they were never a per-offset cost. The same lines now take 64.3 ms and 0.078 s, with doubling ratios of 1.84 to 2.01. Redaction output is byte-identical to the previous implementation, pinned by a differential oracle against a hash-frozen baseline across eleven corpora, three sanitization contexts, both path-display modes, and both shared-state and per-line runs.
82
+ - `context-guard-trim-output --digest` no longer inflates small output. When a command succeeds and its output is already smaller than the digest would be, the output is passed through with a one-line marker; a 19-byte output previously produced a 461-byte markdown digest or a 755-byte JSON digest. A failing command always keeps the digest, because that is where the exit code and failure signature live, and requesting `--artifact-receipt` always keeps it too. Pass `--digest-always` to force the structured digest in every case.
83
+ - Both READMEs now document the standing per-request cost of the advisory rule blocks (`brief-mode.lite` 1,487 bytes, `brief-mode.standard` 1,568, `brief-mode.ultra` 1,523, `narration-mode.quiet` 866) and frame that size as the break-even threshold a reply-length reduction has to clear. Hook guardrails are contrasted honestly: they charge only when they act, and a sub-threshold `Read` adds 3 bytes.
84
+ - Added a default-off, Claude-only quiet-narration rule managed through a dedicated rules-only setup path. It suppresses discretionary narration while preserving approvals, blockers, failures, safety warnings, final results, changed files, and verification; it does not activate settings or hooks or claim guaranteed savings.
85
+ - Benchmark measurement substrate for the planned token-savings study: scheduling, accounting, resume, and inference surfaces plus a real twelve-task fixture suite with out-of-workspace success checkers and a zero-cost seventy-two-run fake-provider rehearsal. These are measurement-enabling only. No provider-measured token or cost savings are claimed, and the rehearsal explicitly records that its own token counts are scripted local fixtures.
86
+
7
87
  ## [0.4.15] - 2026-07-15
8
88
 
9
89
  - Added conservative plan-only and evaluation-only proof-carrying-context, semantic-GC, and image-context-pack surfaces without enabling automatic omission, renderer/OCR/provider/proxy execution, promotion authority, or hosted savings claims.
package/README.ko.md CHANGED
@@ -95,6 +95,33 @@ brief 모드는 코딩 에이전트가 군더더기를 줄이도록 요청하되
95
95
 
96
96
  사전 정의된 세 레벨이 [`plugins/context-guard/brief/`](plugins/context-guard/brief/)에 포함됩니다: `lite`, `standard`, `ultra`. 각 레벨은 에이전트 규칙·지시 파일(`AGENTS.md`, `CLAUDE.md`, Cursor 규칙 파일, Copilot 지시 등)에 들어가는 마커 구분 블록입니다. `context-guard setup --agent codex --scope project --brief-mode standard --plan`으로 미리 보고, 적용은 `--yes`로 다시 실행하며, 제거는 `--brief-mode off`를 사용하세요. 자세한 내용은 [`plugins/context-guard/brief/README.md`](plugins/context-guard/brief/README.md)를 참고하세요.
97
97
 
98
+ ### 상시 비용과 손익분기
99
+
100
+ 안내용 규칙 블록은 공짜가 아닙니다. 에이전트의 규칙 파일에 상주하므로 설치해 둔 동안 모든 요청에 다시 실려 갑니다.
101
+
102
+ | 관리 블록 | 설치 크기 |
103
+ | --- | --- |
104
+ | `brief-mode.lite` | 1,487 바이트 |
105
+ | `brief-mode.standard` | 1,568 바이트 |
106
+ | `brief-mode.ultra` | 1,523 바이트 |
107
+ | `narration-mode.quiet` | 866 바이트 |
108
+
109
+ 이 비용은 요청마다 선불로 확정되는 반면, 이득은 ContextGuard가 강제할 수 없는 확률적인 응답 길이 감소입니다. 턴 수가 적은 세션이나 이미 간결하게 답하는 에이전트에서는 블록이 절감분보다 더 들 수 있습니다. 훅 기반 가드레일은 성질이 다릅니다. 실제로 개입할 때만 비용이 들고, 측정된 최악의 경우도 작습니다. 임계값 이하 `Read`는 3바이트를 더하고, 대용량 읽기를 반복 시도해도 첫 경고 이후에는 누적되지 않고 오히려 줄어듭니다.
110
+
111
+ 토큰 효과를 노려 규칙 블록을 설치하기 전에 직접 측정하십시오. `context-guard-bench`로 블록이 있는 경우와 없는 경우를 동일 과제에서 비교하고, 블록의 설치 크기를 응답 길이 감소가 넘어야 하는 손익분기점으로 취급하십시오. 여기 적힌 바이트 수는 관측값이지만 토큰 효과는 관측값이 아니며, 고정된 절감률을 보장하지 않습니다.
112
+
113
+ ## Claude 조용한 진행 설명 (안내용)
114
+
115
+ 조용한 진행 설명은 기본적으로 꺼져 있는 별도의 Claude 전용 규칙입니다. 선택적 사전 설명, 도구별 진행 중계, 군더더기, 반복 중간 요약은 줄이지만 승인·결정 요청, 차단 요인, 실패, 파괴적 작업·보안 경고, 상위 우선순위가 요구하는 진행 보고, 최종 결과, 변경 파일, 검증 결과는 유지합니다. 최종 답변의 간결성이나 추론 깊이와는 별개인 최선 노력 규칙이며, 토큰·비용 절감을 **보장하지 않습니다.**
116
+
117
+ ```bash
118
+ context-guard setup --rules-only --agent claude --scope project --narration-mode quiet --plan
119
+ context-guard setup --rules-only --agent claude --scope project --narration-mode quiet --yes
120
+ context-guard setup --rules-only --agent claude --scope project --narration-mode default --yes
121
+ ```
122
+
123
+ 이 격리된 작업은 프로젝트 `CLAUDE.md` 안의 ContextGuard narration 구간만 관리합니다. Claude settings, hook, permission, statusline, model default 또는 다른 에이전트 규칙 파일은 읽거나 바꾸지 않습니다. brief mode, 초기화, skill 생성 또는 일반 setup 작업과 함께 사용할 수 없습니다. Gate C는 정적 규칙과 setup 부작용만 검증하며 모델의 준수나 수치 절감 주장을 증명하지 않습니다.
124
+
98
125
  ## 직접 측정하는 방법
99
126
 
100
127
  절감 수치가 필요하면 실제 작업에서 직접 측정하세요.
@@ -194,6 +221,62 @@ npm exec @ictechgy/context-guard -- --version
194
221
 
195
222
  `--scope project`는 `AGENTS.md`, `.agents/skills/...`처럼 저장소 안 파일에 적용합니다. `--scope user`는 전체 사용자 환경에 적용하려는 경우에만 의도적으로 사용하세요. 실제 적용에는 `--yes`와 명시적인 `--agent`가 필요하며, 지원되는 쓰기는 되돌리기 기록을 남깁니다.
196
223
 
224
+ ### Claude Code용 선택적 Bash reference
225
+
226
+ `bash_reference_v1` 경로는 정확한 프로젝트 로컬 npm 설치에서만 사용할 수
227
+ 있습니다. 루트 패키지는 `@ictechgy/context-guard-receipt@0.2.1`을 정확히
228
+ 고정합니다. global npm, `npx`, 소스 체크아웃, Homebrew, Claude marketplace
229
+ plugin 배치에서는 기존 Bash trim 동작을 유지하고 setup이 reference 경로를
230
+ 사용할 수 없다고 알립니다.
231
+
232
+ ```bash
233
+ npm install --save-exact @ictechgy/context-guard@0.5.1
234
+ ./node_modules/.bin/context-guard setup --root . --agent claude --scope project --bash-reference-v1 --plan
235
+ ./node_modules/.bin/context-guard setup --root . --agent claude --scope project --bash-reference-v1 --yes
236
+ ```
237
+
238
+ 기본 비활성인 이 `PreToolUse:Bash` 모드는 강하게 가림 처리된 긴 명령 출력을
239
+ 프로젝트의 비공개 Receipt 저장소에 두고 digest에는 짧은 조회 handle만
240
+ 넣습니다. Handle은 bearer와 비슷하고 Claude/provider에 보일 수 있으며 발급
241
+ 후 정확히 7일 뒤 만료됩니다. Bash 실행 전에 wrapper는 소유자 전용 익명 캡처
242
+ descriptor와 검증된 Receipt broker 하나를 준비합니다. Broker는 코드 로드와
243
+ repository/store/expiry/journal 경계 고정을 끝낸 뒤에만 준비 완료를 알립니다.
244
+ 따라서 8,192바이트 공개 임계값보다 작은 출력도 로컬 상태 축을 초기화할 수
245
+ 있지만, 이 경우 `ABORT`하고 handle은 내보내지 않습니다. Strong sanitizer,
246
+ 정확한 패키지 pin, 절대 Node runtime, broker 준비 또는 최종 등록을 사용할 수
247
+ 없으면 감싼 명령의 exit status를 바꾸지 않고 legacy trim으로 돌아갑니다.
248
+ 기존 `--artifact-receipt` 캡처와는 동시에 사용할 수 없습니다.
249
+
250
+ Digest는 handle을 실행 가능한 프로젝트 로컬 조회 명령으로 표시합니다.
251
+
252
+ ```bash
253
+ ./node_modules/.bin/context-guard reference <cgr1p-handle>
254
+ ```
255
+
256
+ Handle을 발급한 동일한 물리 프로젝트 root에서 실행하세요. 명령은 비공개
257
+ sibling state 위치를 내부에서 계산하고, 정확한 sanitized UTF-8 출력 중 최대
258
+ 20,000바이트 한 페이지만 반환합니다. 남은 바이트가 있으면 diagnostic에 다음
259
+ 연속 조회용 `--offset`을 표시하므로 전체 보관 출력을 한 번에 transcript로 쏟지
260
+ 않습니다. 잘못되었거나 만료된 handle, 다른 root, stale source, 변경된 패키지,
261
+ 잘못된 응답은 payload를 전혀 반환하지 않습니다.
262
+
263
+ 패키지를 제거하기 전에 reference 경로를 먼저 끄세요.
264
+
265
+ ```bash
266
+ ./node_modules/.bin/context-guard setup --root . --agent claude --scope project --no-bash-reference-v1 --yes --no-diet-scan
267
+ npm uninstall @ictechgy/context-guard
268
+ ```
269
+
270
+ Receipt 상태는 저장소 밖의 비공개 sibling 디렉터리
271
+ `.context-guard-receipt-state-<root-selector-sha256>`에 둡니다. Selector는
272
+ 정규화한 root 경로와 device/inode identity를 묶으므로 나란한 저장소끼리
273
+ authority를 공유하지 않습니다. 비활성화와 패키지 제거는 나중의 정확한 재설치나
274
+ 별도 사용자 승인 artifact 정리를 위해 이 디렉터리를 보존합니다. 다만 `npm
275
+ uninstall`은 검증된 package-local code와 `node_modules/.bin/context-guard`를
276
+ 제거하므로, 정확한 프로젝트 로컬 pair를 다시 설치하기 전에는 reference 조회를
277
+ 할 수 없습니다. 이 메커니즘은 큰 Bash 출력의 transcript 입력을 줄일 수 있지만
278
+ 고정된 provider token 또는 비용 절감을 보장하지 않습니다.
279
+
197
280
  ## Homebrew 배포 경로
198
281
 
199
282
  Homebrew는 공유 `ictechgy/tap` tap을 통해 macOS 배포 경로로 사용할 수 있습니다.
@@ -234,6 +317,19 @@ context-guard setup --agent claude --scope user --verify --json
234
317
 
235
318
  선택형 Read 가드는 큰 파일에 대해 검색 → 심볼 구간 → 작은 줄 범위 순서의 단계적 축소 전략을 제안합니다. 가능하면 제한된 최상위 개요도 함께 보여줍니다. 같은 대용량 파일을 반복해서 전체 읽으려 하면 중복 읽기 경고를 표시해 같은 컨텍스트 낭비 경로를 반복하지 않게 합니다.
236
319
 
320
+ 적용 범위는 의도적으로 Claude Code `PreToolUse`의 `Read` matcher 훅으로 한정됩니다.
321
+
322
+ 이 Read 가드를 선택하면 setup은 기존 deny 값 중 정확히 `Read(./.env)`와 `Read(./.env.*)`만 제거합니다. 비슷한 permission 항목과 그 상대적 순서는 유지합니다.
323
+
324
+ | Claude 도구 | 보호 범위 |
325
+ | --- | --- |
326
+ | `Read` | 제한된 대용량 파일 범위를 검사하고, basename이 `.env`로 시작하면 차단합니다. 단, 정확히 `.env.example`, `.env.sample`, `.env.template`인 템플릿 이름은 허용합니다. 중첩 경로도 포함하며 symlink 여부가 모호하면 닫힌 상태로 실패합니다. |
327
+ | `Glob` | 일치하는 이름을 나열할 수 있습니다. 이 `Read` 훅을 통해 파일 내용을 읽지는 않습니다. |
328
+ | `Grep` | 이 훅의 범위 밖이며 일치하는 파일 내용을 읽을 수 있습니다. |
329
+ | `Bash` | 이 훅의 범위 밖이며 파일 내용을 읽을 수 있습니다. |
330
+
331
+ 이는 Claude `Read` 보호이지 범용 `.env` 보호나 Bash 보호가 아닙니다. 훅은 symlink를 따라가지 않고 직접 연 파일 descriptor의 상태를 다시 검증하지만, 실제 Claude `Read`는 훅이 반환된 뒤 파일을 다시 엽니다. 그 사이 파일이 교체될 수 있는 post-hook 구간은 문서화된 TOCTOU 한계입니다.
332
+
237
333
  ### 큰 로그를 로컬에 저장하고 필요한 부분만 조회
238
334
 
239
335
  ```bash
@@ -255,6 +351,14 @@ long-command 2>&1 | ./plugins/context-guard/bin/context-guard-artifact store --c
255
351
  --manifest-out suggested-pack.json \
256
352
  --pack-out context-pack.md \
257
353
  --budget-bytes 12000 --json --explain --adaptive-k --symbol-memory
354
+ # 안전한 direct import neighbor를 최대 4개까지 pack에 명시적으로 추가:
355
+ ./plugins/context-guard/bin/context-guard-pack auto \
356
+ --root . --files src/app.py --query "entrypoint 검토" --top 1 \
357
+ --budget-bytes 12000 --json --no-artifact --apply-symbol-memory
358
+ # 로컬 품질 gate 통과 뒤 heuristic source를 명시적으로 축소:
359
+ ./plugins/context-guard/bin/context-guard-pack auto \
360
+ --root . --query "실패 테스트 검토" --top 8 \
361
+ --budget-bytes 12000 --json --no-artifact --apply-adaptive-k
258
362
  # 또는 명시적인 두 단계로 실행:
259
363
  ./plugins/context-guard/bin/context-guard-pack suggest \
260
364
  --root . --query "failing tests review" --diff HEAD \
@@ -276,7 +380,9 @@ long-command 2>&1 | ./plugins/context-guard/bin/context-guard-artifact store --c
276
380
  - JSON explain에는 bounded `repo_map`이 포함될 수 있습니다. 예시는 sampled byte/token-proxy tree, category-only secret risk count, signature-first hint, explain-only graph rank, 기존 `slice`/symbol 재조회 힌트입니다.
277
381
  - repo-map은 manifest, pack 본문, receipt, byte budget을 바꾸지 않고 네트워크·모델 호출·임베딩을 쓰지 않습니다. 토큰 값은 provider-token이나 savings claim이 아닌 추정 `chars_div_4` proxy입니다.
278
382
  - `suggest` 또는 `auto`에 `--adaptive-k`를 추가하면 로컬 score distribution, byte-budget fit, clamped score-mass 기반 recall/precision proxy에서 나온 advisory-only top-k shrink/expand metadata를 포함합니다. `--adaptive-k-policy balanced|recall|precision`과 선택적 `--adaptive-k-min-recall-proxy` / `--adaptive-k-min-precision-proxy` gate로 로컬 추천 정책을 고를 수 있고, gate 실패는 metadata-only(`pass|failed`)입니다. adaptive block은 capped selected/omitted evidence와 구조화된 source-verification hint를 포함하지만 추천값을 자동 적용하지 않으며 manifest, pack 본문, receipt, byte budget을 바꾸지 않습니다.
383
+ - `auto --apply-adaptive-k`는 명시적·기본 비활성 pruning 경로입니다. 회귀 gate가 통과할 때만 로컬 추천값을 적용하고, 호출자가 지정한 file/output/test-output 및 diff source는 항상 유지한 채 같은 byte budget으로 다시 build하며 `adaptive_k_application`을 기록합니다. `--adaptive-k`를 내포하지만 provider token/cost 절감 주장을 허용하지 않습니다.
279
384
  - `auto`에 `--symbol-memory`를 추가하면 repo-map 기반 symbol/graph advisory metadata와 정확한 `slice` / `read-symbol` 검증 힌트를 포함합니다. 이는 source verification 안내일 뿐이며 manifest, pack 본문, receipt, byte budget을 바꾸지 않습니다.
385
+ - `--apply-symbol-memory`는 명시적·기본 비활성 Graphify식 적용 경로입니다. 일반 추천 뒤 안전한 direct import neighbor slice를 최대 4개 manifest에 추가하고 같은 byte budget으로 pack을 다시 만듭니다. explicit/query seed는 더 높은 우선순위를 유지하고 secret-risk neighbor는 제외하며 exact source/fallback receipt는 보존됩니다. 결과에는 닫힌 `graph_application` 블록이 기록되며 provider token/cost 절감 주장은 하지 않습니다.
280
386
  - `--manifest-out`은 `build`가 읽을 수 있는 manifest를 저장하고, `--pack-out`은 렌더링된 팩 본문을 저장합니다.
281
387
  - `context-guard-pack suggest`는 더 낮은 수준의 로컬 전용 준비 단계입니다. `--query`, `--diff`, 반복 `--files`, 그리고 `--root` 아래의 선택적 `--output` / `--test-output` 텍스트 파일을 가림 처리한 신호에서 후보 파일과 줄 범위를 순위화한 뒤 `build --manifest`가 바로 읽을 수 있는 manifest를 씁니다.
282
388
  - `context-guard-pack build`는 우선순위가 있는 로컬 파일 근거를 렌더링된 UTF-8 바이트 기준 `--budget-bytes` 안의 Markdown 팩으로 조립합니다. JSON 출력은 포함·부분 포함·중복·unsafe·missing·예산 초과로 누락된 source를 기록합니다.
@@ -332,7 +438,7 @@ cat sanitized-prose.txt | ./plugins/context-guard/bin/context-guard-compress --j
332
438
  ./plugins/context-guard/bin/context-guard-trim-output --max-lines 120 -- npm test
333
439
  ```
334
440
 
335
- head/tail 로그 대신 의미 요약이 필요하면 `--digest markdown` 또는 `--digest json`을 사용하세요. 요약 모드는 원래 종료 코드를 보존하면서 상태, 종료 코드, 잘린 줄 수, 실행기 실패 정보, 가림 처리된 실패 signature, 중복 라인 그룹, 대표 라인, 가림 처리 횟수, 다음 조회 제안을 남깁니다. 요약 모드에서 가림 처리된 전체 출력을 로컬 `context-guard-artifact` 보관본에 저장하려면 `--artifact-receipt`를 함께 사용하세요. 출력된 `contextguard-artifact:<id>` 핸들을 agent context에 남기고, 생략된 세부 내용에 의존하기 전에 `context-guard-artifact receipt/get/search ...` 명령으로 필요한 부분을 정확히 다시 가져오세요. 래핑된 명령은 기본 600초 뒤 종료되며, `--timeout-seconds`로 조정할 수 있습니다.
441
+ head/tail 로그 대신 의미 요약이 필요하면 `--digest markdown` 또는 `--digest json`을 사용하세요. 명령이 성공하고 출력이 이미 요약보다 작으면 요약 대신 원래 출력을 한 줄 표식과 함께 그대로 통과시키므로, 출력이 적은 명령에 요약 모드를 켜도 컨텍스트가 늘어나지 않습니다. 실패한 명령은 종료 코드와 실패 signature가 요약에 담기므로 항상 요약을 유지합니다. 모든 경우에 구조화된 요약을 유지하려면 `--digest-always`를 전달하세요. 요약 모드는 원래 종료 코드를 보존하면서 상태, 종료 코드, 잘린 줄 수, 실행기 실패 정보, 가림 처리된 실패 signature, 중복 라인 그룹, 대표 라인, 가림 처리 횟수, 다음 조회 제안을 남깁니다. 요약 모드에서 가림 처리된 전체 출력을 로컬 `context-guard-artifact` 보관본에 저장하려면 `--artifact-receipt`를 함께 사용하세요. 출력된 `contextguard-artifact:<id>` 핸들을 agent context에 남기고, 생략된 세부 내용에 의존하기 전에 `context-guard-artifact receipt/get/search ...` 명령으로 필요한 부분을 정확히 다시 가져오세요. 래핑된 명령은 기본 600초 뒤 종료되며, `--timeout-seconds`로 조정할 수 있습니다.
336
442
 
337
443
  ### 검색·diff 출력 민감정보 가림
338
444
 
@@ -365,7 +471,7 @@ JSON 출력에는 여러 증거 surface가 포함될 수 있습니다.
365
471
  [Sonnet] repo | main | ctx 86% ⚠ | cost $0.123 | cache 80% | reuse 8.0x
366
472
  ```
367
473
 
368
- `cache N%`는 최근 일정 범위의 대화 기록에서 관찰된 입력 토큰 중 cache read가 차지하는 비율이며, cache read가 1회 이상 있을 때만 표시됩니다. `reuse X.Yx`는 `cache_read / cache_creation` 값이며, cache read가 양수이고 cache creation이 0이 아닐 때만 표시됩니다. `⚠` 표시는 컨텍스트 사용률이 경고 기준에 도달했을 때 나타나며 기본값은 80%입니다. 프로젝트나 셸에서 `CONTEXT_GUARD_STATUSLINE_CTX_WARN=90`처럼 조정할 있습니다.
474
+ `cache N%`는 최근 일정 범위의 대화 기록에서 관찰된 입력 토큰 중 cache read가 차지하는 비율이며, cache read가 1회 이상 있을 때만 표시됩니다. `reuse X.Yx`는 `cache_read / cache_creation` 값이며, cache read가 양수이고 cache creation이 0이 아닐 때만 표시됩니다. `⚠` 표시는 컨텍스트 사용률이 경고 기준에 도달했을 때 나타나며 기본값은 80%입니다. 자동 훅은 격리된 환경에서 실행되므로 `CONTEXT_GUARD_STATUSLINE_CTX_WARN=90`을 설정한 setup을 다시 실행해 이 안전한 동작 설정을 설치 명령에 고정하세요. Python·shell loader 변수는 전달하지 않습니다.
369
475
 
370
476
  ### 반복 가능한 벤치마크 실행
371
477
 
@@ -375,6 +481,11 @@ JSON 출력에는 여러 증거 surface가 포함될 수 있습니다.
375
481
  --ledger-jsonl bench/cost-shift.jsonl --report-json bench/report.json
376
482
  ```
377
483
 
484
+ 각 task fixture의 선택 필드 `output_format`은 기본값이 `json`이며 `json|stream-json`만
485
+ 허용합니다. `stream-json` 모드는 runner가 관리하는 `--verbose`를 추가하고 bounded NDJSON의
486
+ 마지막 event가 유효한 terminal result일 때만 성공으로 처리합니다. 이 경로의 client cost도
487
+ provider billing을 authoritative하게 증명하지 않는 진단값입니다.
488
+
378
489
  보고서를 읽을 때는 먼저 주장 범위를 확인하세요.
379
490
 
380
491
  - 성공한 기준/변형 실행은 실제 토큰과 `cost_usd + external_cost_usd` 기준으로 비교하고, 바이트 감소는 간접 증거로만 기록합니다.
@@ -500,6 +611,21 @@ context-guard-setup --plan
500
611
 
501
612
  `context-guard mcp`(또는 `context-guard-mcp`)는 의존성 없는 로컬 stdio MCP 서버입니다. 프로세스 하나는 root와 namespace 하나에 고정되며 compression, sanitization된 artifact 조회, 로컬 통계만 제공합니다. HTTP, SSE, 네트워크, provider, model, proxy, 자동 client 설정 기능은 없습니다. 저장되는 fallback은 원문이 아닌 정확한 sanitization 완료 사본이고 다른 namespace의 artifact는 조회할 수 없습니다. 이 로컬 어댑터는 hosted token/cost 절감을 주장하지 않습니다.
502
613
 
614
+ 반복 파일·로그 컨텍스트를 명시적으로 다루려면 함께 설치되는 Receipt
615
+ companion을 `context-guard-receipt-mcp --root /absolute/repository`로 실행할
616
+ 수 있습니다. `receipt_context` 도구는 사용자가 `eligible`이라고 명시한
617
+ 상대 경로만 읽고, byte-benefit router가 유리하다고 판단하면 compact exact
618
+ reference를 반환하며, 반복 조회에는 같은 live reference를 재사용하고 한 번에
619
+ 최대 65,536바이트의 exact slice만 가져옵니다. 이 기능은 opt-in이며
620
+ process-local입니다. 선택적 task scope는 task 간 재사용을 막고, 명시적 release는
621
+ context GC를 수행하며, content-free history에는 process-keyed HMAC과 결정만
622
+ 남습니다. `receipt_diagnose`는 파일 byte를 반환하지 않고 비적용 shadow
623
+ firewall/router와 prefix 재사용 기반 scout/surgeon 안내를 제공합니다. 명시적
624
+ private `--state-dir`로 같은 binary를 시작하면 action을 실행하지 않는
625
+ authenticated `receipt_twin` 근거 기록만 추가됩니다. 스스로 등록되거나 전체
626
+ prompt를 가로채지 않고, capability가 재시작을 넘어 유지되지 않으며, provider를
627
+ 호출하거나 hosted 절감 효과를 주장하지 않습니다.
628
+
503
629
  ## 릴리스 확인
504
630
 
505
631
  릴리스에 민감한 변경을 배포하거나 머지하기 전에는 동기화 확인과 두 게이트를 모두 실행하세요.
package/README.md CHANGED
@@ -80,7 +80,7 @@ ContextGuard complements provider and semantic caches, and works alongside promp
80
80
  | 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 cache-write instead of cache-read. |
81
81
  | Semantic response cache | Reusing answers to identical or similar requests. | Complementary; ContextGuard does not serve cached AI answers. |
82
82
  | 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. |
83
- | Experimental planners and local runtimes | Default-off and explicit-command-only; covers plan-only `image-context-pack` and `semantic-checkpoint` gates plus local-proxy plans/gate records and narrow local runtimes for caller-supplied context-diff, visual evidence-pack, learned-compression, and self-hosted metrics evidence. | `image-context-pack` and `semantic-checkpoint` are dry-run planning gates only: they do not emit replacements, call models/providers, proxy traffic, write files, or make hosted token/cost savings claims. `semantic-checkpoint` additionally requires exact context fallback/re-expand metadata, provenance review acknowledgement, provider-boundary acknowledgement, protected-zone denial, and missed-context notes before the JSON payload reports readiness. 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; `--response-sandbox` can replace a safe UTF-8 upstream body with a compact local artifact rehydration envelope. Compressor/model execution, OCR/crop services, external forwarding, credential persistence, runtime checkpoint replacement, and hosted-savings claims stay out of scope until a separate evidence gate and future PR allow them. |
83
+ | Experimental planners and local runtimes | Default-off and explicit-command-only; covers plan-only `image-context-pack` and `semantic-checkpoint` gates plus local-proxy plans/gate records and narrow local runtimes for caller-supplied context-diff, visual evidence-pack, learned-compression, and self-hosted metrics evidence. | `image-context-pack` is a pxpipe-inspired dry-run planning gate only: it does not render images, run OCR, emit replacements, store binary image artifacts, call providers, or proxy traffic, and it requires exact text fallback plus provider-measured matched-task evidence before claims. `semantic-checkpoint` likewise emits planning metadata only, writes no files or replacement context, and requires exact fallback/re-expand metadata, provenance review acknowledgement, provider-boundary acknowledgement, protected-zone denial, and missed-context notes before reporting readiness. 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; `--response-sandbox` can replace a safe UTF-8 upstream body with a compact local artifact rehydration envelope. Compressor/model execution, OCR/crop services, external forwarding, credential persistence, runtime checkpoint replacement, and hosted-savings claims stay out of scope until a separate evidence gate and future PR allow them. |
84
84
  | ContextGuard | Avoiding unnecessary files, logs, repeated failures, and noisy output before they enter agent context. | Local guardrails, reversible artifacts, and measurement. |
85
85
 
86
86
  Related patterns that informed the design:
@@ -97,6 +97,44 @@ Brief mode is a set of agent-neutral, advisory rule snippets that ask a coding a
97
97
 
98
98
  Three deterministic levels ship under [`plugins/context-guard/brief/`](plugins/context-guard/brief/): `lite`, `standard`, and `ultra`. Each level is a single marker-delimited block for an agent's rule/instruction file (for example `AGENTS.md`, `CLAUDE.md`, a Cursor rules file, or Copilot instructions). Manage it through setup with `context-guard setup --agent codex --scope project --brief-mode standard --plan`, rerun with `--yes` to apply, and use `--brief-mode off` to remove the managed block. See [`plugins/context-guard/brief/README.md`](plugins/context-guard/brief/README.md).
99
99
 
100
+ ### Standing cost and break-even
101
+
102
+ Advisory rule blocks are not free. They live in an agent's rule file, so they are
103
+ re-sent with every request for as long as they are installed:
104
+
105
+ | Managed block | Installed size |
106
+ | --- | --- |
107
+ | `brief-mode.lite` | 1,487 bytes |
108
+ | `brief-mode.standard` | 1,568 bytes |
109
+ | `brief-mode.ultra` | 1,523 bytes |
110
+ | `narration-mode.quiet` | 866 bytes |
111
+
112
+ That is a fixed per-request cost paid up front, while the benefit is a
113
+ probabilistic reduction in reply length that ContextGuard cannot enforce. On a
114
+ session with few turns, or with an agent that already answers tersely, the block
115
+ can cost more than it saves. The hook-based guardrails behave differently: they
116
+ charge only when they act, and the measured worst cases stay small — a
117
+ sub-threshold `Read` adds 3 bytes, and repeated large-read attempts shrink after
118
+ the first warning instead of accumulating.
119
+
120
+ Before installing a rule block for its token effect, measure it. Use
121
+ `context-guard-bench` on matched tasks with and without the block, and treat the
122
+ block's installed size as the break-even threshold your reply-length reduction has
123
+ to clear. Byte counts here are observed; token effects are not, and no fixed
124
+ saving is claimed.
125
+
126
+ ## Quiet narration for Claude (advisory)
127
+
128
+ Quiet narration is a separate, default-off Claude-only rule for reducing discretionary preambles, per-tool narration, filler, and repeated interim summaries. It still requires approvals and decisions, blockers, failures, destructive or security warnings, higher-priority progress updates, the final result, changed files, and verification. It is best-effort guidance, independent of final-answer brevity or reasoning depth, and does **not** guarantee token or cost savings.
129
+
130
+ ```bash
131
+ context-guard setup --rules-only --agent claude --scope project --narration-mode quiet --plan
132
+ context-guard setup --rules-only --agent claude --scope project --narration-mode quiet --yes
133
+ context-guard setup --rules-only --agent claude --scope project --narration-mode default --yes
134
+ ```
135
+
136
+ This isolated operation manages only ContextGuard's narration span in the project's `CLAUDE.md`. It does not read or change Claude settings, hooks, permissions, statusline, model defaults, or other agents' rule files. It cannot be combined with brief mode, initialization, skill generation, or normal setup actions. Gate C verifies the static rule and setup side effects only; it does not prove model compliance or authorize a numeric savings claim.
137
+
100
138
  ## What to measure
101
139
 
102
140
  If you need a savings claim, measure it on your own tasks:
@@ -196,6 +234,66 @@ npm exec @ictechgy/context-guard -- --version
196
234
 
197
235
  Use `--scope project` for repository files such as `AGENTS.md` and `.agents/skills/...`. Use `--scope user` only when you intentionally want a user-level path; applying user scope requires `--yes` plus an explicit `--agent`, and supported writes record rollback metadata.
198
236
 
237
+ ### Opt-in Bash references for Claude Code
238
+
239
+ The `bash_reference_v1` route is available only from an exact, project-local npm
240
+ installation. The root package pins `@ictechgy/context-guard-receipt@0.2.1`; a
241
+ global, `npx`, source-checkout, Homebrew, or Claude marketplace-plugin layout
242
+ keeps the existing Bash trim behavior and setup reports the reference route as
243
+ unavailable.
244
+
245
+ ```bash
246
+ npm install --save-exact @ictechgy/context-guard@0.5.1
247
+ ./node_modules/.bin/context-guard setup --root . --agent claude --scope project --bash-reference-v1 --plan
248
+ ./node_modules/.bin/context-guard setup --root . --agent claude --scope project --bash-reference-v1 --yes
249
+ ```
250
+
251
+ This default-off `PreToolUse:Bash` mode keeps strongly sanitized long command
252
+ output in the private project-local Receipt store and puts only a compact
253
+ retrieval handle in the digest. The handle is bearer-like and can be visible to
254
+ Claude/the provider; it expires exactly seven days after issuance. Before Bash
255
+ starts, the wrapper creates an anonymous owner-only capture descriptor and one
256
+ verified Receipt broker, which preloads code and retains the repository, store,
257
+ expiry, and journal boundaries. Even output below the 8,192-byte disclosure
258
+ threshold can therefore initialize those local axes; it sends `ABORT` and emits
259
+ no handle. If strong sanitization, the exact package pin, the absolute Node
260
+ runtime, broker preparation, or final registration is unavailable, execution
261
+ falls back to legacy trimming without changing the wrapped command's exit
262
+ status. The mode is mutually exclusive with legacy `--artifact-receipt`
263
+ capture.
264
+
265
+ The digest renders the handle as an executable, project-local retrieval command:
266
+
267
+ ```bash
268
+ ./node_modules/.bin/context-guard reference <cgr1p-handle>
269
+ ```
270
+
271
+ Run it from the same physical project root that issued the handle. It derives
272
+ the private sibling state location internally and returns one exact sanitized
273
+ UTF-8 page, capped at 20,000 bytes. When more bytes remain, its diagnostic gives
274
+ the next continuation `--offset`; each page stays bounded, so retrieval cannot dump
275
+ the full retained output into the transcript in one step. Invalid, expired,
276
+ wrong-root, stale-source, changed-package, and malformed references return no
277
+ payload.
278
+
279
+ Disable the route before uninstalling:
280
+
281
+ ```bash
282
+ ./node_modules/.bin/context-guard setup --root . --agent claude --scope project --no-bash-reference-v1 --yes --no-diet-scan
283
+ npm uninstall @ictechgy/context-guard
284
+ ```
285
+
286
+ Receipt state is kept outside the repository in a private sibling directory
287
+ named `.context-guard-receipt-state-<root-selector-sha256>`. The selector binds
288
+ the normalized root path and its device/inode identity so sibling repositories
289
+ do not share authority. Disablement and package removal preserve that directory
290
+ for a later exact reinstall or separately authorized artifact cleanup. `npm
291
+ uninstall` removes the verified package-local code and
292
+ `node_modules/.bin/context-guard`, so reference retrieval is unavailable until
293
+ the exact project-local pair is reinstalled. This mechanism can reduce
294
+ transcript input for large Bash output, but it does not guarantee a fixed
295
+ provider-token or cost reduction.
296
+
199
297
  ## Homebrew release path
200
298
 
201
299
  Homebrew is available through the shared `ictechgy/tap` tap:
@@ -247,6 +345,19 @@ The structural-waste doctor is opt-in and read-only. It reuses the diet scanner'
247
345
 
248
346
  The optional Read guard uses a progressive path for oversized files: search first, then symbol slices, then small line ranges. When possible, it also returns a bounded top-level outline. Repeated attempts to full-read the same oversized file get a deduplicated warning instead of repeating the same context-heavy path.
249
347
 
348
+ Its enforcement surface is deliberately limited to the installed Claude Code `PreToolUse` hook whose matcher is `Read`:
349
+
350
+ When that Read guard is selected, setup removes only the exact legacy deny values `Read(./.env)` and `Read(./.env.*)`; similar permission entries and their relative order are preserved.
351
+
352
+ | Claude tool | Covered behavior |
353
+ | --- | --- |
354
+ | `Read` | The hook checks bounded large-file ranges and denies a basename beginning with `.env`, except the exact template names `.env.example`, `.env.sample`, and `.env.template`. Nested paths are included; ambiguous symlink paths fail closed. |
355
+ | `Glob` | May list matching names. It does not read file contents through this `Read` hook. |
356
+ | `Grep` | Out of scope for this hook and may read matching file contents. |
357
+ | `Bash` | Out of scope for this hook and may read file contents. |
358
+
359
+ This is Claude `Read` protection, not universal `.env` or Bash protection. The hook proves the file state it opens without following symlinks and revalidates that same descriptor, but Claude performs the actual `Read` with a later open after the hook returns. A replacement in that post-hook window is a documented TOCTOU limitation.
360
+
250
361
  ### Store and query large logs locally
251
362
 
252
363
  ```bash
@@ -268,6 +379,14 @@ Artifact mode is for capture, sandbox search, and retrieval. It stores sanitized
268
379
  --manifest-out suggested-pack.json \
269
380
  --pack-out context-pack.md \
270
381
  --budget-bytes 12000 --json --explain --adaptive-k --symbol-memory
382
+ # Explicitly add up to four safe direct import neighbors to the pack:
383
+ ./plugins/context-guard/bin/context-guard-pack auto \
384
+ --root . --files src/app.py --query "review entrypoint" --top 1 \
385
+ --budget-bytes 12000 --json --no-artifact --apply-symbol-memory
386
+ # Explicitly prune heuristic sources after the local quality gates pass:
387
+ ./plugins/context-guard/bin/context-guard-pack auto \
388
+ --root . --query "review failing tests" --top 8 \
389
+ --budget-bytes 12000 --json --no-artifact --apply-adaptive-k
271
390
  # Or run the two explicit steps:
272
391
  ./plugins/context-guard/bin/context-guard-pack suggest \
273
392
  --root . --query "review failing tests" --diff HEAD \
@@ -289,7 +408,9 @@ A few boundaries are intentional:
289
408
  - `--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.
290
409
  - 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.
291
410
  - Add `--adaptive-k` to `suggest` or `auto` for advisory-only shrink/expand top-k metadata derived from local score distribution, byte-budget fit, and clamped score-mass recall/precision proxies. Use `--adaptive-k-policy balanced|recall|precision` plus optional `--adaptive-k-min-recall-proxy` / `--adaptive-k-min-precision-proxy` gates to choose a local recommendation policy; gate failures are metadata-only (`pass|failed`). The adaptive block includes capped selected/omitted evidence and structured source-verification hints, never applies the recommendation automatically, and does not change the manifest, pack body, receipt, or byte budget.
411
+ - Add `--apply-adaptive-k` to `auto` for an explicit, default-off pruning pass. It applies the local recommendation only when its regression gates pass, always retains caller-declared file/output/test-output and diff sources, rebuilds inside the same byte budget, and records `adaptive_k_application`. It implies `--adaptive-k` and does not authorize a provider-token or cost-savings claim.
292
412
  - 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.
413
+ - Add `--apply-symbol-memory` for an explicit, default-off Graphify-style step: after the ordinary suggestion pass, it adds at most four direct import-neighbor slices to the manifest and rebuilds within the same byte budget. Explicit/query seeds keep higher priority, secret-risk neighbors are excluded, the exact source/fallback receipt remains available, and the result records a closed `graph_application` block. This implies symbol-memory output but makes no provider-token or cost claim.
293
414
  - `--manifest-out` writes a build-compatible manifest; `--pack-out` saves the rendered pack.
294
415
  - `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.
295
416
  - `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.
@@ -354,7 +475,7 @@ Add `--mode readable` only for sanitized prose previews. It uses a deterministic
354
475
  ./plugins/context-guard/bin/context-guard-trim-output --max-lines 120 -- npm test
355
476
  ```
356
477
 
357
- Use `--digest markdown` or `--digest json` for a compact semantic digest instead of head/tail logs. Digest mode keeps status, exit code, truncation counts, runner failure facts, a sanitized failure signature, duplicate-line groups, representative lines, redaction counts, and suggested next queries while preserving the wrapped command exit code. Add `--artifact-receipt` with digest mode when you want the exact sanitized full output stored locally as a `context-guard-artifact` receipt; keep the emitted `contextguard-artifact:<id>` handle in agent context and re-expand with the emitted `context-guard-artifact receipt/get/search ...` commands before relying on omitted details. Wrapped commands time out after 600 seconds by default; tune this with `--timeout-seconds`.
478
+ Use `--digest markdown` or `--digest json` for a compact semantic digest instead of head/tail logs. When a command succeeds and its output is already smaller than the digest would be, the output is passed through with a one-line marker instead, so enabling digest mode on quiet commands cannot inflate context. A failing command always keeps the digest, because that is where the exit code and failure signature live; pass `--digest-always` to keep the structured digest in every case. Digest mode keeps status, exit code, truncation counts, runner failure facts, a sanitized failure signature, duplicate-line groups, representative lines, redaction counts, and suggested next queries while preserving the wrapped command exit code. Add `--artifact-receipt` with digest mode when you want the exact sanitized full output stored locally as a `context-guard-artifact` receipt; keep the emitted `contextguard-artifact:<id>` handle in agent context and re-expand with the emitted `context-guard-artifact receipt/get/search ...` commands before relying on omitted details. Wrapped commands time out after 600 seconds by default; tune this with `--timeout-seconds`.
358
479
 
359
480
  ### Sanitize search and diff output
360
481
 
@@ -409,7 +530,7 @@ These fields can flag likely volatile content near the prompt prefix, stable-pre
409
530
  [Sonnet] repo | main | ctx 86% ⚠ | cost $0.123 | cache 80% | reuse 8.0x
410
531
  ```
411
532
 
412
- `cache N%` is the cache-read share of observed input-side tokens in the bounded transcript tail and stays hidden until at least one cache read is observed. `reuse X.Yx` is `cache_read / cache_creation` and is shown only when cache read is positive and cache creation is non-zero. The `⚠` marker appears when context usage reaches the warning threshold, defaulting to 80%; set `CONTEXT_GUARD_STATUSLINE_CTX_WARN=90` to tune it for a project or shell.
533
+ `cache N%` is the cache-read share of observed input-side tokens in the bounded transcript tail and stays hidden until at least one cache read is observed. `reuse X.Yx` is `cache_read / cache_creation` and is shown only when cache read is positive and cache creation is non-zero. The `⚠` marker appears when context usage reaches the warning threshold, defaulting to 80%. Automatic hooks run with an isolated environment, so set `CONTEXT_GUARD_STATUSLINE_CTX_WARN=90` and rerun setup to pin that safe behavior setting into the installed command; Python and shell loader variables are never carried through.
413
534
 
414
535
  ### Run a repeatable benchmark
415
536
 
@@ -420,6 +541,11 @@ These fields can flag likely volatile content near the prompt prefix, stable-pre
420
541
  --dashboard-md bench/dashboard.md
421
542
  ```
422
543
 
544
+ Each task fixture may set `output_format` to `json` (the default) or opt in to
545
+ `stream-json`. Stream mode adds the runner-controlled `--verbose` flag and only
546
+ accepts a bounded NDJSON stream whose final event is a valid terminal result.
547
+ Its client-reported cost remains diagnostic and is not authoritative provider billing.
548
+
423
549
  For deterministic local replay before a live provider run, add `--evidence-jsonl docs/benchmark-fixtures/token-savings-12task.evidence.example.jsonl` and, for the 12-task fixture, `--baseline-variant baseline_full_context_fixture`. Replay mode skips provider and `success_command` execution, writes the same CSV/report/dashboard surfaces, and marks synthetic/manual evidence as non-public-claim-eligible.
424
550
 
425
551
  Read the report through its claim boundaries before writing any savings statement:
@@ -553,6 +679,21 @@ Do not rely on `PATH` lookup for generated hooks by default. The setup wizard re
553
679
 
554
680
  `context-guard mcp` (or `context-guard-mcp`) is a dependency-free local stdio MCP server. Each process is fixed to one root and one namespace; it exposes only compression, sanitized artifact retrieval, and local statistics. It has no HTTP, SSE, network, provider, model, proxy, or automatic client-configuration surface. Stored fallback content is an exact sanitized copy, not raw input, and artifacts from another namespace are not retrievable. This local adapter makes no hosted token or cost-savings claim.
555
681
 
682
+ For explicit repeated file or log context, the bundled Receipt companion also
683
+ provides `context-guard-receipt-mcp --root /absolute/repository`. Its
684
+ `receipt_context` tool accepts an explicitly eligible relative path, returns a
685
+ compact exact reference when the byte-benefit router says deferral is useful,
686
+ reuses that live reference for repeated reads, and retrieves exact slices of at
687
+ most 65,536 bytes. Optional task scopes prevent cross-task reuse, explicit
688
+ release performs context GC, and the content-free history records only
689
+ process-keyed HMACs and decisions. `receipt_diagnose` adds non-applying shadow
690
+ firewall/router plus prefix-reuse scout/surgeon advice without returning file
691
+ bytes. Starting the same binary with an explicit private `--state-dir` enables
692
+ only `receipt_twin`, which records authenticated revalidation evidence but
693
+ executes no action. The flow remains opt-in: it does not register itself,
694
+ intercept whole prompts, survive capability restart, call a provider, or make a
695
+ hosted savings claim.
696
+
556
697
  ## Release checks
557
698
 
558
699
  Before publishing or merging release-sensitive changes, run the copy check and both gates:
@@ -27,6 +27,106 @@ context-guard setup --agent claude --scope user --plan
27
27
 
28
28
  Project scope is the default. `context-guard doctor` and `context-guard setup --verify` are read-only health checks. User scope is opt-in and requires an explicit agent for writes. Supported user-scope writes record backups and rollback metadata under `.context-guard/rollback` in the user home directory. Setup resolves packaged/check-out helpers first; `PATH` helper fallback is default-off and requires `--allow-path-helper-fallback` for a trusted install after canonical executable and identity validation.
29
29
 
30
+ ## Exact npm pair for Bash references
31
+
32
+ `bash_reference_v1` is a narrower distribution than the ordinary CLI/plugin.
33
+ It accepts only an exact project-local npm topology: root
34
+ `@ictechgy/context-guard@0.5.1` declares
35
+ `@ictechgy/context-guard-receipt: 0.2.1`, and the installed Receipt inventory
36
+ must match the SHA-256 trust anchor embedded in the root policy. Hoisted and
37
+ nested npm dependency layouts are supported; global npm, `npx`, Homebrew,
38
+ source-checkout, arbitrary `PATH`, and marketplace-plugin layouts are refused.
39
+
40
+ ```bash
41
+ npm install --save-exact @ictechgy/context-guard@0.5.1
42
+ ./node_modules/.bin/context-guard setup --root . --agent claude --scope project --bash-reference-v1 --plan
43
+ ./node_modules/.bin/context-guard setup --root . --agent claude --scope project --bash-reference-v1 --yes
44
+ ```
45
+
46
+ Setup writes the opt-in flag only when the paired topology is present. Doctor
47
+ and source/plugin setup report it as unavailable otherwise and retain the
48
+ legacy Bash trim hook. Runtime discovery never launches Node by name from
49
+ `PATH`: it binds an absolute interpreter from fixed system locations, with a
50
+ GitHub Actions-only Node fallback restricted to fixed hosted-toolcache roots,
51
+ and rechecks the pinned Receipt files before starting one private broker. Before
52
+ Bash starts, every interpreter must be a regular, single-link executable owned
53
+ by root or the current user, executable, and not group- or world-writable. The
54
+ CI workflow validates the canonical hosted Python and Node locations, removes
55
+ group/world write permission from exactly those two ephemeral targets, and then
56
+ runs the same production preflight; `GITHUB_ACTIONS` never weakens this policy.
57
+ The broker has
58
+ already loaded its code and retained the repository, store, expiry, journal,
59
+ and anonymous owner-only capture descriptors. `COMMIT` therefore performs no
60
+ later package-path, interpreter, or Git lookup. Even a below-threshold command
61
+ can initialize the local state axes before the wrapper sends `ABORT`. A missing
62
+ strong sanitizer, changed package, invalid response, timeout, or unavailable
63
+ state yields legacy output, not a reference and not a changed child exit
64
+ status.
65
+
66
+ An issued digest contains the directly executable retrieval command below; it
67
+ must be run from the same physical project root:
68
+
69
+ ```bash
70
+ ./node_modules/.bin/context-guard reference <cgr1p-handle>
71
+ ```
72
+
73
+ The root command never accepts or reveals `--root` or `--state-dir`. It derives
74
+ the deterministic sibling state internally and returns at most one exact
75
+ 20,000-byte sanitized UTF-8 page. If more content remains, a compact diagnostic
76
+ provides the next continuation `--offset`. Expansion rechecks the exact package,
77
+ root/source binding, and active seven-day registry entry; any failure emits no
78
+ payload.
79
+
80
+ The handle is provider-visible bearer material with an exact seven-day expiry.
81
+ State is placed outside the repository in a private sibling named
82
+ `.context-guard-receipt-state-<root-selector-sha256>`; the selector binds the
83
+ normalized root path and device/inode identity. This keeps Receipt state
84
+ physically disjoint from the repository snapshot and separates sibling roots.
85
+ Disablement removes only the hook flag, and npm uninstall removes package code
86
+ but deliberately leaves state/artifacts intact for a later exact reinstall or
87
+ separately authorized cleanup. After uninstall, the verified package-local code
88
+ and `node_modules/.bin/context-guard` are absent, so retrieval is unavailable
89
+ until the exact project-local pair is reinstalled:
90
+
91
+ ```bash
92
+ ./node_modules/.bin/context-guard setup --root . --agent claude --scope project --no-bash-reference-v1 --yes --no-diet-scan
93
+ npm uninstall @ictechgy/context-guard
94
+ ```
95
+
96
+ Artifact deletion is not automated; it requires a separate, explicit
97
+ user-authorized retention decision. `--bash-reference-v1` and
98
+ `--artifact-receipt` are mutually exclusive.
99
+
100
+ ## npm candidate, publication, and promotion gates
101
+
102
+ `.github/workflows/npm-candidate.yml` checks out one exact commit, runs both
103
+ package gates, packs each package exactly once offline, exercises the paired
104
+ tarballs in a clean install, and uploads immutable per-package artifacts. The
105
+ shared candidate manifest binds the commit, exact dependency, Receipt inventory
106
+ digest, policy digest, SHA-256, sha512 SRI, sizes, toolchain, and protocol. The
107
+ workflow refuses a requested commit that differs from its own workflow-source
108
+ commit so the later source and signer attestation digests bind the same revision.
109
+
110
+ `.github/workflows/npm-publish.yml` downloads an exact artifact by run and
111
+ artifact ID, revalidates the manifest and tarball, verifies GitHub build
112
+ provenance for both the candidate manifest and tarball against the candidate
113
+ source commit plus the exact trusted signer workflow revision, and publishes
114
+ only that tarball to `next`. Publishing the root also
115
+ requires the npm registry's Receipt `dist.integrity` to equal the Receipt bytes
116
+ bound in the same candidate manifest. Publication remains a manual,
117
+ environment-protected operation and is not performed by CI automatically.
118
+
119
+ `.github/workflows/npm-promote.yml` is a separate manual gate. Before changing
120
+ `latest`, it proves both requested versions are the current reviewed `next`
121
+ pair, verifies the root's exact Receipt dependency, and records the previous
122
+ tags for rollback. One manually approved `npm-pair-promote` environment exposes
123
+ the two package-scoped credentials only to the pair-mutation step. That same
124
+ shell moves Receipt then root and, on failure or ordinary cancellation, attempts
125
+ both compensating tag restores before it exits; no second environment approval
126
+ is needed for compensation. A force-cancel, unavailable npm registry, or
127
+ unavailable promotion credential can still prevent restoration; in that case
128
+ rerun the preflight and restore the recorded previous tags explicitly.
129
+
30
130
  ## Runtime requirements
31
131
 
32
132
  The helpers are Python/shell scripts packaged through npm and Homebrew as plugin-local `plugins/context-guard/bin` entrypoints plus `plugins/context-guard/lib` helpers; checkout-only `context-guard-kit` sources are not duplicated in the npm tarball. Supported machines need: