@ictechgy/context-guard 0.4.0

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 (71) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +4 -0
  4. package/README.ko.md +353 -0
  5. package/README.md +353 -0
  6. package/context-guard-kit/README.md +76 -0
  7. package/context-guard-kit/benchmark_runner.py +1898 -0
  8. package/context-guard-kit/claude_transcript_cost_audit.py +1591 -0
  9. package/context-guard-kit/context_compress.py +543 -0
  10. package/context-guard-kit/context_escrow.py +919 -0
  11. package/context-guard-kit/context_guard_cli.py +149 -0
  12. package/context-guard-kit/context_guard_diet.py +1036 -0
  13. package/context-guard-kit/context_pack.py +929 -0
  14. package/context-guard-kit/failed_attempt_nudge.py +567 -0
  15. package/context-guard-kit/guard_large_read.py +690 -0
  16. package/context-guard-kit/hook_secret_patterns.py +43 -0
  17. package/context-guard-kit/read_symbol.py +483 -0
  18. package/context-guard-kit/rewrite_bash_for_token_budget.py +501 -0
  19. package/context-guard-kit/sanitize_output.py +725 -0
  20. package/context-guard-kit/settings.example.json +67 -0
  21. package/context-guard-kit/setup_wizard.py +1724 -0
  22. package/context-guard-kit/statusline.sh +362 -0
  23. package/context-guard-kit/statusline_merged.sh +157 -0
  24. package/context-guard-kit/tool_schema_pruner.py +837 -0
  25. package/context-guard-kit/trim_command_output.py +1098 -0
  26. package/docs/distribution.md +55 -0
  27. package/package.json +70 -0
  28. package/packaging/homebrew/context-guard.rb.template +34 -0
  29. package/plugins/context-guard/.claude-plugin/plugin.json +41 -0
  30. package/plugins/context-guard/LICENSE +201 -0
  31. package/plugins/context-guard/NOTICE +4 -0
  32. package/plugins/context-guard/README.ko.md +135 -0
  33. package/plugins/context-guard/README.md +135 -0
  34. package/plugins/context-guard/bin/claude-read-symbol +6 -0
  35. package/plugins/context-guard/bin/claude-sanitize-output +6 -0
  36. package/plugins/context-guard/bin/claude-token-artifact +6 -0
  37. package/plugins/context-guard/bin/claude-token-audit +6 -0
  38. package/plugins/context-guard/bin/claude-token-bench +6 -0
  39. package/plugins/context-guard/bin/claude-token-diet +6 -0
  40. package/plugins/context-guard/bin/claude-token-failed-nudge +6 -0
  41. package/plugins/context-guard/bin/claude-token-guard-read +6 -0
  42. package/plugins/context-guard/bin/claude-token-rewrite-bash +6 -0
  43. package/plugins/context-guard/bin/claude-token-setup +6 -0
  44. package/plugins/context-guard/bin/claude-token-statusline +6 -0
  45. package/plugins/context-guard/bin/claude-token-statusline-merged +6 -0
  46. package/plugins/context-guard/bin/claude-trim-output +6 -0
  47. package/plugins/context-guard/bin/context-guard +149 -0
  48. package/plugins/context-guard/bin/context-guard-artifact +919 -0
  49. package/plugins/context-guard/bin/context-guard-audit +1591 -0
  50. package/plugins/context-guard/bin/context-guard-bench +1898 -0
  51. package/plugins/context-guard/bin/context-guard-compress +543 -0
  52. package/plugins/context-guard/bin/context-guard-diet +1036 -0
  53. package/plugins/context-guard/bin/context-guard-failed-nudge +567 -0
  54. package/plugins/context-guard/bin/context-guard-guard-read +690 -0
  55. package/plugins/context-guard/bin/context-guard-pack +929 -0
  56. package/plugins/context-guard/bin/context-guard-read-symbol +483 -0
  57. package/plugins/context-guard/bin/context-guard-rewrite-bash +501 -0
  58. package/plugins/context-guard/bin/context-guard-sanitize-output +725 -0
  59. package/plugins/context-guard/bin/context-guard-setup +1724 -0
  60. package/plugins/context-guard/bin/context-guard-statusline +362 -0
  61. package/plugins/context-guard/bin/context-guard-statusline-merged +157 -0
  62. package/plugins/context-guard/bin/context-guard-tool-prune +837 -0
  63. package/plugins/context-guard/bin/context-guard-trim-output +1098 -0
  64. package/plugins/context-guard/brief/README.md +65 -0
  65. package/plugins/context-guard/brief/brief-mode.lite.md +29 -0
  66. package/plugins/context-guard/brief/brief-mode.standard.md +31 -0
  67. package/plugins/context-guard/brief/brief-mode.ultra.md +32 -0
  68. package/plugins/context-guard/lib/hook_secret_patterns.py +43 -0
  69. package/plugins/context-guard/skills/audit/SKILL.md +39 -0
  70. package/plugins/context-guard/skills/optimize/SKILL.md +48 -0
  71. package/plugins/context-guard/skills/setup/SKILL.md +40 -0
