From lazycortex-core
Optimize Claude Code context loading for the current project. Slims oversized rules files by moving reference material to agent definitions, audits global settings for project-specific leakage and moves entries to local settings. Run when startup feels slow or after adding new rules/agents.
How this skill is triggered — by the user, by Claude, or both
Slash command
/lazycortex-core:lazy-core.optimizeThis skill is limited to the following tools:
The summary Claude sees in its skill listing — used to decide when to auto-load this skill
Reduce startup context weight and fix settings layer violations for the current project.
Reduce startup context weight and fix settings layer violations for the current project.
Path expansion (applies to this skill and every dispatched agent): Glob and Read do not shell-expand ~ or $HOME. Before any Glob/Read targeting a home-relative path, run Bash(echo $HOME) once and substitute the result (or read the absolute home path from the session env block). A literal ~/.claude/rules/*.md or $HOME/.claude/rules/*.md passed to Glob will match nothing and silently report "empty".
This skill has 11 ordered steps. The executing agent MUST NOT skip, merge, reorder, or silently omit any step. To make dropped steps structurally impossible:
TaskCreate with exactly one task per step below — no merging, no abbreviation, no renaming. The canonical list (use these titles verbatim):
Phase 1 — Audit context weightPhase 2 — Fix oversized rules filesPhase 2.5 — LLM-readability auditPhase 3 — Audit global settings for project leakagePhase 4 — Fix settings leakagePhase 5 — Memory index healthPhase 5.5 — Expert memory hygienePhase 6 — Heavy-scan delegation auditPhase 7 — Fill agent_models wizardReport (Output / Optimization Results)Log the runin_progress on enter and completed on exit. "Completed" means "I executed the step's logic AND produced a report line for it". No-ops count only if they produced an explicit outcome line (e.g. asserted, already-ignored, absent, skipped-per-user-choice).TaskList shows every prior task completed or explicitly skipped with an outcome. A still-pending task is a bug — stop and execute it first.Measure everything that loads at conversation start.
Measure byte sizes of everything Claude Code loads into every session's context on every turn:
$HOME/.claude/CLAUDE.md (global instructions)<project>/.claude/CLAUDE.md (project instructions) — also CLAUDE.md at repo root if present$HOME/.claude/rules/*.md without a paths: key in YAML frontmatter (scoped rules only load when files matching their glob are touched, so they don't count)<project>/.claude/rules/*.md without a paths: key$HOME/.claude/projects/<project-key>/memory/MEMORY.md (memory index — auto-loaded)Thresholds (mirror lazy-core.doctor): total > 20 KB → WARN, > 40 KB → FAIL. This is the real token budget — each turn pays this cost.
Count and total sizes of:
.claude/agents/*.md.claude/skills/*/SKILL.md.claude/commands/*.md$HOME/.claude/commands/*.md (global commands)$HOME/.claude/skills/*/SKILL.md (global skills)Show two tables (always-loaded sorted by size desc, on-demand sorted by size desc) with file path, size, and count. Show totals for each category.
For each rules file over 3 KB:
Read the rules file and identify its corresponding agent(s):
.claude/agents/ for agents that reference this rules fileClassify every section as constraint or reference:
Show the classification to the user and ask for confirmation before proceeding.
Rewrite:
## Reference: <topic> headersAfter rewriting, re-measure and show the before/after comparison.
Every file under this phase's scope is authored for the LLM, not humans. Detect constructs that look clear on a page but hurt LLM comprehension — decision-logic tables, narrative preamble, cross-references without anchors, decorative markers, and long prose where bullets would serialize better. Rewrites require per-finding user confirmation.
Scan every LLM-consumed artifact file:
.claude/rules/*.md, $HOME/.claude/rules/*.md.claude/skills/*/SKILL.md, $HOME/.claude/skills/*/SKILL.md.claude/agents/*.md, $HOME/.claude/agents/*.md.claude/commands/*.md, $HOME/.claude/commands/*.md.claude/skills/*/references/*.md, $HOME/.claude/skills/*/references/*.mdExcluded: README*.md, CHANGELOG.md, docs/**, CLAUDE.md at any scope, and any non-.md file.
Dispatch up to 5 Explore subagents in parallel — one per file-group (rules / skills / agents / commands / references) — in a single message with N Agent tool calls. Each uses subagent_type: "Explore", mode: "dontAsk". The prompt passes the scope glob list and the pattern catalog (2.5c). Budget: "Report under 600 words". If a group has zero files, skip its dispatch.
Each agent returns a finding list with this shape per entry:
- file: <project-relative path>
line_start: <int>
line_end: <int>
pattern: P1 | P2 | P3 | P4 | P5 | P6
original: <verbatim snippet, ≤400 chars; elide with "…" if longer>
rewrite_class: <short label, e.g. "table→numbered-cases">
reason: <one-line rationale>
Agents flag a finding for each occurrence of any of:
if, when, unless, else, otherwise, except when), imperatives (must, should, do not, always, never), or action verb-phrases. rewrite_class: "table→numbered-cases".Stage | Inputs | Outputs | Rule, Step | Trigger | Action) AND cells contain verb phrases requiring the reader to cross-reference headers to recover meaning. rewrite_class: "table→named-entries"."This skill...", "Welcome to...", "This guide walks you through...", "The purpose of this document is...". rewrite_class: "delete-or-fold-to-description"."as mentioned above", "see the section below", "the previous section" without a concrete section name, heading anchor, or file path. rewrite_class: "inline-or-anchor".✅, ❌, 🔴, ⚠️, →) used as visual bullets where semantics are already carried by surrounding text. rewrite_class: "strip-decoration".rewrite_class: "prose→bullets".Must NOT flag (preserve):
Thought | Reality in superpowers:using-superpowers).## Reference: headings in agent definitions.Coordinator deduplicates findings by (file, line_start, pattern) and groups by file. For every finding, assign:
check_id: llm-readability.<pattern-slug> — one of decision-table, abstract-header-table, narrative-preamble, restated-cross-ref, decorative-marker, long-prose.scope: project (path inside the repo) or personal (path under $HOME/.claude/**).fingerprint: (check_id, normalized_path, detail_hash) where detail_hash is the first 8 hex chars of sha256(normalized_original) — whitespace collapsed, line numbers stripped.Load waivers from both stores (same format as lazy-core.doctor Phase 2.7b):
$HOME/.claude/projects/<slug>/memory/doctor.waivers/*.md (project)$HOME/.claude/memory/doctor.waivers/*.md (personal)For each finding whose fingerprint matches a waiver's check_id + normalized_path + detail_hash, move it to a waived_findings list. Render waived count in the summary header, same as doctor.
Render a summary block:
## Phase 2.5 — LLM-readability audit
- Files scanned: N (rules=A, skills=B, agents=C, commands=D, references=E)
- Findings: M across K files
- By pattern: P1=x, P2=x, P3=x, P4=x, P5=x, P6=x
- Waived: W
Then, per non-waived finding, render:
#### [P1] decision-logic table in <file>:<line_start>–<line_end>
<reason>
--- original ---
<snippet>
--- proposed rewrite class ---
<rewrite_class>
AskUserQuestion with three options:
AskUserQuestion ("Apply this diff? / Edit further / Cancel"), and on confirmation writes via the Edit tool.Bash(mkdir -p <doctor.waivers-dir>) followed by the Write tool (never chained). File path: <doctor.waivers-dir>/llm-readability.<pattern-slug>__<detail_hash>.md. Frontmatter shape matches the template in lazy-core.doctor Phase 2.7d.Rewrites are generated by the main coordinator, not the scan agent. Scan agents identify constructs; the coordinator synthesizes the rewrite so the user can review the diff in the same turn.
Append one row to the final Optimization Results table (Phase 6 Output):
| LLM-readability rewrites | - | N | applied: A, skipped: S, waived: W |
Read these files:
~/.claude/settings.json (global tracked — enablement only)
~/.claude/settings.local.json (global local — owns global permissions)
.claude/settings.json (project tracked — enablement only)
.claude/settings.local.json (project local — owns project permissions)
For every entry in global settings.json, classify as:
GLOBAL (belongs in global):
PROJECT-SPECIFIC (should be in project settings):
additionalDirectories entriesFor each item classified as PROJECT-SPECIFIC, check if it already exists in the project's settings.local.json. If not, flag it for migration.
For each PROJECT-SPECIFIC entry found in global settings:
.claude/settings.local.json (merge into existing arrays, don't duplicate)$HOME/.claude/settings.jsonAfter all moves, show a summary: N entries moved, from which global section to which project file.
Check the memory index at $HOME/.claude/projects/<project-key>/memory/MEMORY.md:
Report findings. Fix orphaned/broken links automatically, flag stale for user review.
Operates on the .memory/<expert>/ subtree (Spec §8 — distinct from Phase 5's MEMORY.md index). Two checks; both interactive (per-finding AskUserQuestion):
For every note under .memory/<expert>/*.md (skip .tags/):
tags:. For each tag, check whether the matching local tag file .memory/<expert>/.tags/<topic>.md lists this note.For each orphan note, AskUserQuestion:
AskUserQuestion:
question: "Orphan memory note `<path>` — its tags are listed in no local .tags file."
description: "Either the note's tags are stale or the .tags files are. Pick a remedy."
options:
- "Run /lazy-memory.index — regenerate .tags/ from notes"
- "Delete the note (it's no longer reachable)"
- "Leave alone (I'll fix it manually)"
/lazy-memory.index → invoke the sibling skill; state reindexed.Bash(rm <path>); state deleted.For every pair of notes within the same .memory/<expert>/ that share at least one tag and whose titles match by Levenshtein distance ≤ 3:
AskUserQuestion:
AskUserQuestion:
question: "Near-duplicate memory notes: `<note-a>` and `<note-b>` share tags `<topics>` and similar titles."
description: "Consolidating may reduce noise; keeping both is fine if they cover different angles."
options:
- "Show me both (Read each and decide)"
- "Leave alone"
Read each, present a one-line comparison, then ask whether to keep both or merge manually. This phase never auto-merges; merges go through a separate /lazy-memory.write invocation by the operator.Append one row to the Optimization Results table (Output section):
| Memory hygiene | - | N | reindexed: R, deleted: D, kept: K |
Find skills that should be refactored to the coordinator-plus-parallel-Explore-agents pattern described in ${CLAUDE_PLUGIN_ROOT}/references/lazy-core.parallel-scan.md. This phase only reports — it never rewrites skills, because coordinator logic is skill-specific.
.claude/skills/*/SKILL.md (project)$HOME/.claude/skills/*/SKILL.md (global)claude/*/skills/*/SKILL.md (plugin sources, if this repo has a claude/ tree)For each SKILL.md, Read the body (not the frontmatter) and test:
### N., ### Na.)Check N: or Phase N: where each phase reads a distinct file setsubagent_type: "Explore", subagent_type: "general-purpose", in parallel, dispatching-parallel-agents, references/lazy-core.parallel-scan.md, rules/lazy-core.parallel-scan.md, "multiple Agent tool calls".AskUserQuestion, "ask the user", "confirm", "fix which", [y/N]) appears after more than half the scan blocks in (2).If a skill hits all four, it is a candidate.
Group the skill's scan blocks by the top-level file tree they read:
rules/, agents/, skills/, commands/ → "artifact" groupsettings*.json, memory/ → "config+memory" groupCap at 4 agents per skill to keep dispatch cheap and report merging tractable. If natural grouping produces more, combine the smallest.
Emit one section per positive finding plus a summary table:
## Phase 6: Heavy-scan delegation candidates
| Skill | Size | Scan blocks | Suggested split |
|---|---|---|---|
| <skill-name> | N lines / M KB | K | <short split description> |
Each candidate above does K independent scans before any user interaction.
Refactor to spawn Explore agents in parallel and have the skill itself
act as coordinator. See `${CLAUDE_PLUGIN_ROOT}/references/lazy-core.parallel-scan.md`.
If no candidates found, render "No heavy-scan delegation candidates found." and continue.
Delegates to /lazy-core.agent-models. That skill owns all interactive agent-routing logic (config detection, discovery, wizard loop, per-group scope auto-routing, write-back, logging). Keeping it separate lets you run the wizard cheaply on its own (/lazy-core.agent-models) without paying for Phases 1–6.
Invoke /lazy-core.agent-models with no arguments — default --scope=auto routes _user.* → global file, _project.* → project file, _builtin.* → global, plugin-domain groups → plugin's own install scope. That mapping is structural and almost always what the user wants; deviating is an explicit override via --scope=project|global on a direct invocation of the child skill.
/lazy-core.agent-models returns a compact table (destination × added/skipped/via-scope) and a per-entry list. Pass that through into the Phase 8 Output table as a single row:
agent_models entries | - | N | added: A, skipped: S (auto-scope — wrote to: <one-or-two paths>).
If the child reports nothing to do, the row reads: agent_models entries | - | 0 | nothing to do.
The wizard is the single most-rerun piece of optimize (new agents appear, plugins get added, model preferences change). Running the full 10-phase optimize just to touch agent_models is wasteful. The standalone skill is the canonical entry point; this phase is a thin wrapper so full-pipeline runs still fill missing entries as their last interactive act.
End with a summary:
## Optimization Results
| Metric | Before | After | Change |
|--------|--------|-------|--------|
| Rules (always-loaded) | X KB | Y KB | -Z% |
| Settings entries moved | - | N | global -> project |
| Memory issues fixed | - | N | orphaned/broken |
| Delegation candidates | - | N | heavy skills to refactor |
| Memory hygiene | - | N | reindexed / deleted / kept-orphan |
| LLM-readability rewrites | - | N | applied / skipped / waived |
| agent_models entries | - | N | added / skipped (wrote to: <path>) |
Log to ./.logs/claude/lazy-core.optimize/YYYY-MM-DD_HH-MM-SS.md. Use Bash(mkdir -p ...) then Write tool (never chain).
The log's ## Actions section must include an ## llm-readability audit subsection when Phase 2.5 ran:
check_id).<file>:<line_start> <pattern> → apply | skip | waive.waiver written: llm-readability.<pattern-slug> | <normalized_path>.npx claudepluginhub mebius-san/lazy-cortex --plugin lazycortex-coreCreates, edits, and optimizes skills for Claude Code, including drafting, evaluating with test prompts, iterating on performance, and improving skill descriptions for better triggering accuracy.