feat: thin session — hide skill bulk from injection, route on demand

Claude Code injects every personal skill name (~1.4k skills → ~11k tokens) into
each session. Thin session hides the bulk via native skillOverrides
(user-invocable-only) and surfaces the top-5 relevant skills per prompt — saving
~11k tokens/session while keeping every skill reachable by /name.

- gen-skill-overrides.mjs: writes the skillOverrides hide-map (allowlist editable)
- skill-router.mjs: UserPromptSubmit hook, per-prompt top-5, fail-open + guarded
- athena-research: manual router skill
- build-skill-index.mjs: index now scans ~/.claude/skills + dedupes parity copies
- route-skills.mjs / build_registry.py: usage/frequency removed from ranking
  (still collected for analytics; ranking is quality-led)
- settings.json.tmpl: register the hook; bootstrap Layer 2 runs the generator so
  thin session is on by default for fresh installs
- docs/thin-session.md + README: what it is, how it saves tokens, how to revert

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Зарубин Филипп
2026-06-22 20:31:30 +03:00
co-authored by Claude Opus 4.8
parent bc3696bb38
commit 67e6b0e84d
10 changed files with 346 additions and 7 deletions
@@ -4,6 +4,7 @@ import path from "node:path";
const HOME = process.env.HOME;
const roots = [
path.join(HOME, ".claude/skills"),
path.join(HOME, ".agents/skills"),
path.join(HOME, ".codex/skills"),
path.join(HOME, ".codex/plugins/cache"),
@@ -359,6 +360,23 @@ for (const file of skillFiles) {
records.push(record);
}
// Thin-session: collapse parity-duplicate skills (same id present across
// .claude/skills, .agents/skills, .codex/skills) into ONE record, preferring
// the earliest root above (.claude first = canonical, /name-invocable copy the
// router should Read). Without this, adding .claude/skills would double records
// for every parity-synced skill. ponytail: id-dedup, path-level dedup below still runs.
const rootRank = (r) => {
const i = roots.indexOf(r);
return i === -1 ? 999 : i;
};
const bestSkillById = new Map();
for (const rec of records) {
const prev = bestSkillById.get(rec.id);
if (!prev || rootRank(rec.root) < rootRank(prev.root)) bestSkillById.set(rec.id, rec);
}
records.length = 0;
records.push(...bestSkillById.values());
for (const record of await configuredCapabilities()) {
records.push(record);
}
@@ -162,8 +162,11 @@ def effectiveness(stars, rating, parity_warn, usage_norm=0.0,
quality = (rating or 3) / 5 # real output quality (my judgement)
reach = stars_norm(stars) # community proof — weak signal
proven = success_rate if (runs >= 3 and success_rate is not None) else reach
val = round(100 * (0.42 * quality + 0.25 * proven + 0.18 * reach
+ 0.10 * usage_norm + 0.05 * fresh))
# usage/frequency deliberately NOT scored — collected for analytics only, never
# ranks (one past use must not pin a skill to the top). Its old 0.10 weight folds
# into quality so the score stays QUALITY-led and on a 0-100 scale. usage_norm is
# still accepted (callers pass it) but intentionally unused here.
val = round(100 * (0.52 * quality + 0.25 * proven + 0.18 * reach + 0.05 * fresh))
if parity_warn:
val -= 10
if archived:
@@ -182,8 +182,9 @@ function qualityBoost(record, lexicalScore, routeBoost) {
if (!registryScore) return 0;
if (lexicalScore <= 0 && routeBoost <= 0) return 0;
const usageAdj = Math.min(18, Number(reg.usage_30d || reg.usage_count || 0) * 3);
return Math.round(registryScore * 0.9 + usageAdj);
// usage/frequency intentionally excluded from ranking — collected for analytics
// only (one past use must not pin a skill above genuinely better matches).
return Math.round(registryScore * 0.9);
}
function costRank(cost) {
@@ -219,8 +220,7 @@ const scored = index.records
.sort((a, b) =>
b.route_score - a.route_score ||
b.registry_score - a.registry_score ||
b.usage_30d - a.usage_30d ||
b.usage_count - a.usage_count ||
// usage tiebreakers removed — frequency must not affect ordering/selection.
costRank(a.cost_tier) - costRank(b.cost_tier) ||
a.path.localeCompare(b.path)
);
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env node
// Thin-session: UserPromptSubmit hook — always-on GraphiFy auto-routing.
//
// Most local skills are hidden from the model's listing (skillOverrides=
// user-invocable-only). To keep them reachable, on every SUBSTANTIVE prompt this
// runs the local capability router and injects the top-5 candidates as context,
// so the model can Read the right SKILL.md without ever seeing 1400 names.
//
// Pure-local (node + a JSON index) → ~0 model tokens to produce; only the short
// ranked list enters context. Guarded (skips tiny / slash / confirmation prompts)
// and FAIL-OPEN (any error or slowness → emit nothing, never block the prompt).
import { execFileSync } from "node:child_process";
import path from "node:path";
const HOME = process.env.HOME;
const ROUTER = path.join(HOME, ".agents/registry/scripts/route-skills.mjs");
const LIMIT = 5;
const TIMEOUT_MS = 3500;
const MIN_LEN = 10;
// Standalone confirmations / acks (RU+EN) — never worth routing.
const CONFIRM = /^(да|нет|неа|ок(ей)?|ага|угу|ладно|спс|спасибо|готово|понятно|продолжай|дальше|далее|стоп|ok(ay)?|y(es|ep|up)?|no(pe)?|nah|k|thx|thanks|sure|go|go on|next|done|stop|yeah)[\s!.…)?]*$/iu;
function emit(additionalContext) {
process.stdout.write(
JSON.stringify({
hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext },
}),
);
}
let input = "";
process.stdin.on("data", (c) => (input += c));
process.stdin.on("end", () => {
try {
const prompt = (JSON.parse(input).prompt || "").trim();
// Guards — skip cheaply, emit nothing.
if (prompt.length < MIN_LEN) return;
if (prompt.startsWith("/")) return; // slash command
if (CONFIRM.test(prompt)) return; // ack / confirmation
let parsed;
try {
const out = execFileSync(process.execPath, [ROUTER, prompt, "--limit", String(LIMIT), "--json"], {
encoding: "utf8",
timeout: TIMEOUT_MS,
stdio: ["ignore", "pipe", "ignore"],
});
parsed = JSON.parse(out);
} catch {
return; // router missing / slow / error → fail open
}
const results = (parsed.results || []).filter((r) => r && r.path);
if (!results.length) return;
const lines = results.map((r, i) => {
const name = r.name || r.id || "?";
const score = r.route_score ?? r.score ?? "?";
const desc = (r.description || "").replace(/\s+/g, " ").trim().slice(0, 70);
const rel = r.path.replace(HOME, "~");
return `${i + 1}. ${name} (score ${score}) — ${rel}${desc ? `\n ${desc}` : ""}`;
});
emit(
"GraphiFy skill candidates for this task (auto-routed, local — most skills are hidden by design, this is how you find them):\n" +
lines.join("\n") +
"\nIf one clearly fits, Read its SKILL.md and follow it (or hand it to a subagent); ignore the rest and do NOT load other skills. If none fit, just proceed without a skill.",
);
} catch {
// Silent fail — never block a prompt.
}
});
@@ -0,0 +1,81 @@
#!/usr/bin/env node
// Thin-session: regenerate `skillOverrides` in ~/.claude/settings.local.json.
//
// Every personal skill under ~/.claude/skills EXCEPT the allowlist is set to
// "user-invocable-only" — hidden from the model's skill listing (≈0 injected
// tokens) but still invocable by the user via /name, and still Read-able by the
// athena-research router. Allowlist skills are OMITTED from the map, so they
// fall through to the default "on" (model-auto-invocable) — a typo here can
// never force a needed skill off.
//
// Idempotent + machine-portable: it derives the set from THIS machine's FS, so
// it is safe to ship via chezmoi and re-run anywhere. Re-run after adding skills.
//
// node ~/.claude/scripts/gen-skill-overrides.mjs
//
import { promises as fs } from "node:fs";
import path from "node:path";
const HOME = process.env.HOME;
const SKILLS = path.join(HOME, ".claude/skills");
const SETTINGS = path.join(HOME, ".claude/settings.local.json");
// Kept model-auto-invocable (constitution lifecycle + cross-referenced + router).
// caveman/ponytail are PLUGINS (separate visibility) — not listed here.
const ALLOWLIST = new Set([
"athena-research", // the router itself — entry point, must stay visible
"mnemazina", // daily knowledge pipeline, model-invoked by name
"self-learning", // constitution checkpoint
"handoff", // constitution checkpoint
"organize", // constitution structure workflow
"grill-me", // constitution new-work workflow
"codex", // cross-harness handoff, referenced
"humanizer", // constitution: apply every response (UI strings)
"humanizer-ru", // constitution: apply to RU text
"humanizer-en", // constitution: apply to EN text
"skill-creator", // model creates skills on request
"bootstrap-project", // constitution new-project workflow
]);
// Collect skill ids = basename of any dir (<=2 deep under SKILLS) holding SKILL.md.
// Depth 2 covers top-level skills/<id> and one grouping level skills/<grp>/<id>.
async function findSkillIds(root, depth, ids) {
let entries;
try {
entries = await fs.readdir(root, { withFileTypes: true });
} catch {
return ids;
}
if (entries.some((e) => e.isFile() && e.name === "SKILL.md")) ids.add(path.basename(root));
if (depth > 0) {
for (const e of entries) {
if (e.isDirectory() && !e.name.startsWith(".") && e.name !== "node_modules") {
await findSkillIds(path.join(root, e.name), depth - 1, ids);
}
}
}
return ids;
}
const ids = [...(await findSkillIds(SKILLS, 2, new Set()))].sort();
const overrides = {};
for (const id of ids) {
if (!ALLOWLIST.has(id)) overrides[id] = "user-invocable-only";
}
let settings = {};
try {
settings = JSON.parse(await fs.readFile(SETTINGS, "utf8"));
} catch {
/* fresh file */
}
settings.skillOverrides = overrides;
await fs.writeFile(SETTINGS, JSON.stringify(settings, null, 2) + "\n");
const present = [...ALLOWLIST].filter((i) => ids.includes(i));
const missing = [...ALLOWLIST].filter((i) => !ids.includes(i));
console.log(`skills on disk: ${ids.length}`);
console.log(`hidden (user-invocable-only): ${Object.keys(overrides).length}`);
console.log(`allowlist present (stays on): ${present.length} -> ${present.join(", ")}`);
console.log(`allowlist MISSING on disk: ${missing.join(", ") || "(none)"}`);
console.log(`wrote ${SETTINGS}`);
+12
View File
@@ -68,6 +68,18 @@
]
}
],
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "node \"{{ .chezmoi.homeDir }}/.claude/hooks/skill-router.mjs\"",
"timeout": 6,
"statusMessage": "GraphiFy skill routing..."
}
]
}
],
"SessionStart": [
{
"hooks": [
@@ -0,0 +1,56 @@
---
name: athena-research
description: Thin-session capability router. Given a task description OR an explicit skill id, finds the single best local skill via GraphiFy (route-skills.mjs) and Reads only that one SKILL.md to follow it. Most of the ~1450 local skills are hidden from the skill listing (skillOverrides=user-invocable-only) to keep sessions lean — their names/descriptions are NOT in context. Use this whenever you need a capability you don't currently see, or to run a named hidden skill.
---
# athena-research — capability router
Most of the ~1450 local skills are hidden from your skill listing
(`skillOverrides: user-invocable-only`) so the session starts lean. Their bodies
still live in `~/.claude/skills/<id>/SKILL.md` and work fully — you just have to
find and Read the right one on demand. That is this skill's only job.
## Input — one of
- **A task** ("scrape this site to markdown", "review this Go diff", "harvest a
YouTube transcript into the vault"): you don't know the skill name. → *find then load.*
- **An explicit skill id** ("run `firecrawl-scrape`"): you already know it. → *load directly.*
## Protocol
### Task → find then load
1. Run the local router (pure node, ~0 model tokens):
```bash
node ~/.agents/registry/scripts/route-skills.mjs "<task text>" --limit 5 --json
```
2. Look at the 5 results (each has `name`, `route_score`, `path`). Pick the best
fit. If the top score is weak or nothing fits the actual task, say so and
proceed WITHOUT a skill — do not force a bad match.
3. **Read only that one `SKILL.md`** (its `path`) and follow it. Do not load the
other four.
4. If the chosen skill is heavy (large body, many reads, multi-step) or the work
is parallelizable, spawn a subagent with the task + the skill path instead of
running it inline — keep this context lean.
### Explicit id → load directly
1. Read `~/.claude/skills/<id>/SKILL.md`. Some skills are nested
(e.g. `~/.claude/skills/ecc/<id>/SKILL.md`); if the direct path is missing,
run the router with the id as the query to resolve the real `path`, then Read it.
2. Follow it (or hand it to a subagent, same heavy/parallel rule as above).
## Notes
- The `UserPromptSubmit` hook (`~/.claude/hooks/skill-router.mjs`) already runs
this router on every substantive prompt and injects the top 5 — so usually the
candidates are already in front of you. Invoke this skill explicitly mainly for
a **named** skill, or to re-search mid-task with a sharper query.
- **Reading a `SKILL.md` works regardless of `skillOverrides`** (the Read tool
ignores skill visibility). You never need to re-enable a skill to use its body
this way.
- `/name` still works for the user on every `user-invocable-only` skill. Only
`off` skills need re-enabling first.
- The allowlist kept visible (model-auto-invocable) is small and lives in
`~/.claude/settings.local.json` under `skillOverrides`. Everything not listed
there is reached through this router.