@@ -0,0 +1,65 @@
1
+ # ContextGuard brief mode (advisory)
2
+
3
+ Brief mode is a set of **agent-neutral, advisory** rule snippets that ask a coding/tool
4
+ agent to cut filler from its responses while preserving the technical evidence a reviewer
5
+ needs. It is guidance text, not an enforcement mechanism.
6
+
7
+ - **Advisory / best-effort.** Compatible agents may follow these rules fully, partially, or
8
+ ignore them. Brief mode does not intercept, rewrite, or block model output.
9
+ - **No guaranteed savings.** Brief mode does **not** promise any token or cost reduction.
10
+ Verbosity behavior varies by agent and model. Measure real before/after results for your
11
+ own tasks with `context-guard-bench` before making any savings claim.
12
+ - **Evidence first.** Every level keeps the same mandatory evidence floor (see below). Brief
13
+ mode trims wording, never correctness-critical content.
14
+ - **Local and reversible.** Snippets are plain text you install into an agent's own rule or
15
+ instruction file. They are delimited by stable markers so a setup/adapter step can add or
16
+ remove them without touching unrelated configuration.
17
+
18
+ ## Levels
19
+
20
+ Brief mode ships three deterministic levels. Each level file contains one marker-delimited
21
+ block that is safe to copy into an agent rules file as-is.
22
+
23
+ | Level | File | Verbosity dial |
24
+ | --- | --- | --- |
25
+ | `lite` | [`brief-mode.lite.md`](brief-mode.lite.md) | Drop pleasantries and restated context; keep explanations where they aid understanding. |
26
+ | `standard` | [`brief-mode.standard.md`](brief-mode.standard.md) | Answer first, bullets over paragraphs, one short rationale line where it matters. |
27
+ | `ultra` | [`brief-mode.ultra.md`](brief-mode.ultra.md) | Telegraphic: results/bullets/tables only, no preamble or self-narration. |
28
+
29
+ The levels differ only in how aggressively they cut wording. They never differ in what
30
+ evidence must be preserved.
31
+
32
+ ## Mandatory evidence floor (all levels)
33
+
34
+ A brief-mode response must still include, whenever relevant:
35
+
36
+ 1. **File paths** — exact paths, with line numbers where useful (e.g. `src/app.py:42`).
37
+ 2. **Commands** — the exact commands that were run.
38
+ 3. **Command output / failure evidence** — relevant output, error messages, stack traces,
39
+ and exit codes. Never hide a failure to look terse.
40
+ 4. **Code blocks** — when code is needed for correctness, keep it in a fenced block.
41
+ 5. **Verification status** — what was run to verify, and whether it passed or failed.
42
+ 6. **Changed files** — the list of files created, modified, or deleted.
43
+ 7. **Known gaps** — TODOs, untested paths, and assumptions made.
44
+ 8. **Caveats** — uncertainty and anything the reader must double-check.
45
+
46
+ ## Installing and removing
47
+
48
+ Brief mode is installed by copying the marker-delimited block from a level file into the
49
+ target agent's rule/instruction file (for example a repo `AGENTS.md`, `CLAUDE.md`,
50
+ `.cursorrules`, or `.github/copilot-instructions.md`). The cross-agent setup planner is the
51
+ intended automation for this; per the project safety rules it stays dry-run first, writes
52
+ only local files, backs up before changing anything, and applies only with explicit
53
+ approval.
54
+
55
+ Each block is wrapped in stable markers:
56
+
57
+ ```text
58
+ <!-- BEGIN context-guard:brief-mode level=<level> version=1 -->
59
+ ...rules...
60
+ <!-- END context-guard:brief-mode -->
61
+ ```
62
+
63
+ To remove brief mode, delete the block between (and including) those two marker lines. Only
64
+ one brief-mode block should be present at a time; installing a different level replaces the
65
+ existing block rather than stacking a second one.
@@ -0,0 +1,29 @@
1
+ # Brief mode — lite (advisory)
2
+
3
+ Lightest level. Trims pleasantries and restated context while keeping explanations where they
4
+ genuinely aid understanding. Advisory and best-effort: a compatible agent may follow it
5
+ partially or ignore it, and it does **not** guarantee any token or cost savings. Copy the block
6
+ below into your agent's rule/instruction file; remove it by deleting the marked block.
7
+
8
+ <!-- BEGIN context-guard:brief-mode level=lite version=1 -->
9
+ ## Response style: brief mode (lite) — advisory
10
+
11
+ Keep replies focused. This is best-effort guidance, not a hard rule.
12
+
13
+ - Skip greetings, apologies, self-congratulation, and restating the request back to me.
14
+ - Don't narrate what you are about to do; just do it and report the result.
15
+ - Explanations are welcome where they aid understanding — trim them, don't delete them.
16
+
17
+ Always preserve this evidence, even when trimming wording:
18
+
19
+ - Exact file paths, with line numbers where useful (e.g. `src/app.py:42`).
20
+ - The exact commands you ran.
21
+ - Relevant command output, error messages, stack traces, and exit codes — never hide a failure.
22
+ - Code in fenced blocks whenever code is needed for correctness.
23
+ - Verification status: what you ran and whether it passed or failed.
24
+ - The list of changed files.
25
+ - Known gaps, TODOs, and assumptions.
26
+ - Caveats and anything I should double-check.
27
+
28
+ This guidance does not promise reduced tokens or cost; measure real results before claiming savings.
29
+ <!-- END context-guard:brief-mode -->
@@ -0,0 +1,31 @@
1
+ # Brief mode — standard (advisory)
2
+
3
+ Balanced level. Answer first, bullets over paragraphs, one short rationale line where it
4
+ matters. Advisory and best-effort: a compatible agent may follow it partially or ignore it,
5
+ and it does **not** guarantee any token or cost savings. Copy the block below into your
6
+ agent's rule/instruction file; remove it by deleting the marked block.
7
+
8
+ <!-- BEGIN context-guard:brief-mode level=standard version=1 -->
9
+ ## Response style: brief mode (standard) — advisory
10
+
11
+ Be concise by default. This is best-effort guidance, not a hard rule.
12
+
13
+ - Lead with the answer or result; put detail after it only if it is needed.
14
+ - Prefer bullet points and short tables over paragraphs.
15
+ - Keep at most one short rationale line where a choice is non-obvious.
16
+ - Drop greetings, apologies, restated context, and "I will now..." narration.
17
+ - Don't pad with summaries of work you already showed.
18
+
19
+ Always preserve this evidence, even at this terseness:
20
+
21
+ - Exact file paths, with line numbers where useful (e.g. `src/app.py:42`).
22
+ - The exact commands you ran.
23
+ - Relevant command output, error messages, stack traces, and exit codes — never hide a failure to look terse.
24
+ - Code in fenced blocks whenever code is needed for correctness.
25
+ - Verification status: what you ran and whether it passed or failed.
26
+ - The list of changed files.
27
+ - Known gaps, TODOs, and assumptions.
28
+ - Caveats and anything I should double-check.
29
+
30
+ This guidance does not promise reduced tokens or cost; measure real results before claiming savings.
31
+ <!-- END context-guard:brief-mode -->
@@ -0,0 +1,32 @@
1
+ # Brief mode — ultra (advisory)
2
+
3
+ Most aggressive level. Telegraphic output: results, bullets, and tables only, with no preamble
4
+ or self-narration. Advisory and best-effort: a compatible agent may follow it partially or
5
+ ignore it, and it does **not** guarantee any token or cost savings. The evidence floor below is
6
+ never dropped, no matter how terse. Copy the block below into your agent's rule/instruction
7
+ file; remove it by deleting the marked block.
8
+
9
+ <!-- BEGIN context-guard:brief-mode level=ultra version=1 -->
10
+ ## Response style: brief mode (ultra) — advisory
11
+
12
+ Maximum terseness. Best-effort guidance, not a hard rule.
13
+
14
+ - Result first. No preamble, no greeting, no apology, no restated request.
15
+ - No self-narration ("I'll now...", "Let me...", "Here is..."). Just the content.
16
+ - Use bullets, tables, and short fragments. Avoid connective prose.
17
+ - No closing summary of what you just did.
18
+ - Terseness must never remove correctness-critical content or hide problems.
19
+
20
+ Never drop this evidence, however terse:
21
+
22
+ - Exact file paths + line numbers where useful (e.g. `src/app.py:42`).
23
+ - Exact commands run.
24
+ - Relevant output, errors, stack traces, exit codes — surface failures, don't bury them.
25
+ - Fenced code blocks when code is needed for correctness.
26
+ - Verification status: command run + pass/fail.
27
+ - Changed files list.
28
+ - Known gaps, TODOs, assumptions.
29
+ - Caveats / what to double-check.
30
+
31
+ Does not promise reduced tokens or cost; measure real results before claiming savings.
32
+ <!-- END context-guard:brief-mode -->
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env python3
2
+ """Shared high-confidence secret patterns for hook-visible text.
3
+
4
+ These patterns are intentionally narrower than the full output sanitizer: hooks
5
+ use them on user-controlled path labels and short diagnostics where false
6
+ positives should redact the whole label rather than rewrite large command
7
+ output. Keep alternatives bounded or structurally linear; hooks run before any
8
+ downstream sanitizer can protect their own stderr/JSON output.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import re
13
+
14
+
15
+ CONTROL_CHAR_RE = re.compile(r"[\x00-\x1f\x7f-\x9f]")
16
+ SENSITIVE_HOOK_TEXT_RE = re.compile(
17
+ r"(?i)("
18
+ r"gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|"
19
+ r"glpat-[A-Za-z0-9_-]{12,}|(?:AKIA|ASIA)[0-9A-Z]{16}|"
20
+ r"(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{16,}|"
21
+ r"sk-(?:ant|proj)-[A-Za-z0-9_-]{8,}|xox[abprs]-[A-Za-z0-9-]{8,}|"
22
+ r"npm_[A-Za-z0-9]{20,}|AIza[0-9A-Za-z_-]{20,}|"
23
+ r"SG\.[A-Za-z0-9_-]{16,256}\.[A-Za-z0-9_-]{16,512}|"
24
+ r"eyJ[A-Za-z0-9_-]*(?:\.[A-Za-z0-9_-]*){2}|"
25
+ r"\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{12,}|"
26
+ r"[a-z][a-z0-9+.-]{0,31}:/+(?:[^/\s:@]{0,256}:[^/\s@]{0,2048}|[^/\s@]{1,2048})@|"
27
+ r"(?<![A-Za-z0-9])(?:api[_-]?key|token|secret|password|client[_-]?secret)\s*(?:=|:|%3d)[^/\\\s]{4,})"
28
+ )
29
+
30
+
31
+ def hook_text_has_sensitive_evidence(value: str) -> bool:
32
+ """Return True when hook-visible text contains a high-confidence secret."""
33
+ return bool(SENSITIVE_HOOK_TEXT_RE.search(value))
34
+
35
+
36
+ def hook_label_has_sensitive_evidence(value: str) -> bool:
37
+ """Return True when a compact hook-visible label must be fully redacted."""
38
+ return bool(CONTROL_CHAR_RE.search(value) or hook_text_has_sensitive_evidence(value))
39
+
40
+
41
+ def redact_sensitive_hook_text(value: str, replacement: str = "[redacted]") -> str:
42
+ """Redact high-confidence secrets from hook-visible text."""
43
+ return SENSITIVE_HOOK_TEXT_RE.sub(replacement, value)
@@ -0,0 +1,39 @@
1
+ ---
2
+ description: Audit local Claude Code transcript usage and summarize likely token hotspots. Use when the user asks where Claude Code tokens are going or wants evidence before optimizing.
3
+ argument-hint: [optional transcript path]
4
+ disable-model-invocation: true
5
+ ---
6
+
7
+ # ContextGuard Audit
8
+
9
+ Run a best-effort transcript audit, then interpret the result conservatively.
10
+
11
+ Default command:
12
+
13
+ ```bash
14
+ context-guard-audit ~/.claude/projects --top 20 --recommend
15
+ ```
16
+
17
+ If the user supplies a path, audit that path instead. If no path is supplied, keep the default Claude projects path:
18
+
19
+ ```bash
20
+ if [ -n "$ARGUMENTS" ]; then
21
+ context-guard-audit "$ARGUMENTS" --top 20 --recommend
22
+ else
23
+ context-guard-audit ~/.claude/projects --top 20 --recommend
24
+ fi
25
+ ```
26
+
27
+ Report:
28
+
29
+ - observed token buckets: input, output, cache_read, cache_creation;
30
+ - model distribution;
31
+ - query_source distribution: main, subagent, auxiliary;
32
+ - top transcript files and commands observed;
33
+ - generated recommendations with priority, reason, action, and evidence;
34
+ - `cache_friendliness` status, bounded prefix/tail churn signals, and any cache-layout findings;
35
+ - top likely causes and one safe next experiment.
36
+
37
+ Privacy: default output uses basename+hash transcript labels and command category+hash labels. Do not ask for `--show-paths` or `--show-commands` unless the user explicitly wants local identifiers in the report. Cache-friendliness diagnostics use bounded redacted segment hashes and do not print raw prompt text. Recommendations are heuristics; treat them as hypotheses, especially with small `files` or `records` counts.
38
+
39
+ Caveat: Claude Code transcript schemas can change. Treat this as an operational signal, not billing authority. `cache_read`/`cache_creation` and `cache_friendliness` are provider-cache diagnostics, not proof of ContextGuard-caused token reduction. For billing authority, use Claude Console, cloud-provider billing, or configured OpenTelemetry metrics.
@@ -0,0 +1,48 @@
1
+ ---
2
+ description: Diagnose and reduce Claude Code token usage for a project or session using context hygiene, model and effort routing, MCP minimization, output trimming/sanitizing, subagent discipline, and measurement. Use when the user asks to lower Claude Code token usage, cost, context bloat, or usage-limit burn.
3
+ argument-hint: [project/session symptoms]
4
+ allowed-tools: Bash(context-guard-setup *), Bash(context-guard-audit *), Bash(context-guard-diet scan *), Bash(context-guard-read-symbol *), Bash(context-guard-artifact store *), Bash(context-guard-artifact get *), Bash(context-guard-artifact list *), Bash(context-guard-statusline)
5
+ ---
6
+
7
+ # ContextGuard
8
+
9
+ Goal: reduce Claude Code token usage without lowering task success quality.
10
+
11
+ Use this order:
12
+
13
+ 1. Measure before changing behavior.
14
+ - Ask the user to run `/usage` and `/context` if inside Claude Code.
15
+ - For first-time setup, run `context-guard-setup --plan` and offer `context-guard-setup --yes` for recommended project-local settings.
16
+ - If transcript files are available, run `context-guard-audit ~/.claude/projects --top 20 --recommend`.
17
+ - For project configuration/context bloat, run `context-guard-diet scan .`.
18
+ 2. Identify the largest bucket:
19
+ - stale conversation history -> recommend `/clear` between unrelated tasks and focused `/compact` for long tasks.
20
+ - startup context -> prune `CLAUDE.md`, move long workflows to skills, disable unused MCP servers.
21
+ - large file reads -> use `context-guard-read-symbol` and the example Read guard before whole-file context.
22
+ - very large logs that may need later exact slices -> store sanitized output with `context-guard-artifact store` and query only needed lines/patterns.
23
+ - noisy command output -> use `context-guard-trim-output` wrappers or the example PreToolUse hook.
24
+ - grep/diff output with possible secrets -> use `context-guard-sanitize-output` or the example Bash hook.
25
+ - expensive reasoning -> route default work to `sonnet` and lower `/effort`; reserve Opus/`opusplan` for planning.
26
+ - noisy exploration -> keep it local: use `rg`, `context-guard-read-symbol`, artifact queries, or a bounded subagent only when parallel value justifies the multiplier.
27
+ 3. Produce a minimal action plan with:
28
+ - immediate changes,
29
+ - config or hook snippets,
30
+ - validation command,
31
+ - risks and rollback.
32
+ 4. Do not recommend payment/limit bypasses, account sharing, leaked-source patches, or other unsafe/unauthorized methods.
33
+
34
+ Useful local commands provided by this plugin:
35
+
36
+ ```bash
37
+ context-guard-audit ~/.claude/projects --top 20 --recommend
38
+ context-guard-setup --plan
39
+ context-guard-diet scan .
40
+ context-guard-read-symbol path/to/file.py TargetSymbol
41
+ context-guard-artifact store --command "long-command" --json < large.log
42
+ context-guard-artifact get <artifact_id> --lines 1:80
43
+ context-guard-trim-output --max-lines 120 -- npm test
44
+ context-guard-sanitize-output -- rg -n "TOKEN|SECRET" .
45
+ context-guard-statusline
46
+ ```
47
+
48
+ If installing hook examples, prefer project-local opt-in settings first. Do not silently modify global `~/.claude/settings.json`.
@@ -0,0 +1,40 @@
1
+ ---
2
+ description: Interactive or guided project setup for Claude Code token optimizer settings. Use when the user asks to install, configure, setup, enable hooks, or choose token-saving options interactively.
3
+ argument-hint: [plan|apply|options]
4
+ allowed-tools: Bash(context-guard-setup *), Bash(context-guard-diet scan *)
5
+ ---
6
+
7
+ # ContextGuard Setup
8
+
9
+ Goal: help the user configure this plugin without memorizing helper commands.
10
+
11
+ Default flow:
12
+
13
+ 1. Run a read-only plan first:
14
+
15
+ ```bash
16
+ context-guard-setup --plan
17
+ ```
18
+
19
+ 2. Explain the options briefly:
20
+ - deny bulky/sensitive reads,
21
+ - token/cost statusline,
22
+ - Bash trim + grep/diff sanitizer hook,
23
+ - large Read guard,
24
+ - failed-attempt nudge for repeated Bash failures,
25
+ - missing model/effort defaults.
26
+ 3. If the user wants the recommended project-local setup, run:
27
+
28
+ ```bash
29
+ context-guard-setup --yes
30
+ ```
31
+
32
+ 4. Treat the post-apply `context-guard-diet scan` summary emitted by setup as the default remaining-gap check; run `context-guard-diet scan .` separately only when the user wants the full report.
33
+ 5. For automation that must skip the post-apply scan summary, run `context-guard-setup --no-diet-scan --yes`.
34
+ 6. If they want extra token reduction beyond setup, prefer local artifact escrow, symbol reads, and semantic digests rather than external model offload.
35
+
36
+ Safety:
37
+
38
+ - Do not modify global `~/.claude/settings.json`.
39
+ - Prefer project-local `.claude/settings.json`.
40
+ - Setup's post-apply scan is local, read-only, and prints a summary only; it does not mutate settings.