@bglocation/tune-context 1.0.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.
@@ -0,0 +1,26 @@
1
+ ---
2
+ name: caveman
3
+ description: Terse caveman output mode — drop articles/filler/pleasantries, fragments OK, no tool-call narration or decorative tables. ~65% fewer output tokens. Invoke to compress responses; suspend for safety warnings and irreversible-action confirmations.
4
+ ---
5
+
6
+ # Caveman mode
7
+
8
+ Terse output to cut **output** tokens (~65%). Output is uncached and ~4–5× the
9
+ price of input, so this is a real cost lever — not just style.
10
+
11
+ ## Rules
12
+ - Drop articles (a/an/the), filler (just/really/basically/simply), pleasantries.
13
+ - Fragments OK. Short synonyms. No tool-call narration, no decorative
14
+ tables/emoji.
15
+ - Technical terms exact; code blocks unchanged; standard acronyms (DB/API) fine.
16
+ - Never invent abbreviations.
17
+ - Pattern: `[thing] [action] [reason]. [next step].`
18
+
19
+ ## Suspend (clarity wins)
20
+ - Security warnings; irreversible-action confirmations.
21
+ - Multi-step sequences where compression breeds ambiguity.
22
+
23
+ Resume after clarity is achieved. Terseness never trims a required safety
24
+ confirmation or a real caveat.
25
+
26
+ Source: <https://github.com/JuliusBrussee/caveman>
@@ -0,0 +1,50 @@
1
+ ---
2
+ name: cdd
3
+ description: Comment-Driven Development — write the contract (what/why, inputs/outputs, side effects, edge cases) in comments before the code. The contract becomes the test assertions (CDD↔AAA) and, embedded with the symbol, improves semantic retrieval. Use when writing or reviewing non-trivial functions/classes.
4
+ ---
5
+
6
+ # Comment-Driven Development (CDD)
7
+
8
+ Write the **contract in comments before the implementation**. The comment states
9
+ WHY and the contract; the code states HOW.
10
+
11
+ ## The contract, before the code
12
+ Order:
13
+ 1. A comment describing the unit's purpose — what it does, inputs/outputs, side
14
+ effects, edge cases, invariants.
15
+ 2. The code beneath it.
16
+
17
+ The comment **never paraphrases the code**. It captures the intent and constraints
18
+ the code cannot show on its own.
19
+
20
+ ## Contract = test assertions (CDD ↔ AAA)
21
+ What the comment promises is what the tests assert. The contract is the source of
22
+ the Arrange-Act-Assert cases: each promised behavior, edge case, and invariant
23
+ becomes an assertion. If the comment and the tests disagree, one of them is wrong.
24
+
25
+ ## Comments that retrieve well (CDD ↔ RAG)
26
+ Chunkers embed the leading comment together with the symbol, so the comment lands
27
+ in the symbol's embedding vector. Comment and code are **complementary halves of
28
+ one vector**: the code already supplies the HOW vocabulary (identifiers, calls) for
29
+ free, so the comment must add only what the code cannot express — the domain-level
30
+ WHAT/WHY, in the words someone would *search* with.
31
+
32
+ **Litmus test** before writing a comment: *"does this sentence contain any word not
33
+ already in the code below?"* If not, it is a paraphrase — zero retrieval signal,
34
+ noise for the reader. Rewrite it as contract, or drop it.
35
+
36
+ ## Example
37
+ ```ts
38
+ // BAD (paraphrase — no new signal):
39
+ // Loops through refresh tokens and checks the exp field against now.
40
+
41
+ // GOOD (contract — domain WHAT/WHY):
42
+ // Rejects expired user sessions: a refresh token past its expiry must never mint a
43
+ // new access token (security invariant). Returns the still-valid sessions; throws
44
+ // AuthError on a tampered token.
45
+ function pruneSessions(tokens: RefreshToken[]): Session[] { … }
46
+ ```
47
+
48
+ The good comment adds searchable concepts ("expired session", "refresh token
49
+ reuse", "security invariant") that the code's identifiers don't; the tests assert
50
+ exactly those.
@@ -0,0 +1,28 @@
1
+ ---
2
+ name: phase-workflow
3
+ description: End-of-phase context hygiene. Use when finishing a development/testing/docs phase or switching to an unrelated task — writes a compact state-doc and prompts for /compact (phase boundary) or /clear (new task). The reset itself stays a user action.
4
+ ---
5
+
6
+ # Phase workflow — end-of-phase context hygiene
7
+
8
+ Run at a phase boundary (development → testing → docs) or when switching to an
9
+ unrelated task. Compaction is **user-initiated** (`/compact` / `/clear` are
10
+ client commands — the model can't invoke them); this skill prepares for it so
11
+ nothing important is lost.
12
+
13
+ ## Procedure
14
+ 1. **Write / update a state-doc** — a compact snapshot of what matters going
15
+ forward: decisions made, open threads, the current path/plan, and the next
16
+ step. Keep it short; it becomes the seed of the next context.
17
+ 2. **Choose the reset:**
18
+ - Same session, thread closed → **`/compact`** (summarizes history, keeps
19
+ continuity).
20
+ - New, unrelated task → **`/clear`** (fresh context; the old task's files and
21
+ diffs are dead weight).
22
+ 3. **Run the reset yourself** — the model cannot invoke `/compact` / `/clear`.
23
+
24
+ ## Automated backing (hooks)
25
+ Once the tune-context hooks are installed, a `PreCompact` hook writes the
26
+ state-doc before any compaction and a `SessionStart` (matcher `compact`) hook
27
+ re-injects it after — so the state-doc survives even an auto-compaction
28
+ (mechanism confirmed; see the configurator epic).
@@ -0,0 +1,52 @@
1
+ ---
2
+ name: token-efficiency
3
+ description: Token-saving working methods — prefer semantic search over grep, read only what you need, delegate broad searches to subagents, keep context lean. Use before broad code exploration, when reading large files, or as a session's context grows.
4
+ ---
5
+
6
+ # Token efficiency
7
+
8
+ Cut context (input) and output tokens without losing correctness. Apply before
9
+ broad exploration and as a session grows.
10
+
11
+ ## 1. Search by meaning, not by text
12
+ When a semantic-search MCP is available (`search_codebase` from
13
+ code-search-mcp), prefer it over broad `grep -r` / `find` for conceptual
14
+ "where/why is X" questions, then read **only** the returned spans. Keep `grep`
15
+ for exact string/symbol lookups. Broad text search pulls whole files into
16
+ context; semantic search returns just the relevant span. Narrow with a `segment`
17
+ filter when you know which side you need (code vs docs).
18
+
19
+ ## 2. Read narrow
20
+ - After a search hit, read only the returned range (`get_chunk`, or a ranged
21
+ read around the line span) — not the whole file.
22
+ - After edits, read `git diff`, not a re-read of the changed files.
23
+ - Never re-read a file already in context. The cheapest token is the one you
24
+ don't carry forward.
25
+
26
+ ## 3. Delegate — and right-size the model
27
+ When answering needs sweeping many files (naming-convention hunts, "where is
28
+ everything about X"), delegate to the **`explore-cheap`** subagent (read-only, on
29
+ a cheap model): it burns its own context and returns the conclusion, so the main
30
+ session pays for the answer, not the search. For a judgment second-pass before
31
+ committing non-trivial changes, use **`reviewer`** (a strong model). Right-size:
32
+ cheap model for mechanical search, strong for judgment.
33
+
34
+ ## 4. Comments that retrieve well (CDD ↔ RAG synergy)
35
+ Chunkers embed the leading comment together with the symbol, so a contract-first
36
+ comment (see the `cdd` skill) literally lands in the embedding vector. Write
37
+ comments in the domain vocabulary someone would *search* with — better contracts
38
+ → better retrieval → fewer missed reads.
39
+
40
+ ## 5. Context hygiene
41
+ - `/compact` after a work thread closes (keeps the thread, drops raw detail);
42
+ `/clear` between independent tasks. See the `phase-workflow` skill.
43
+ - Old turns ride along as input on every later request — don't carry dead weight.
44
+
45
+ ## 6. Measure, don't believe
46
+ If the tool logs usage (`.rag/usage.jsonl` → `rag-usage`), review it
47
+ periodically: is semantic search actually replacing grep? Promote or drop levers
48
+ on data, not faith.
49
+
50
+ ## In a new project
51
+ Set up semantic search proactively — `npx -p @bglocation/code-search-mcp
52
+ rag-init`, then build the index — so this lever exists from the start.
@@ -0,0 +1,157 @@
1
+ ---
2
+ name: tune-context
3
+ description: Configure this project for token-efficient Claude Code use — detect the stack, existing MCP servers and wiki, then generate a lean project CLAUDE.md, wire the doctrine skills, and set up permissions. Run once per repo; idempotent.
4
+ disable-model-invocation: true
5
+ ---
6
+
7
+ # tune-context — configure a repo for token efficiency
8
+
9
+ Three phases, in order: **detect → generate → verify**. Gather facts before
10
+ writing anything. Templates live in `${CLAUDE_SKILL_DIR}/templates/`.
11
+
12
+ ## Managed blocks — how idempotency actually works
13
+ Everything you generate into an existing file goes **inside markers**:
14
+
15
+ ```
16
+ <!-- >>> tune-context (managed) >>> … generated … <!-- <<< tune-context (managed) <<< -->
17
+ ```
18
+
19
+ Rules: replace **only** what is between the markers; never touch anything outside
20
+ them; if the markers are absent in an existing file, insert a fresh block rather
21
+ than rewriting the file. For JSON (`.mcp.json`, `settings.json`) there are no
22
+ markers — merge key-by-key and preserve every existing key. This is what makes a
23
+ second run a no-op.
24
+
25
+ **Delta only, never duplicate.** If the existing hand-written CLAUDE.md already
26
+ covers the template's content (build/test/lint, architecture, conventions), the
27
+ managed block carries **only what is missing** — usually just pointers to the
28
+ doctrine skills — not a second copy of hand-written sections. When in doubt, add
29
+ less: a thin pointer beats a duplicate.
30
+
31
+ ---
32
+
33
+ ## 1. Detect (read-only)
34
+
35
+ **Stack.** Package manager and languages (`package.json`, `pyproject.toml`,
36
+ `go.mod`, `Cargo.toml`, …); the real build / test / lint commands (script names,
37
+ not guesses); monorepo vs single project (workspaces, `packages/`, `apps/`).
38
+
39
+ **Existing MCP servers — check every scope** (do not assume only `.mcp.json`):
40
+
41
+ | Scope | Where |
42
+ |---|---|
43
+ | project | `./.mcp.json` |
44
+ | user | `~/.claude.json` → top-level `mcpServers` |
45
+ | local | `~/.claude.json` → `["<abs project path>"].mcpServers` |
46
+ | gating | `settings.json`: `enabledMcpjsonServers`, `disabledMcpjsonServers`, `allowedMcpServers`, `deniedMcpServers` |
47
+
48
+ If `CLAUDE_CONFIG_DIR` is set, `.claude.json` lives there instead of `~`.
49
+
50
+ **Classify each server** — this is what turns "a server exists" into a rule:
51
+
52
+ | Type | Rule to write into the project CLAUDE.md |
53
+ |---|---|
54
+ | semantic code search | search by meaning, read only returned spans |
55
+ | wiki / docs | look up docs through this MCP, don't paste pages |
56
+ | database | schema and queries through the MCP, don't dump tables |
57
+ | VCS / issues | PR and issue state through the MCP, not full `git log` |
58
+ | unknown | inspect its tools; if any returns whole pages/tables, prefer the narrow variant |
59
+
60
+ **Wiki / docs location** — decides the lever:
61
+ - local markdown tree (`wiki/`, `docs/`) or a clonable git wiki → **RAG segment**
62
+ - hosted SaaS (Confluence, Notion) → **its own MCP** (RAG cannot index it)
63
+ - a few canonical pages → just a **pointer** in CLAUDE.md
64
+
65
+ **Existing config.** Note whether `./CLAUDE.md`, `.claude/settings.json`,
66
+ `.mcp.json`, `rag.config.json` already exist — you will merge, never clobber.
67
+ For `settings.json` also check `hooks.PreCompact` / `hooks.SessionStart` /
68
+ `hooks.PostToolUse` / `hooks.SubagentStart` for an entry already calling
69
+ `pre-compact-snapshot.mjs` / `session-start-reinject.mjs` / `adoption-log.mjs`
70
+ (idempotency: skip if present — `adoption-log.mjs` is registered under both
71
+ `PostToolUse` and `SubagentStart`) and `permissions.allow` for entries already
72
+ covering the detected build/test/lint commands.
73
+
74
+ ---
75
+
76
+ ## 2. Generate (idempotent, never clobber)
77
+
78
+ 1. **Project `./CLAUDE.md`** from `${CLAUDE_SKILL_DIR}/templates/CLAUDE.md.project.tmpl`.
79
+ Fill the slots from detection; delete the slot guide comment; keep the managed
80
+ markers. If the file exists, replace only the managed block — hand-written
81
+ content outside it survives untouched.
82
+ 2. **User `~/.claude/CLAUDE.md`** from `${CLAUDE_SKILL_DIR}/templates/CLAUDE.md.user.tmpl`
83
+ — only if it is missing or clearly untuned. Never overwrite a user-tuned file
84
+ without asking.
85
+ 3. **Doctrine skills** — ensure `token-efficiency`, `caveman`, `cdd` and
86
+ `phase-workflow` are present in `~/.claude/skills/` (they ship with this tool).
87
+ 4. **`.mcp.json`** — **merge**. Add a semantic-search server only if none was
88
+ detected in any scope. Preserve every existing server and key.
89
+ 5. **Hooks** — ensure `~/.claude/hooks/pre-compact-snapshot.mjs`,
90
+ `~/.claude/hooks/session-start-reinject.mjs` and `~/.claude/hooks/adoption-log.mjs`
91
+ exist (they ship with this tool, installed once user-level — same as the
92
+ doctrine skills in step 3). Merge into `settings.json` from
93
+ `${CLAUDE_SKILL_DIR}/templates/settings.json.tmpl`: append the `PreCompact`
94
+ (matcher `"*"`, docs: omit or `*` = every trigger), `SessionStart`
95
+ (matcher `"compact"`), `PostToolUse` (matcher `"*"`) and `SubagentStart`
96
+ (matcher `"*"`) entries **only if an entry calling that script isn't already
97
+ there** — treat each hook array as a set keyed by `command`, not a value to
98
+ overwrite.
99
+ - `PreCompact` writes a mechanical git/branch/status snapshot per-project to
100
+ `~/.claude/tune-context/state/`; `SessionStart(compact)` reads it back via
101
+ `additionalContext`. Filesystem/git facts only — not decisions/open threads
102
+ (a hook has no model access).
103
+ - `adoption-log.mjs` is registered under **both** `PostToolUse` (every tool
104
+ call) and `SubagentStart` (subagent spawns — these are NOT PostToolUse tools,
105
+ they fire their own event carrying `agent_type`). It appends one line per
106
+ event to `~/.claude/tune-context/adoption.jsonl` — which lever the model
107
+ reached for (RAG vs grep, Skill, subagent, re-reads). Read it with
108
+ `eval/adoption-report.mjs` (the `rag-usage` analog). Behavioral proxy only:
109
+ no token cost (needs OTEL `claude_code.cost.usage` + a collector) and no
110
+ caveman (an output style, not a tool call).
111
+ 6. **`settings.json` permissions** — merge `permissions.allow`: the project's
112
+ safe, frequent commands (build/test/lint, `git status`/`diff`/`log`) and
113
+ `mcp__<server>__<tool>` for detected servers. Union with the existing array
114
+ (dedupe, never remove entries). Never add blanket `Bash(*)` or bypass modes.
115
+ 7. **Wiki** — wire the lever chosen in detection (segment / MCP note / pointer).
116
+
117
+ Keep the generated CLAUDE.md **thin**: headings and pointers only. Depth belongs
118
+ in skills — that is the whole point of this setup.
119
+
120
+ ---
121
+
122
+ ## 3. Verify (before reporting done)
123
+
124
+ - Every command written into CLAUDE.md **actually exists** (check the script names
125
+ you found; don't trust the template).
126
+ - Every internal link resolves to a real file.
127
+ - Skill descriptions still fit the listing budget (a handful of skills, each
128
+ description one or two sentences).
129
+ - If a semantic-search MCP is configured, it answers a probe query.
130
+ - Hook scripts referenced in `settings.json` exist and are executable
131
+ (`node ~/.claude/hooks/pre-compact-snapshot.mjs` under empty stdin `{}`
132
+ should exit 0 without throwing; same for `adoption-log.mjs`).
133
+ - **The merge actually landed — don't just trust step 5 ran.** Re-read the
134
+ target `settings.json` (the same file you merged into) and parse it: confirm
135
+ `hooks.PreCompact`, `hooks.SessionStart`, `hooks.PostToolUse` and
136
+ `hooks.SubagentStart` each contain an entry whose `command` references the
137
+ expected script (`pre-compact-snapshot.mjs` / `session-start-reinject.mjs` /
138
+ `adoption-log.mjs` twice, for `PostToolUse` and `SubagentStart`). Copying the
139
+ hook scripts to `~/.claude/hooks/` is not sufficient — a real prior incident
140
+ had the scripts present and executable while `settings.json` had **no**
141
+ `hooks` key at all, so the hooks silently never fired. Scripts-exist and
142
+ entries-are-registered are two different, both-required checks.
143
+ - **Idempotency:** a second run would produce no changes.
144
+
145
+ Report what you created, what you merged, and anything you deliberately skipped.
146
+
147
+ ---
148
+
149
+ ## Rules
150
+
151
+ - **Never clobber.** Merge into existing config. If a conflict cannot be merged
152
+ safely, stop and report it instead of guessing.
153
+ - **RAG is optional.** Everything here works without a semantic-search MCP —
154
+ detect it, never assume it.
155
+ - **Facts over guesses.** Read the manifests; do not invent commands.
156
+ - **Thin always-on.** If content is deep enough to need sections, it belongs in a
157
+ skill, not in CLAUDE.md. `@import` does not save tokens — it is inlined in full.
@@ -0,0 +1,39 @@
1
+ <!-- >>> tune-context (managed) >>>
2
+ Regenerated by /tune-context. Edit freely OUTSIDE this block — content
3
+ outside the markers is never touched. -->
4
+ # CLAUDE.md — {{PROJECT_NAME}}
5
+
6
+ {{ONE_LINE_WHAT_THIS_IS}}
7
+
8
+ ## Build / test / lint
9
+ ```bash
10
+ {{BUILD_CMD}}
11
+ {{TEST_CMD}}
12
+ {{LINT_CMD}}
13
+ ```
14
+ {{RUN_NOTES}}
15
+
16
+ ## Working methods (token-saving)
17
+ {{MCP_RULES}}
18
+ Depth lives in skills: `token-efficiency`, `cdd`, `phase-workflow` (and
19
+ `/caveman` for terse output) — not in this file.
20
+
21
+ ## Architecture
22
+ {{ARCHITECTURE_BULLETS}}
23
+
24
+ ## Conventions that bite
25
+ {{CONVENTIONS}}
26
+
27
+ <!-- <<< tune-context (managed) <<< -->
28
+
29
+ <!--
30
+ Slot guide (delete after filling):
31
+ PROJECT_NAME package/repo name
32
+ ONE_LINE_WHAT_THIS_IS one sentence, what the project is
33
+ BUILD_CMD/TEST_CMD/LINT_CMD verified commands (must actually exist)
34
+ RUN_NOTES how to run locally, if non-obvious
35
+ MCP_RULES one line per detected MCP server (see tune-context skill)
36
+ ARCHITECTURE_BULLETS 3-6 lines, module -> responsibility
37
+ CONVENTIONS only rules that bite (things that break if ignored)
38
+ Keep this file thin: headings + pointers. Depth goes into skills.
39
+ -->
@@ -0,0 +1,23 @@
1
+ # CLAUDE.md (user) — token-efficient defaults
2
+
3
+ Cross-project defaults. **Depth lives in skills** (loaded on demand), not here —
4
+ keep this file thin.
5
+
6
+ ## Working methods (token-saving)
7
+ - **Search by meaning, not text.** Prefer a semantic-search MCP
8
+ (`search_codebase`) over broad `grep`/`find` for "where/why is X"; read only
9
+ the returned spans. Full playbook: `token-efficiency` skill.
10
+ - **Read narrow.** Ranged reads; `git diff` after edits; never re-read a file
11
+ already in context.
12
+ - **Delegate broad searches** to an Explore/subagent — it burns its own context
13
+ and returns the conclusion.
14
+ - **Terse by default;** `/caveman` for maximum compression. (Suspend for safety
15
+ and irreversible-action confirmations.)
16
+ - **Contracts-first** (`/cdd`): write the contract in comments before the code; it
17
+ becomes the test assertions and improves retrieval.
18
+ - **Phase hygiene:** `/phase-workflow` at phase boundaries (state-doc +
19
+ `/compact`); `/clear` between unrelated tasks.
20
+ - **New project:** set up semantic search (`rag-init`) proactively.
21
+
22
+ Skills carry the full playbook: `token-efficiency`, `caveman`, `cdd`,
23
+ `phase-workflow`.
@@ -0,0 +1,58 @@
1
+ {
2
+ "hooks": {
3
+ "PreCompact": [
4
+ {
5
+ "matcher": "*",
6
+ "hooks": [
7
+ {
8
+ "type": "command",
9
+ "command": "node \"$HOME/.claude/hooks/pre-compact-snapshot.mjs\""
10
+ }
11
+ ]
12
+ }
13
+ ],
14
+ "SessionStart": [
15
+ {
16
+ "matcher": "compact",
17
+ "hooks": [
18
+ {
19
+ "type": "command",
20
+ "command": "node \"$HOME/.claude/hooks/session-start-reinject.mjs\""
21
+ }
22
+ ]
23
+ }
24
+ ],
25
+ "PostToolUse": [
26
+ {
27
+ "matcher": "*",
28
+ "hooks": [
29
+ {
30
+ "type": "command",
31
+ "command": "node \"$HOME/.claude/hooks/adoption-log.mjs\""
32
+ }
33
+ ]
34
+ }
35
+ ],
36
+ "SubagentStart": [
37
+ {
38
+ "matcher": "*",
39
+ "hooks": [
40
+ {
41
+ "type": "command",
42
+ "command": "node \"$HOME/.claude/hooks/adoption-log.mjs\""
43
+ }
44
+ ]
45
+ }
46
+ ]
47
+ },
48
+ "permissions": {
49
+ "allow": [
50
+ "Bash({{BUILD_CMD}}:*)",
51
+ "Bash({{TEST_CMD}}:*)",
52
+ "Bash({{LINT_CMD}}:*)",
53
+ "Bash(git status:*)",
54
+ "Bash(git diff:*)",
55
+ "Bash(git log:*)"
56
+ ]
57
+ }
58
+ }