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:
co-authored by
Claude Opus 4.8
parent
bc3696bb38
commit
67e6b0e84d
@@ -155,6 +155,8 @@ Every time an AI assistant has to rediscover its own tools, re-read scattered in
|
||||
|
||||
Less wandering means fewer tokens spent on overhead and more spent on your actual problem. The structure does the remembering, so the assistant doesn't have to.
|
||||
|
||||
**Thin session — thousands of skills, near-zero startup cost.** Listing every skill to the assistant up front costs ~11k tokens *per session*. Athena hides the bulk behind a native, reversible `skillOverrides` map and surfaces only the ~5 most relevant skills per prompt (a fail-open `UserPromptSubmit` router), so the model starts clean and pulls capability on demand — every skill still reachable by `/name`. **~11k tokens saved per session.** See [docs/thin-session.md](docs/thin-session.md).
|
||||
|
||||
---
|
||||
|
||||
## Why it's efficient (in short)
|
||||
|
||||
+7
-1
@@ -162,8 +162,14 @@ layer1b_plugins() {
|
||||
layer2_registry() {
|
||||
phase 2 || return 0; say "Слой 2 — реестр способностей"
|
||||
R="$HOME/.agents/registry/scripts"
|
||||
[ -d "$R" ] && run "cd '$R' && (python3 build_registry.py; python3 build_views.py; python3 validate.py) || true" \
|
||||
[ -d "$R" ] && run "cd '$R' && (node build-skill-index.mjs; python3 build_registry.py; python3 build_views.py; python3 validate.py) || true" \
|
||||
&& ok "registry пересобран" || warn "нет ~/.agents/registry — придёт с дотфайлами"
|
||||
# thin-session: спрятать массу личных скиллов из инжекта Claude (skillOverrides=
|
||||
# user-invocable-only) — чистый старт сессии (~11k токенов экономии). Аллоулист остаётся
|
||||
# видимым; остальное достаётся router-скиллом athena-research + UserPromptSubmit-хуком и /name.
|
||||
# Идемпотентно, карта выводится из локальной ФС → ~/.claude/settings.local.json.
|
||||
GSO="$HOME/.claude/scripts/gen-skill-overrides.mjs"
|
||||
[ -f "$GSO" ] && run "node '$GSO'" && ok "thin-session: скиллы скрыты из инжекта (allowlist on)" || true
|
||||
}
|
||||
|
||||
# ───────── Слой 3: проекты (Работа) ─────────
|
||||
|
||||
@@ -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)
|
||||
);
|
||||
|
||||
@@ -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}`);
|
||||
@@ -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.
|
||||
@@ -0,0 +1,87 @@
|
||||
# Thin session — thousands of skills, near-zero startup cost
|
||||
|
||||
## The problem
|
||||
|
||||
Claude Code injects the **name (and description) of every personal skill** in
|
||||
`~/.claude/skills` into the system prompt at the **start of every session**. With
|
||||
~1,400 skills that is **~11k tokens spent before you type a single character** —
|
||||
every session, paying to advertise tools you mostly will not use this turn.
|
||||
|
||||
## What changed
|
||||
|
||||
Athena now ships a **thin session**: the bulk of skills are hidden from the
|
||||
model's listing, and the right ones are surfaced **on demand** instead. Nothing is
|
||||
moved or deleted — the skills stay exactly where they are and remain fully usable.
|
||||
|
||||
Three parts:
|
||||
|
||||
1. **Hide the bulk — native, reversible.** `gen-skill-overrides.mjs` writes a
|
||||
`skillOverrides` map into `~/.claude/settings.local.json`, setting every skill
|
||||
except a small allowlist to **`user-invocable-only`** — Claude Code's built-in
|
||||
state meaning *"hidden from the model, but still runnable by you via `/name`."*
|
||||
Hidden skills cost **zero** injection tokens.
|
||||
2. **Surface on demand — always-on.** A `UserPromptSubmit` hook
|
||||
(`skill-router.mjs`) runs the local capability router on every substantive
|
||||
prompt and injects only the **top-5 relevant** skills (name + score + path). The
|
||||
model reads the one that fits and follows it. Pure-local Node — ~0 model tokens
|
||||
to produce; only the short ranked list enters context.
|
||||
3. **A router skill — `athena-research`.** Manual entry point: hand it a task or an
|
||||
explicit skill name, it finds and loads the right `SKILL.md`.
|
||||
|
||||
## How it saves tokens
|
||||
|
||||
| | tokens / session |
|
||||
|---|---|
|
||||
| Before | ~11,000 (listing ~1,400 skill names) |
|
||||
| After | ~150 (a ~12-skill allowlist) + a short per-prompt top-5 |
|
||||
| **Saved** | **~11k per session, every session** |
|
||||
|
||||
The model starts clean and **pulls capability by relevance** instead of carrying
|
||||
the whole catalog in context. Less overhead, more room for your actual problem.
|
||||
|
||||
## Why it is safe
|
||||
|
||||
- `user-invocable-only` keeps **`/name` working for every hidden skill** — nothing
|
||||
becomes unreachable.
|
||||
- The hook is **fail-open** (any error/timeout → injects nothing, never blocks your
|
||||
prompt) and **guarded** (skips tiny prompts, slash-commands, and plain
|
||||
confirmations like "ok"/"да").
|
||||
- Reading a `SKILL.md` ignores `skillOverrides`, so the router/hook can **always**
|
||||
load any skill.
|
||||
- **Fully reversible**: delete the `skillOverrides` block (or just the entries you
|
||||
want back).
|
||||
|
||||
## The allowlist
|
||||
|
||||
Kept visible (the model can auto-invoke them): the router itself plus
|
||||
lifecycle / always-on skills. Edit the `ALLOWLIST` set at the top of
|
||||
`~/.claude/scripts/gen-skill-overrides.mjs` and re-run it.
|
||||
|
||||
## Also fixed alongside (routing quality)
|
||||
|
||||
- The capability index now scans `~/.claude/skills` too (it did not before) and
|
||||
**de-duplicates parity copies** across `.claude` / `.agents` / `.codex`, so the
|
||||
router can rank **all** your skills and points at the canonical, `/name`-invocable
|
||||
path.
|
||||
- **Usage/frequency no longer affects ranking.** It is still collected for
|
||||
analytics, but a skill you used once is no longer pinned above genuinely better
|
||||
matches. Ranking is **quality-led**.
|
||||
|
||||
## Use it
|
||||
|
||||
- **Fresh install:** `bootstrap.sh` runs the generator in Layer 2 — thin session is
|
||||
**on by default**.
|
||||
- **Existing install:** `node ~/.claude/scripts/gen-skill-overrides.mjs`, then
|
||||
restart Claude Code.
|
||||
- **Revert:** remove `skillOverrides` from `~/.claude/settings.local.json`.
|
||||
|
||||
## Files
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `~/.claude/scripts/gen-skill-overrides.mjs` | generates the hide-map (allowlist editable here) |
|
||||
| `~/.claude/hooks/skill-router.mjs` | `UserPromptSubmit` hook — per-prompt top-5 |
|
||||
| `~/.claude/skills/athena-research/SKILL.md` | manual router skill |
|
||||
| `~/.agents/registry/scripts/build-skill-index.mjs` | index now covers `~/.claude/skills` + dedup |
|
||||
| `~/.agents/registry/scripts/route-skills.mjs` | ranking (usage removed from ordering) |
|
||||
| `~/.agents/registry/scripts/build_registry.py` | score is quality-led (usage unweighted) |
|
||||
Reference in New Issue
Block a user