feat: Athena OS Фаза 2 — generic chezmoi-канон Мозга

chezmoi-source (чистая пересборка, не дамп 1.2 ГБ):
- dot_claude: CLAUDE.md лин-роутер, AGENTS.md.tmpl (VPS вычищен),
  settings.json.tmpl (deny-щит 20 + security-guard hook), rules
  (structure + ECC 21 язык), 30 generic ECC-агентов, health-check
- dot_codex: symlink-паритет; dot_agents: registry 13 скриптов
  HOME-генерик + методология docs
- плагины: plugins.manifest + bootstrap Слой 1b (marketplace+install)
- launchd: health.plist (PATH-фикс 127) + session-reaper.example
- smoke++: secret-токен guard + канон-проверки (зелёный)
- 0 hard личных данных; cut личного (kb/references/gsd/owner) → Ф4
This commit is contained in:
Зарубин Филипп
2026-06-15 16:59:09 +03:00
parent 25a7005f5d
commit f219b1fc67
188 changed files with 16165 additions and 5 deletions
@@ -0,0 +1,112 @@
# Shared Skills And Workflows
> Inventory regenerated by build_registry.py on bootstrap (Layer 2).
Applies to: Claude, Codex, and any agent that can read `~/.agents`
This is the shared source of truth for concrete skills, workflows, installation propagation, usage tracking, and GitHub activity signals.
## Required Read Rule
Before selecting or installing skills/workflows, every agent should read this file first, then read tool-specific instructions only when needed.
Read order:
1. `~/.agents/SHARED-SKILLS-WORKFLOWS.md`
2. `~/.agents/registry/CAPABILITY-PLANNING.md`
3. Relevant project `AGENTS.md`, `CLAUDE.md`, or `claud.md`
4. Selected skill/workflow body
If a project has stricter rules, follow the stricter project rule.
## Cross-Agent Propagation Rule
When a new skill, workflow, agent role, command, or related configuration is installed:
1. Install or mirror it for both Claude and Codex when technically applicable.
2. Register it in this file under `Shared Additions`.
3. Record expected locations for Claude and Codex.
4. Mark propagation status as one of:
- `synced`: installed or mirrored for both Claude and Codex.
- `codex-only`: only meaningful for Codex.
- `claude-only`: only meaningful for Claude.
- `pending`: not fully propagated yet.
5. Add a validation note explaining how stable operation was checked.
6. If the skill has a public source page or GitHub repository, add it to `~/.agents/INSTALLED-SKILL-SOURCES.md` and `~/.agents/TRACKED-INSTALLED-SOURCES.md`.
Do not delete or move existing skills during propagation unless the user explicitly approves a migration.
## Stable Operation Validation
For explicit concrete workflows, validate:
- The documented skill/agent/command exists at the declared path.
- Existing paths remain valid, or compatibility mirrors exist.
- The workflow has one canonical owner for each generated artifact.
- Agents read indexes/caches before raw large sources.
- No private data is copied across project boundaries by default.
- External actions such as push, publish, deploy, SSH, rsync, DNS, or credential changes require explicit user approval.
## Shared Additions
> This table is populated by `build_registry.py` during bootstrap (Layer 2).
> Run `python3 ~/.agents/registry/scripts/build_registry.py` to regenerate.
| id | type | description | canonical path | claude path | codex path | status | validation |
|---|---|---|---|---|---|---|---|
| cheap-skill-router | workflow | Shared Claude+Codex capability discovery via shared metadata index plus canonical quality signals. | `~/.agents/registry/scripts/capability-plan.mjs` + route/build scripts | same shared scripts | same shared scripts | synced | `capability-plan.mjs` runs graph-first preflight, repo scan, routing, and draft plan. |
| capability-planning-gate | workflow | Mandatory pre-use planning gate for Skills, plugins, MCP, agents, and workflows. | `~/.agents/registry/CAPABILITY-PLANNING.md` | same shared doc | same shared doc | synced | Makes Claude/Codex use the same quality-first capability selection process. |
| instruction-budget-check | command | Checks live project `AGENTS.md` / `CLAUDE.md` files against the hard 200-line budget. | `~/.agents/registry/scripts/check-instruction-budget.mjs` | same shared script | same shared script | synced | Local project smoke passed. |
## Usage Tracking
Record usage in `~/.agents/SKILL-USAGE-LEDGER.md`.
Minimum fields:
`date | agent | skill_or_workflow | task_context | outcome | notes`
Usage frequency categories:
- `representative`: used often and internally convenient.
- `promising`: useful but needs more observations.
- `rare`: valuable for specialist work only.
- `archive-candidate`: duplicated, stale, or inconvenient.
When a skill/workflow is used for a meaningful task, append one row to the ledger. Do not log private case facts; describe task context generically.
## Installed Source Tracking
This system tracks the upstream pages and repositories of installed skills/tools.
Primary files:
- `~/.agents/INSTALLED-SKILL-SOURCES.md` — source URLs grouped by installed skills.
- `~/.agents/TRACKED-INSTALLED-SOURCES.md` — unique public source repositories/pages with latest stars when available.
- `~/.agents/GITHUB-STARS-LEDGER.md` — dated history of star counts.
Stars are a qualifying signal of external engagement or activity. They do not override local usefulness, security, correctness, or fit.
## Weekly Stars Update
Cadence: every 7 days.
Procedure:
1. Read `~/.agents/TRACKED-INSTALLED-SOURCES.md`.
2. For each valid public GitHub repository URL, fetch the current star count.
3. Append dated rows to `~/.agents/GITHUB-STARS-LEDGER.md`.
4. Update `~/.agents/TRACKED-INSTALLED-SOURCES.md` with the latest `stars`, `last_checked`, `status`, and notes.
5. If new installed sources appear in `~/.agents/.skill-lock.json`, add them to `~/.agents/INSTALLED-SKILL-SOURCES.md`.
6. Note repositories that are missing, private, deleted, or rate-limited.
7. Do not modify remote GitHub state.
## Validation Checklist For New Additions
- [ ] Added to `Shared Additions`.
- [ ] Claude location exists or is marked not applicable.
- [ ] Codex location exists or is marked not applicable.
- [ ] Usage tracking rule is clear.
- [ ] Source URL is recorded when available.
- [ ] No existing skill or workflow was removed without approval.
- [ ] External mutation boundaries remain explicit.
@@ -0,0 +1,108 @@
# Capability Planning Gate
Applies to: Claude, Codex
Use before applying any non-trivial Skill, plugin, MCP server, agent, or workflow.
Default automation:
`node ~/.agents/registry/scripts/capability-plan.mjs "<task>" --cwd "$PWD" --limit 10 --external-fallback --log`
This command performs the graph-first preflight, repository scan, capability routing, and draft plan. Agents should run it themselves; the user should not have to ask Graphify questions manually.
Treat the output as a required draft, not blind autopilot. Refine it with repository evidence before calling tools or reading large skill bodies.
## Goal
Pick the best capability set for the actual repository and task before spending context on full skill bodies or tool calls.
Quality comes first. Token cost only breaks ties after fit and expected output quality are effectively equal.
## Procedure
1. Read `~/.agents/SHARED-SKILLS-WORKFLOWS.md`.
2. Run the default automation above.
3. Inspect the repository lightly when the automation shows missing or ambiguous repo signals:
- project rules: `AGENTS.md`, `CLAUDE.md`, `claud.md`
- structure: `rg --files`, package/config files, docs, tests
- current state: relevant git status/diff when editing code
4. If a relevant `graphify-out/graph.json` exists, query it before broad file reads:
- capability system graph:
`graphify query "<question>" --graph ~/.agents/registry/capability-system-graph/graphify-out/graph.json --budget 1200`
- use graph answers to pick exact files/nodes to inspect
5. Build or reuse the shared capability index:
- rebuild after installs or config changes:
`node ~/.agents/registry/scripts/build-skill-index.mjs`
- route:
`node ~/.agents/registry/scripts/route-skills.mjs "<task>" --limit 10`
6. Select capabilities across all types:
- Skills: task methods and domain workflows
- Plugins: artifact surfaces such as browser, documents, spreadsheets, presentations
- MCP: external/local tools such as Context7, Exa, GitHub, Memory, Playwright, Codegraph
7. State the plan briefly before use:
- selected capability
- why it fits this repo/task
- what it will read or do
- why rejected close alternatives are not first choice
8. Read full `SKILL.md` only for selected Skill finalists.
9. Use MCP/plugins only when their capability is directly needed.
10. Log meaningful usage in `~/.agents/SKILL-USAGE-LEDGER.md`.
11. Apply the **Local-First Cascade** below when the preflight reports `local_match: weak` or `none`.
12. After the task, append one outcome line to the **Self-Learning Loop** log.
## Selection Order
1. Required by user or project rule.
2. Repository fit.
3. Expected quality and completeness.
4. Proven local usage and registry score.
5. Public signal: stars, freshness, community proof.
6. Token/runtime cost as tie-breaker.
## Local-First Cascade (grow the arsenal, never recycle blindly)
`capability-plan.mjs --external-fallback` adds a `local_match` verdict and, when local is too weak, an `external_fallback` recipe. Honor it as a cascade:
- **Tier 0 — local:** `local_match: strong` → use the local finalist. Stop. Do not search externally.
- **Tier 1 — external discovery (only on `weak`/`none`):** run the emitted `npx skills find "<terms>"`. READ-ONLY. It lists external skills.sh candidates — treat them as UNVETTED.
- **Tier 2 — gate (mandatory before any install):** read the candidate `SKILL.md`; check author (anthropics / vercel-labs / microsoft = trusted; unknown = full scrutiny or skip); run `uvx mcp-scan@latest --skills`; present what it does + scan verdict to the user.
- **Tier 3 — install (explicit approval only):** `npx skills add <owner/repo@skill>` — never `-y`, never blind `-g`. Re-scan after.
Strong-hit gate: top finalist `route_score >= FALLBACK_FLOOR` (140, calibrated 2026-06-13) and `lexical_score > 0`. Tune via env `CAP_FALLBACK_FLOOR`. Above the floor but semantically wrong? That is still a weak hit — fall back and log the false match.
Invariant: external = untrusted until gated. No install without SKILL.md read + clean mcp-scan + explicit user yes. ToxicSkills (Snyk 2026): 13.4% of ecosystem skills carry CRITICAL flaws.
## Self-Learning Loop (each task better than the last)
The cascade only makes the arsenal grow if outcomes feed back. Two mechanical steps:
**Before** a non-trivial task — scan `~/.claude/references/agents-routing-log.md` for the task class. If past runs fell back or failed, start from the capability that worked / the external skill already identified. Do not re-derive.
**After** the task — append one line to that log, in its existing format:
```text
DATE | <task class> | <capability used> | <✅|⚠️|❌> | local=<strong|weak|none> fell_back=<yes|no> adopted=<skill|–>
```
**On adopt** (Tier 3 install passed): register in `SHARED-SKILLS-WORKFLOWS.md`, run `build-skill-index.mjs`, refresh the graph (capability-system-graph / `/graphify`). The new skill becomes a Tier-0 local hit next time — fallback frequency for that task class decays to zero. That decay IS the growth.
Repeated `fell_back=yes` for one task class = a standing gap: fill it proactively (find + vet + adopt) instead of falling back every run.
**Auto-capture (no discipline required):** the preflight runs with `--log`, so every `weak`/`none` match is appended to `~/.claude/references/routing-auto.log` (TSV) automatically. Surface standing gaps anytime — `node ~/.agents/registry/scripts/routing-gaps.mjs` (prints nothing when there are none; safe to wire into a session-start hook once the log has data).
**Recalibrate `FALLBACK_FLOOR`** when the arsenal changes materially: rerun a labeled HAVE/MISS probe through `route-skills.mjs --json` and set the floor in the valley between their `route_score` ranges.
## Output Template
Keep it terse:
```text
Capability plan:
- repo signal: <what was found>
- graph signal: <graphify node/file/path if used>
- use: <skill/plugin/MCP> — <reason>
- skip: <near alternative> — <reason>
- next: <first action>
```
For tiny tasks, one sentence is enough. For risky or broad tasks, use a short bullet plan.
+166
View File
@@ -0,0 +1,166 @@
# Capability Registry — Practical Reference
> Generated by `build_registry.py` + `build_views.py` on bootstrap (Layer 2).
> This file provides a curated human-readable index of the most useful capabilities
> grouped by domain. The canonical database is `registry.jsonl`.
---
## MCP Servers and Plugins
| Server | Value | When to use |
|--------|-------|-------------|
| **firecrawl-mcp** | Scrape + web search, clean markdown without HTML parsing, batch operations | 20+ pages at once, web search with filters, download site documentation |
| **scrapegraph-mcp** | LLM-driven structured extraction (JSON) from complex pages via prompt | Extract `{title, price}` from a product page directly into JSON |
| **agentmemory** | Semantic memory across sessions — agent recalls past without manual copy-paste | Accumulate error patterns over a week, find similar case in new session |
| **codegraph** | AST navigation: who calls a function, dependency chain — without grepping the whole repo | What breaks when you change an interface — in seconds, not hours |
| **context7** | Current library documentation into context, version-accurate — no hallucinations | Write code against Supabase JS v2 / Next.js 15 / any fresh lib |
| **computer-use** | Control native desktop apps via mouse/keyboard — the only way for apps without an API | Finder, Maps, Notes, desktop forms — without a browser |
| **mcp__playwright** | Browser with DOM access, clicks, forms, network interception — more reliable than coordinate clicks | Log in, click, screenshot, E2E test |
| **mcp__Figma** | Read tokens, layers, frame screenshots from Figma — precise code without guessing the design | Implement a component 1:1 against a design system |
| **mcp__supabase** | Manage Supabase (schema, migrations, SQL, edge functions, logs) without leaving the chat | Create a table, apply a migration, debug a slow query |
---
## Top Skills by Domain
### Design
| Skill | Value |
|-------|-------|
| **frontend-design** | Blocks "AI slop" — forces a concrete aesthetic choice (brutalism, editorial, luxury) and implements with non-default fonts and asymmetry instead of Inter + purple gradient |
| **premium-frontend-ui** | Blueprint for award-level UI: preloader, ScrollTrigger, magnetic buttons, custom cursor with lerp, noise overlays — everything that standard instructions miss |
| **figma** | Mandatory order for Figma MCP: get_design_context → get_screenshot → implement — guarantees 1:1 reproduction instead of guessing |
| **shadcn** | Manages a real shadcn/ui project via CLI: add component, switch theme, update upstream without losing local edits |
| **ui-ux-pro-max** | 50+ visual styles and 161 color palettes as a structured DB — pick a style, get a ready token system without reinventing the wheel |
| **web-design-reviewer** | Opens a browser, takes screenshots at 4 breakpoints, finds layout bugs, overflow, low contrast and fixes source files |
| **nothing-design** | Strict Nothing Phone aesthetic: Space Grotesk/Mono, dot-matrix, no shadows/gradients — concrete tokens, not just "minimalism" |
---
### AgentOps & Infrastructure
| Skill | Value |
|-------|-------|
| **caveman** | Cuts ~75% of tokens in responses without losing meaning — saves budget in long sessions and swarms |
| **dispatching-parallel-agents** | Solve N independent problems in the time of one: each agent gets isolated context and clear scope — 3x speedup |
| **board-council** | 10 subagents in parallel (5 advisors + 5 peer-reviewers) — finds blind spots a single agent misses |
| **continuous-agent-loop** | Navigator of autonomous loop patterns with decision tree and failure recovery — without reading a long document |
| **claude-devfleet** | Multiple Claude Code agents in parallel in isolated git-worktrees via MCP — parallel execution without conflicts |
| **agent-capability-installer** | Installs a skill on both harnesses (Claude + Codex) with SHA pinning and registry entry — eliminates sync drift |
| **agentic-os** | Turns Claude Code into a persistent OS with routing through CLAUDE.md and cron automation — agents work between sessions |
---
### Research & Web
| Skill | Value |
|-------|-------|
| **firecrawl** | Meta-router for all web operations: explains when search→scrape→map→crawl→interact — saves time choosing the tool |
| **firecrawl-search** | Search without URL + full page markdown — no separate scrape needed, all in one call |
| **firecrawl-scrape** | Clean markdown from JS-rendered SPAs — what WebFetch can't do with dynamic sites |
| **firecrawl-deep-research** | Parallel agents on multiple angles of a topic → structured report with sources, not raw results |
| **deep-research** | Structured analysis with tradeoffs and recommendation (architecture, technology, market) — synthesis methodology, not a data collection tool |
| **graphify** | Any folder of files (code, docs, PDF) → interactive graph with communities and BFS/DFS queries — connections that would otherwise go unnoticed |
| **search-first** | Enforces "search npm/PyPI/GitHub first, then write code" — blocks reinventing the wheel |
---
### GSD (Project Management)
| Skill | Value |
|-------|-------|
| **gsd-do** | Accepts arbitrary text and routes to the correct /gsd-* command — eliminates overhead of remembering 26+ commands |
| **gsd-next** | Reads STATE.md + ROADMAP.md and automatically calls the next workflow step — no need to remember where you left off |
| **gsd-fast** | Executes a trivial task directly in context without PLAN.md and subagents — <2 min, one-line description |
| **gsd-plan-phase** | Produces PLAN.md with step-by-step executable prompts via research + verification that the plan achieves the goal |
| **gsd-execute-phase** | Executes phase plans in parallel waves of subagents with atomic commits — each gets fresh 200k context |
| **gsd-verify-work** | Conversational UAT against phase criteria — finds discrepancies, auto-diagnoses and prepares gap plans |
| **gsd-debug** | Systematic debug via hypothesis→experiment→verification with persistent state in .planning/debug/ |
| **gsd-ship** | Closes the loop plan→execution→verification→PR with auto-generated body and merge tracking |
---
### Web / Testing / DevOps
| Skill | Value |
|-------|-------|
| **playwright-generate-test** | Generates a saved working @playwright/test TypeScript spec, validates by running — a file on disk that passes |
| **playwright-explore-website** | Structural reconnaissance of an unfamiliar site: 3-5 key flows, locators, proposed test cases — before writing tests |
| **tdd-workflow** | Tests-first + mandatory 80% coverage across unit/integration/E2E with checklist — stricter than just tdd |
| **webapp-testing** | Interactive check of a local web app via Playwright MCP: screenshots, console, forms, viewport |
| **performance-optimization** | Measurement-first: profiling → CWV targets (LCP/INP/CLS) → fix with regression tests |
| **accessibility** | WCAG 2.2 full audit: perceivable/operable/understandable/robust with AA checklist |
| **docker-patterns** | Docker Compose best practices: Dockerfile hardening, networking, volumes, multi-service |
---
### Finance & Data
| Skill | Value |
|-------|-------|
| **dcf-model** | Institutional-grade DCF with WACC, sensitivity tables, Bear/Base/Bull — live formulas, ready for client delivery |
| **3-statement-model** | Connects IS/BS/CF in a template with integrity checks and balance-sheet verification |
| **equity-research** | Analyst consensus + fundamentals + macro → investment thesis buy/hold/sell in minutes |
| **lbo-model** | LBO template: IRR/MOIC formulas, debt waterfall, sensitivity — for PE deals and IC presentations |
| **audit-xls** | Spreadsheet QA: formula errors, hardcodes, BS-balance, cash tie-out — report first, fix on request |
| **data-visualizer** | Interactive charts/dashboards in React (Recharts/Chart.js/D3) with real-time updates, filters, export |
---
### Security
> Skills in this domain are runbooks/operational references, not AI capabilities for attacking systems.
| Skill | Value |
|-------|-------|
| **security-review** | Code protection checklist during development: authorization, secrets, API, payments — the skill at source-code level |
| **performing-threat-modeling-with-owasp-threat-dragon** | Runbook for STRIDE/LINDDUN data flow diagrams in Threat Dragon — threats found before writing code |
| **building-incident-response-playbook** | Structured IR playbook per NIST 800-61 / SANS PICERL with SOAR integration |
| **detecting-ransomware-encryption-behavior** | Real-time encryption detection via entropy analysis — trigger for auto host isolation |
| **analyzing-memory-dumps-with-volatility** | RAM dump forensics: malicious processes, injected code, credentials — Volatility 2/3 |
---
## Disambiguation — Similar Skills
### Web search and scraping
| Skill | Type | Needs URL? | Returns | When |
|-------|------|-----------|---------|------|
| **firecrawl** | Router | — | Routes to the right tool | Don't know which tool |
| **firecrawl-search** | Search | No | Page markdown | Find pages by topic |
| **firecrawl-scrape** | Scrape | Yes | Clean markdown | Specific URL, JS rendering |
| **firecrawl-deep-research** | Research | No | Multi-source report | Sourced report on a topic |
| **deep-research** | Methodology | — | Synthesis with tradeoffs | Architecture/business decisions |
| **browse** | Browser | Yes | Clicks + screenshots | QA, auth, interaction |
---
### Frontend design
| Skill | Use when |
|-------|---------|
| **frontend-design** | Any web UI — blocks template defaults, forces aesthetic choices |
| **nothing-design** | Explicitly want Nothing Phone brand aesthetic only |
| **premium-frontend-ui** | Award-level bar: preloaders, ScrollTrigger, magnetic buttons |
| **shadcn** | Managing an existing shadcn/ui project |
| **ui-ux-pro-max** | Need a structured style + token system from 50+ options |
| **web-design-reviewer** | Already have a built UI — need automated review + screenshots |
---
## Selection Policy
Quality comes first. Token cost is only a tie-breaker after fit and expected output quality are effectively equal.
```
value(skill | project, task) = effectiveness × fit × right_size − switch_cost
pick = argmax value ; tie-break → lower cost_tier
```
| work | model |
|------|-------|
| product-critical · hard synthesis · architecture · final pass | **Opus** |
| standard build / analysis / code | **Sonnet** |
| bulk / mechanical: grep, classify, format, sort, leaf-workers | **Haiku** |
@@ -0,0 +1,423 @@
#!/usr/bin/env node
import { promises as fs } from "node:fs";
import path from "node:path";
const HOME = process.env.HOME;
const roots = [
path.join(HOME, ".agents/skills"),
path.join(HOME, ".codex/skills"),
path.join(HOME, ".codex/plugins/cache"),
];
const codexConfigPath = path.join(HOME, ".codex/config.toml");
const claudeMcpPath = path.join(HOME, ".claude/mcp.json");
const outDir = path.join(HOME, ".agents/registry");
const outJson = path.join(outDir, "skill-index.json");
const outMd = path.join(outDir, "skill-index.md");
const legacyOutDir = path.join(HOME, ".codex/agent-system-ops/routing");
const legacyOutJson = path.join(legacyOutDir, "skill-index.json");
const legacyOutMd = path.join(legacyOutDir, "skill-index.md");
const skipDirs = new Set([
".git",
"node_modules",
"__pycache__",
".venv",
"venv",
".cache",
"dist",
"build",
]);
const capabilityDescriptions = {
"capability-planning-gate": {
type: "workflow",
name: "Capability Planning Gate",
description: "Mandatory graph-first planning workflow before using Skills, plugins, MCP servers, agents, or workflows. It inspects the repository, queries Graphify, routes capabilities, and explains the selected plan.",
domains: ["agentops", "planning"],
cost_tier: "light",
},
"cheap-skill-router": {
type: "workflow",
name: "Cheap Capability Router",
description: "Shared Claude/Codex capability routing workflow using build-skill-index, route-skills, and canonical registry quality signals.",
domains: ["agentops", "planning"],
cost_tier: "light",
},
"capability-system-graph": {
type: "workflow",
name: "Capability System Graph",
description: "Focused Graphify map of the Claude/Codex capability-selection system. Use before broad reads to find exact rules, scripts, and relationships cheaply.",
domains: ["agentops", "graph"],
cost_tier: "light",
},
github: {
type: "mcp",
name: "GitHub MCP",
description: "Read GitHub repositories, issues, pull requests, files, commits, and reviews. Use for repo inspection, PR review, issue triage, and GitHub evidence.",
domains: ["code", "agentops"],
cost_tier: "medium",
},
context7: {
type: "mcp",
name: "Context7 MCP",
description: "Fetch up-to-date official library documentation and code examples. Use before implementing against current APIs, SDKs, and framework versions.",
domains: ["docs", "code"],
cost_tier: "medium",
},
exa: {
type: "mcp",
name: "Exa MCP",
description: "Neural web search and page fetch. Use for current web research, source discovery, company/person lookup, and fresh external evidence.",
domains: ["research", "web"],
cost_tier: "medium",
},
memory: {
type: "mcp",
name: "Memory MCP",
description: "Local cross-session memory. Use to recall past decisions, previous project context, known bugs, and durable preferences.",
domains: ["agentops", "memory"],
cost_tier: "light",
},
agentmemory: {
type: "mcp",
name: "Agent Memory MCP",
description: "Semantic memory across sessions. Use to find prior observations, decisions, and patterns without loading old chats.",
domains: ["agentops", "memory"],
cost_tier: "light",
},
playwright: {
type: "mcp",
name: "Playwright MCP",
description: "Browser automation with DOM snapshots, clicks, forms, screenshots, console, and network inspection. Use for E2E, QA, and local web app verification.",
domains: ["web", "testing"],
cost_tier: "medium",
},
"sequential-thinking": {
type: "mcp",
name: "Sequential Thinking MCP",
description: "Structured step-by-step reasoning support. Use for complex planning, decomposition, and decision audits when the plan itself is risky.",
domains: ["planning", "agentops"],
cost_tier: "medium",
},
codegraph: {
type: "mcp",
name: "Codegraph MCP",
description: "Code relationship graph and dependency navigation. Use after repository scan for cross-file impact tracing, call graphs, and architecture mapping.",
domains: ["code", "graph"],
cost_tier: "medium",
},
node_repl: {
type: "mcp",
name: "Node REPL MCP",
description: "Persistent JavaScript execution. Use for quick JS probes, data transforms, package inspection, and small generated artifacts.",
domains: ["code", "data"],
cost_tier: "light",
},
"firecrawl-mcp": {
type: "mcp",
name: "Firecrawl MCP",
description: "Web search, scrape, map, crawl, and clean markdown extraction. Use for multi-page research and structured web evidence collection.",
domains: ["research", "web"],
cost_tier: "medium",
},
"scrapegraph-mcp": {
type: "mcp",
name: "ScrapeGraph MCP",
description: "Prompt-driven structured extraction from web pages. Use when the desired output is JSON fields from messy pages.",
domains: ["research", "data", "web"],
cost_tier: "medium",
},
documents: {
type: "plugin",
name: "Documents Plugin",
description: "Create and edit document artifacts, Word files, and Google Docs-ready material.",
domains: ["docs"],
cost_tier: "medium",
},
spreadsheets: {
type: "plugin",
name: "Spreadsheets Plugin",
description: "Create, edit, analyze, visualize, render, and export spreadsheets or Google Sheets-ready workbooks.",
domains: ["data", "finance"],
cost_tier: "medium",
},
presentations: {
type: "plugin",
name: "Presentations Plugin",
description: "Create, edit, render, verify, and export presentation decks and PowerPoint files.",
domains: ["slides", "docs"],
cost_tier: "medium",
},
browser: {
type: "plugin",
name: "Browser Plugin",
description: "Codex in-app browser for opening, inspecting, navigating, testing, clicking, typing, and screenshots.",
domains: ["web", "testing"],
cost_tier: "medium",
},
caveman: {
type: "plugin",
name: "Caveman Plugin",
description: "Terse agent-to-user communication style. Use to keep replies short, accurate, and low-filler.",
domains: ["comms"],
cost_tier: "light",
},
};
function uniq(values) {
return [...new Set(values.filter(Boolean))];
}
function stripYamlQuotes(value) {
return value.replace(/^['"]|['"]$/g, "").trim();
}
function parseFrontmatter(text) {
if (!text.startsWith("---\n")) return {};
const end = text.indexOf("\n---", 4);
if (end === -1) return {};
const fm = {};
for (const line of text.slice(4, end).split(/\r?\n/)) {
const m = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);
if (!m) continue;
fm[m[1]] = stripYamlQuotes(m[2] || "");
}
return fm;
}
function firstParagraph(text) {
const body = text.replace(/^---[\s\S]*?---\s*/m, "");
for (const block of body.split(/\n\s*\n/)) {
const s = block
.split(/\r?\n/)
.filter((line) => !line.trim().startsWith("#"))
.join(" ")
.replace(/\s+/g, " ")
.trim();
if (s.length > 25) return s.slice(0, 360);
}
return "";
}
function headings(text) {
return text
.split(/\r?\n/)
.filter((line) => /^#{1,3}\s+\S/.test(line))
.slice(0, 8)
.map((line) => line.replace(/^#{1,3}\s+/, "").trim());
}
function keywordsFor(record) {
const source = [
record.id,
record.name,
record.description,
record.path,
...record.headings,
]
.join(" ")
.toLowerCase();
const words = source.match(/[a-zа-я0-9][a-zа-я0-9_.-]{2,}/giu) || [];
const stop = new Set([
"the",
"and",
"for",
"with",
"from",
"что",
"как",
"для",
"или",
"это",
"при",
"над",
"через",
"skill",
"skills",
"агент",
"скилл",
]);
return uniq(words.filter((w) => !stop.has(w))).slice(0, 40);
}
async function walk(dir, files = []) {
let entries;
try {
entries = await fs.readdir(dir, { withFileTypes: true });
} catch {
return files;
}
for (const entry of entries) {
if (entry.name.startsWith(".") && entry.name !== ".system") continue;
if (entry.isDirectory()) {
if (skipDirs.has(entry.name)) continue;
await walk(path.join(dir, entry.name), files);
} else if (entry.name === "SKILL.md") {
files.push(path.join(dir, entry.name));
}
}
return files;
}
function capabilityRecord(id, source, configPath) {
const meta = capabilityDescriptions[id] || capabilityDescriptions[id.replace(/@.*$/, "")] || {};
const record = {
id,
type: meta.type || source,
name: meta.name || id,
description: meta.description || `${source.toUpperCase()} capability from local configuration.`,
path: configPath,
root: source,
model: "",
cost_tier: meta.cost_tier || "",
allowed_tools: "",
domains: meta.domains || [],
headings: [source.toUpperCase(), "Local capability"],
updated_at: new Date().toISOString(),
};
record.keywords = keywordsFor(record);
return record;
}
async function configuredCapabilities() {
const records = [];
try {
const config = await fs.readFile(codexConfigPath, "utf8");
for (const match of config.matchAll(/^\[mcp_servers\.([^\]]+)\]/gm)) {
records.push(capabilityRecord(match[1].replace(/^"|"$/g, ""), "mcp", codexConfigPath));
}
for (const match of config.matchAll(/^\[plugins\."([^"]+)"\]/gm)) {
const pluginId = match[1].split("@")[0];
records.push(capabilityRecord(pluginId, "plugin", codexConfigPath));
}
} catch {
// Optional config.
}
try {
const data = JSON.parse(await fs.readFile(claudeMcpPath, "utf8"));
for (const id of Object.keys(data.mcpServers || {})) {
records.push(capabilityRecord(id, "mcp", claudeMcpPath));
}
} catch {
// Optional config.
}
return records;
}
async function workflowCapabilities() {
const specs = [
["capability-planning-gate", path.join(HOME, ".agents/registry/CAPABILITY-PLANNING.md")],
["cheap-skill-router", path.join(HOME, ".agents/registry/scripts/route-skills.mjs")],
["capability-system-graph", path.join(HOME, ".agents/registry/capability-system-graph/graphify-out/graph.json")],
];
const records = [];
for (const [id, file] of specs) {
if (await fs.access(file).then(() => true).catch(() => false)) {
records.push(capabilityRecord(id, "workflow", file));
}
}
return records;
}
const skillFiles = uniq((await Promise.all(roots.map((root) => walk(root)))).flat()).sort();
const records = [];
for (const file of skillFiles) {
let text;
try {
text = await fs.readFile(file, "utf8");
} catch {
continue;
}
const fm = parseFrontmatter(text);
const dir = path.dirname(file);
const id = path.basename(dir);
const record = {
id,
type: "skill",
name: fm.name || id,
description: fm.description || firstParagraph(text),
path: file,
root: roots.find((root) => file.startsWith(root)) || "",
model: fm.model || "",
cost_tier: fm.cost_tier || fm.weight || "",
allowed_tools: fm["allowed-tools"] || fm.allowed_tools || "",
headings: headings(text),
updated_at: new Date().toISOString(),
};
record.keywords = keywordsFor(record);
records.push(record);
}
for (const record of await configuredCapabilities()) {
records.push(record);
}
for (const record of await workflowCapabilities()) {
records.push(record);
}
const dedupedRecords = [];
const seenRecords = new Set();
for (const record of records) {
const key = `${record.type}:${record.id}:${record.path}`;
if (seenRecords.has(key)) continue;
seenRecords.add(key);
dedupedRecords.push(record);
}
records.length = 0;
records.push(...dedupedRecords);
await fs.mkdir(outDir, { recursive: true });
await fs.mkdir(legacyOutDir, { recursive: true }).catch(() => {});
const jsonPayload = JSON.stringify(
{
generated_at: new Date().toISOString(),
count: records.length,
skill_count: records.filter((record) => record.type === "skill").length,
mcp_count: records.filter((record) => record.type === "mcp").length,
plugin_count: records.filter((record) => record.type === "plugin").length,
roots,
records,
},
null,
2,
);
await fs.writeFile(outJson, jsonPayload);
await fs.writeFile(legacyOutJson, jsonPayload).catch(() => {});
const byRoot = new Map();
for (const record of records) {
byRoot.set(record.root, (byRoot.get(record.root) || 0) + 1);
}
const md = [
"# Cheap Skill Index",
"",
`Generated: ${new Date().toISOString()}`,
`Capabilities: ${records.length}`,
`Skills: ${records.filter((record) => record.type === "skill").length}`,
`MCP: ${records.filter((record) => record.type === "mcp").length}`,
`Plugins: ${records.filter((record) => record.type === "plugin").length}`,
"",
"## Roots",
...[...byRoot.entries()].map(([root, count]) => `- ${root}: ${count}`),
"",
"## Use",
"",
"Run:",
"",
"```bash",
`node ${HOME}/.agents/registry/scripts/route-skills.mjs "task text" --limit 7`,
"```",
"",
"Read full SKILL.md only for selected candidates.",
"",
].join("\n");
await fs.writeFile(outMd, md);
await fs.writeFile(legacyOutMd, md).catch(() => {});
console.log(`indexed ${records.length} capabilities`);
console.log(outJson);
@@ -0,0 +1,334 @@
#!/usr/bin/env python3
"""Reconcile installed capabilities -> registry.jsonl (canonical).
Sources: .claude/skills, .codex/skills, .claude/agents, .codex/agents, plugins,
.skill-lock.json (provenance), GITHUB-STARS-LEDGER.md (stars), overrides.jsonl (manual).
Usage counts start at 0 (counting begins now). Run: python3 build_registry.py
"""
import json, os, re, math
HOME = os.path.expanduser("~")
AG = f"{HOME}/.agents"
CLA = f"{HOME}/.claude"
COD = f"{HOME}/.codex"
REG = f"{AG}/registry"
OUT = f"{REG}/registry.jsonl"
STARS_CEIL_LOG = math.log10(200000) # ecc ~198k = normalization ceiling
# ---------- helpers ----------
def parse_frontmatter(path):
try:
txt = open(path, encoding="utf-8", errors="ignore").read(6000)
except Exception:
return None, ""
m = re.match(r"^---\s*\n(.*?)\n---", txt, re.S)
fm = m.group(1) if m else txt[:1500]
nm = re.search(r"^name:\s*(.+)$", fm, re.M)
name = nm.group(1).strip().strip("\"'") if nm else None
dm = re.search(r"^description:\s*(.*)$", fm, re.M)
desc = ""
if dm:
first = dm.group(1).strip()
if first in ("|", ">", "|-", ">-", "|+", ">+"):
for ln in fm[dm.end():].splitlines():
if re.match(r"^\s+\S", ln):
desc += " " + ln.strip()
elif ln.strip() == "":
continue
else:
break
desc = desc.strip()
else:
desc = first.strip("\"'")
return name, re.sub(r"\s+", " ", desc)[:300]
def list_dirs(p):
return set(os.listdir(p)) if os.path.isdir(p) else set()
# ---------- load provenance ----------
lock = {}
try:
lock = json.load(open(f"{AG}/.skill-lock.json")).get("skills", {})
except Exception:
pass
def norm_repo(u):
return re.sub(r"\.git$", "", (u or "").strip().rstrip("/"))
# stars by repo from ledger
stars_by_repo = {}
ledger_path = f"{AG}/GITHUB-STARS-LEDGER.md"
if os.path.exists(ledger_path):
for line in open(ledger_path, encoding="utf-8"):
c = [x.strip() for x in line.split("|")]
if len(c) > 6 and c[2].startswith("http"):
try:
stars_by_repo[norm_repo(c[2])] = int(c[4])
except Exception:
pass
# ---------- stars-cache overlay (from gh sync_stars.py; fresher than ledger) ----------
star_cache = {}
_cp = f"{REG}/stars-cache.json"
if os.path.exists(_cp):
try:
star_cache = json.load(open(_cp))
except Exception:
pass
def cache_get(url):
m = re.search(r"github\.com/([^/]+/[^/]+)", url or "")
return star_cache.get(m.group(1).replace(".git", "")) if m else None
# ---------- usage from log (single source of truth) ----------
from datetime import datetime, timezone, timedelta
usage_count_map, usage30_map, last_map = {}, {}, {}
logp = f"{REG}/usage.log"
if os.path.exists(logp):
now = datetime.now(timezone.utc)
cut = now - timedelta(days=30)
for line in open(logp, encoding="utf-8"):
p = line.rstrip("\n").split("\t")
if len(p) < 3:
continue
ts, sid = p[0], p[2]
usage_count_map[sid] = usage_count_map.get(sid, 0) + 1
try:
t = datetime.fromisoformat(ts.replace("Z", "+00:00"))
if t >= cut:
usage30_map[sid] = usage30_map.get(sid, 0) + 1
if sid not in last_map or ts > last_map[sid]:
last_map[sid] = ts
except Exception:
pass
MAXUSE = max(usage_count_map.values()) if usage_count_map else 1
# ---------- manual overrides ----------
overrides = {}
ovp = f"{REG}/overrides.jsonl"
if os.path.exists(ovp):
for line in open(ovp, encoding="utf-8"):
line = line.strip()
if line:
o = json.loads(line)
overrides[o["id"]] = o
# ---------- domain heuristic ----------
# ordered (specific first); first match wins, plus always-eligible 'any'
# Ordered specific->general; first 2 matches win. id-based. Tuned to misc=0, max domain ~200.
DOMAIN_RULES = [
("gsd", r"^gsd-"),
("redteam", r"(exploit-|pentest|red-team|evilginx|metasploit|impacket|covenant|pass-the-hash|pass-the-ticket|lateral-movement-with-wmi|kerberoasting-with|nopac|zerologon|ms17-010|eternal-|initial-access-with|hash-cracking|wifi-password-crack|phishing-simulation|spearphishing-simulation|social-engineering-pentest|social-engineering-pretext|building-c2-|building-red-team|building-attack-pattern|executing-red-team|conducting-full-scope|conducting-man-in-the-middle|conducting-pass-the|conducting-social-engineering|performing-red-team|performing-purple-team|performing-physical-intrusion|performing-wireless-network-pentest|performing-wireless-security-assess|performing-bluetooth-security|performing-wifi|performing-lateral-movement-with-wmiexec|bypassing-authentication|intercepting-mobile|executing-phishing|performing-adversary-in-the-middle|performing-credential-access-with-lazagne|analyzing-heap-spray|performing-bandwidth-throttling|performing-arp-spoof|performing-packet-inject|performing-vlan-hop|performing-privilege-escal|conducting-mobile-app-penetration|performing-thick-client|performing-binary-exploit|exploiting-api-injection|exploiting-bgp-hijack|exploiting-constrained|exploiting-deeplink|exploiting-ipv6|exploiting-server-side-request|exploiting-template-inject|exploiting-websocket-vuln|building-adversary-infra)"),
("detection", r"(detecting-|hunting-for-|triaging-security|correlating-security|analyzing-security-logs|building-detection|building-soc|building-cloud-siem|implementing-alert-fatigue|implementing-siem|implementing-soar|implementing-endpoint-detection|performing-alert-triage|performing-threat-hunting|performing-lateral-movement-detection|performing-user-behavior-analytics|performing-false-positive-reduction|performing-log-source-onboarding|analyzing-api-gateway-access-logs|analyzing-azure-activity-logs|analyzing-cloud-storage-access|analyzing-command-and-control|analyzing-dns-logs|analyzing-email-headers|analyzing-kubernetes-audit|analyzing-linux-audit-logs|analyzing-network-traffic-for|analyzing-network-flow|analyzing-network-covert|analyzing-office365-audit|analyzing-persistence-mechanisms|analyzing-powershell-script|analyzing-web-server-logs|hunting-advanced-persistent|hunting-credential-stuffing|performing-dns-tunneling-detect|investigating-insider-threat|investigating-phishing-email|building-incident-response|performing-soc-tabletop|implementing-deception-based-detect|performing-deception-technology|deploying-active-directory-honeytokens|performing-yara-rule|implementing-honeytokens|analyzing-powershell-empire|analyzing-cyber-kill|configuring-host-based-intrusion|configuring-windows-defender|implementing-file-integrity|implementing-log-integrity|implementing-security-monitoring-with-datadog|implementing-syslog|performing-insider-threat|performing-network-traffic-analysis|performing-network-packet-capture|correlating-threat-campaigns|implementing-security-chaos|implementing-llm-guardrails)"),
("forensics", r"(forensic|volatility|autopsy|memory-dump|disk-image|timeline|file-carv|rekall|hindsight|plaso|cellebrite|prefetch|shellbag|lnk-file|amcache|windows-event-log|outlook-pst|browser-history|sqlite-forensic|extracting-browser|extracting-credentials|extracting-memory|extracting-ioc|extracting-windows|extracting-config|recovering-deleted|analyzing-mft|acquiring-disk|conducting-memory-forensics|performing-disk-forensic|performing-endpoint-forensic|performing-linux-log-forensic|performing-log-analysis-for-forensic|performing-mobile-device-forensic|performing-network-forensic|performing-timeline|performing-windows-artifact|collecting-volatile-evidence|analyzing-usb-device|performing-steganography|analyzing-windows-registry-for-artifacts|performing-firmware-extraction)"),
("malware", r"(malware|ransomware|rootkit|bootkit|trojan|deobfuscat|reverse-engineer|analyzing-cobalt|analyzing-cobaltstrike|analyzing-golang-malware|analyzing-linux-elf|analyzing-linux-kernel-rootkit|analyzing-macro-malware|analyzing-malicious-pdf|analyzing-malicious-url|analyzing-malware|analyzing-packed-malware|analyzing-pdf-malware|analyzing-android-malware|analyzing-ios-app-security-with-objection|performing-static-malware|performing-dynamic-analysis-with|performing-firmware-malware|eradicating-malware|recovering-from-ransomware|implementing-ransomware-|deploying-decoy|analyzing-ethereum-smart-contract|defi-amm-security|analyzing-sbom|performing-supply-chain-attack-simul|building-automated-malware|automating-ioc-enrichment|performing-ioc-enrichment|analyzing-network-traffic-of-malware|analyzing-malware-network|analyzing-ransomware|building-phishing-reporting|implementing-anti-phishing|implementing-mimecast|implementing-email-sandboxing|implementing-proofpoint|performing-dmarc-policy|implementing-dmarc)"),
("iam", r"(active-directory|bloodhound|dcsync|golden-ticket|kerberoast|privilege-escal|access-control|rbac|saml-sso|sso-with-okta|okta|sailpoint|cyberark|pam-for|ldap|zero-standing|just-in-time|identity-governance|identity-federation|identity-aware-proxy|access-recertif|access-review|entitlement-review|service-account-audit|privileged-account|configuring-multi-factor|managing-cloud-identity|implementing-saml|implementing-scim|implementing-conditional-access|implementing-just-in-time|implementing-identity-governance|implementing-passwordless|implementing-hardware-security-key|implementing-zero-standing|implementing-privileged-access|implementing-azure-ad-privileged|conducting-domain-persistence|conducting-internal-reconnais|auditing-gcp-iam|securing-aws-iam|building-identity|implementing-beyondcorp|deploying-cloudflare-access|deploying-software-defined-perimeter|deploying-tailscale|configuring-aws-verified-access|configuring-identity-aware-proxy|configuring-zscaler|implementing-cisa-zero-trust|implementing-browser-isolation|implementing-device-posture|implementing-identity-verification|implementing-zero-trust|auditing-azure-active-directory|performing-access-recertif|performing-access-review|performing-entitlement|performing-service-account|performing-active-directory|configuring-active-directory|performing-privileged-account|implementing-delinea|implementing-mtls|configuring-oauth2|performing-oauth-scope|implementing-privileged-session|implementing-google-workspace-sso|implementing-google-workspace-admin|implementing-google-workspace-phishing)"),
("cloud-sec", r"(aws-security|azure-security|gcp-security|aws-guardduty|azure-defender|aws-macie|aws-security-hub|cloud-incident|cloud-forensic|cloud-penetration|cloud-native-threat|performing-cloud-|performing-aws-account|performing-gcp-|performing-aws-privilege|implementing-aws-config|implementing-aws-iam-permission|implementing-aws-nitro|implementing-azure-defender|implementing-cloud-security|implementing-cloud-trail|implementing-cloud-waf|implementing-cloud-workload|implementing-gcp-binary|implementing-gcp-organization|implementing-gcp-vpc|implementing-cloud-dlp|implementing-cloud-vulnerability|detecting-aws|detecting-azure|detecting-cloud|detecting-compromised-cloud|detecting-misconfigured-azure|detecting-cryptomining-in-cloud|detecting-s3-|auditing-aws-s3|remediating-s3|securing-azure|conducting-cloud-incident|conducting-cloud-penetration|securing-aws-lambda|deploying-edr|deploying-osquery|implementing-aws-macie|building-cloud-siem|analyzing-azure-activity|analyzing-cloud-storage|implementing-attack-surface-management|implementing-attack-path|performing-cloud-asset|securing-serverless|securing-github-actions|implementing-infrastructure-as-code-security|building-devsecops-pipeline)"),
("compliance", r"(compliance|iso-27001|pci-dss|hipaa|gdpr|nerc-cip|nist-csf|soc2|cis-benchmark|iec-62443|performing-nist-csf|performing-privacy-impact|healthcare-phi|implementing-iso|implementing-pci|implementing-gdpr|implementing-nerc|performing-oil-gas-cybersecurity|performing-power-grid-cybersecurity|prioritizing-vulnerabilities|implementing-epss|implementing-rapid7|implementing-vulnerability-management|implementing-vulnerability-remediation|implementing-vulnerability-sla|building-vulnerability|triaging-vulnerabilities|implementing-patch-management|performing-cve-prioritization|performing-asset-criticality|scanning-infrastructure-with-nessus|performing-endpoint-vulnerability|implementing-continuous-security-validation|implementing-application-whitelisting|implementing-usb-device|implementing-endpoint-dlp|performing-agentless-vulnerability|performing-authenticated-scan|performing-authenticated-vulnerability|performing-vulnerability-scanning)"),
("osint", r"(osint|open-source-intelligence|spiderfoot|certificate-transparen|brand-monit|dark-web|paste-site|threat-intelligence|threat-actor|threat-feed|threat-hunt-hypothesis|threat-landscape|threat-emul|mitre-attack|mitre-navigator|diamond-model|stix|taxii|analyzing-apt|analyzing-campaign|analyzing-threat-actor|profiling-threat|building-threat|building-ioc|collecting-indicators|collecting-open-source|collecting-threat|managing-intelligence|processing-stix|performing-osint|performing-ip-reputation|performing-dark-web|performing-indicator|monitoring-darkweb|tracking-threat|correlating-threat-campaigns|performing-brand-monitor|performing-open-source-intelligence|performing-ai-driven-osint|performing-paste-site|analyzing-typosquatting|implementing-security-information-sharing|implementing-stix-taxii|implementing-taxii|implementing-threat-intelligence|building-threat-feed|building-threat-actor|building-threat-intelligence|analyzing-indicators-of-compromise|performing-malware-ioc|performing-malware-hash|performing-subdomain-enumeration|performing-dns-enumeration)"),
("appsec", r"(owasp|xss|csrf|ssrf|graphql-sec|websocket-sec|second-order-sql|sql-injection|api-fuzzing|api-inventory|api-rate-limiting-bypass|api-security-testing|api-security-posture|api-abuse-detection|api-schema-valid|api-threat-protect|api-enum|broken-access|broken-function|broken-object|broken-link|mass-assign|idor|deseri|prototype-poll|race-condition|type-juggling|clickjacking|cors-misc|host-header|content-security-policy-bypass|http-request-smuggl|open-redirect|xml-inject|jwt-none|jwt-algorithm|oauth-misc|implementing-api-gateway-security|implementing-api-key-security|implementing-api-rate-lim|implementing-api-schema|implementing-api-security|securing-api-gateway|performing-api-fuzzing|performing-api-inventory|performing-api-rate-limiting-bypass|performing-graphql|performing-content-security-policy|performing-http-param|implementing-runtime-application-self|implementing-web-application|implementing-semgrep|implementing-github-advanced-security|integrating-dast|integrating-sast|performing-sca-dependency|web-application-firewall|web-application-penetration|web-application-logging|web-application-vuln|web-application-scanning|web-application-security|performing-security-headers|performing-ssl-strip|testing-api-authentication|testing-for-broken|testing-for-business-logic|testing-for-json-web-token|testing-jwt|testing-mobile-api|testing-websocket|testing-oauth2|testing-cors|testing-for-host-header|testing-for-open-redirect|testing-for-xml|testing-for-xss|testing-for-xxe|testing-for-sensitive|testing-for-email|performing-soap-web|performing-directory-traversal|performing-second-order-sql|performing-ssrf|performing-blind-ssrf|performing-jwt-|performing-web-cache|performing-graphql-depth|performing-graphql-introspection|performing-serverless-function-security|implementing-fuzz-testing-in-cicd|performing-fuzzing-with|django-security|laravel-security|quarkus-security|perl-security|springboot-security|security-review$|security-reviewer|security-scan$|security-bounty|implementing-devsecops-security|implementing-secrets-management|implementing-secret-scanning|performing-mobile-app-certificate|implementing-jwt-sign)"),
("crypto", r"(encrypt|aes-encrypt|rsa-key|ed25519|digital-signature|zero-knowledge|certificate-authority|configuring-tls|tls-1-3|tls-certificate|ssl-certificate|ssl-tls-security|implementing-aes|implementing-rsa|implementing-digital|implementing-envelope|implementing-end-to-end|implementing-hardware-security-module|performing-cryptographic|performing-hash-cracking|performing-ssl-certificate|performing-post-quantum|configuring-certificate|implementing-code-signing|implementing-sigstore|implementing-supply-chain-security-with-in-toto|implementing-image-provenance|nodejs-keccak256|evm-token-decimals|configuring-hsm|implementing-hashicorp-vault|performing-hardware-security-module|performing-ssl-tls-inspect)"),
("network-sec", r"(firewall|ddos-mitigation|bgp-security|implementing-bgp|implementing-ddos|implementing-network-intrusion|implementing-network-access-control|implementing-next-generation-firewall|network-deception|implementing-network-traffic|implementing-network-segmentation|configuring-pfsense|configuring-snort|configuring-suricata|configuring-microsegmentation|implementing-microsegmentation|scanning-network-with-nmap|network-penetration-test|detecting-ntlm-relay|detecting-arp-poison|detecting-port-scanning|implementing-canary-token|implementing-network-deception|homelab-network|network-bgp-diagnostics|network-config-validation|network-interface-health|performing-external-network|conducting-network-pentest|conducting-internal-network|conducting-wireless-network|configuring-network-segmentation-with-vlans|analyzing-network-packets|analyzing-network-traffic-with-wireshark|analyzing-network-flow-data|analyzing-network-covert|implementing-network-policies-for-kubernetes|implementing-policy-as-code|network-architect|network-troubleshooter|network-config-reviewer)"),
("ot-ics", r"(scada|modbus|ot-|ics-|plc-|s7comm|dnp3|historian|conduit-security|dragos|claroty|nozomi|purdue-model|monitoring-scada|performing-s7comm|performing-scada|performing-ics|implementing-conduit|implementing-dragos|implementing-nerc-cip|implementing-patch-management-for-ot|securing-historian|securing-remote-access-to-ot|detecting-anomalies-in-industrial|detecting-attacks-on-historian|detecting-attacks-on-scada|detecting-dnp3|detecting-modbus|detecting-stuxnet|implementing-iec-62443)"),
("incident-response", r"(incident-response|ir-playbook|containing-active|eradicating-malware|recovering-from-ransomware|performing-ransomware-response|performing-ransomware-tabletop|conducting-post-incident|triaging-security-incident|building-ransomware-playbook|implementing-ticketing-system-for-incident|implementing-ot-incident|implementing-velociraptor|implementing-immutable-backup|validating-backup-integrity|implementing-ransomware-backup|testing-ransomware-recovery|building-patch-tuesday|conducting-malware-incident|investigating-ransomware|implementing-log-forwarding)"),
("container-sec", r"(container-escape|container-drift|container-image-hardening|scanning-container|scanning-docker|scanning-kubernetes|performing-container-escape|performing-container-image|performing-container-security|performing-docker-bench|performing-kubernetes-|implementing-aqua|implementing-container|implementing-pod|implementing-rbac-hardening|implementing-opa-gatekeeper|securing-container|securing-helm|securing-kubernetes|hardening-docker|deploying-crowdstrike|deploying-edr-agent|implementing-ebpf|detecting-container|implementing-kubernetes-network|implementing-kubernetes-pod|implementing-runtime-security-with-tetragon)"),
("3d", r"(threejs|three-|webgl|3d-|spatial|gltf|blender|typegpu|^three$)"),
("design", r"(design|ui-|ux-|brand|figma|visual|typograph|animation-designer|frontend-design|nothing-design|stitch|penpot|liquid-glass|shadcn|tailwind|framer-motion|css-animation|lottie|waapi|gsap|^animejs$|theme-factory|^prototype$|usability-tester|canvas-design|premium-frontend|web-design-review|design-html|design-md|a11y-architect)"),
("web", r"(frontend|web-design|react-|vue-|next-|accessibility|seo-|core-web|performance-opt|webapp-testing|browser-testing|playwright|chrome-devtools|lighthouse|web-quality|windows-desktop-e2e|vercel-|^seo$|^screenshot$|hyperframes|remotion|^website-builder-setup$|website-to-hyperframes)"),
("video", r"(video|ffmpeg|moviepy|elevenlabs|voice|redub|manim|clip|ltx2|acestep|fal-ai-media|gpt-image-2|runpod|scene-review)"),
("finance", r"(dcf|lbo|comps|valuation|equity|bond|earnings|merger|portfolio|nav-|kyc|accrual|gl-|fsi-|3-statement|tax-loss|fx-carry|swap-curve|option-vol|catalyst-calendar|deal-|buyer-list|cim-|ic-memo|tear-sheet|ib-check|prediction-market|initiating-coverage|sector-overview|macro-rates|morning-note|funding-digest|ito-basket|ito-market|ito-trade|returns-analysis|returns-reverse|unit-economics|value-creation|variance-commentary|financial-plan|finance-billing|customer-billing|inventory-demand|carrier-relationship|logistics-exception|energy-procurement|production-scheduling|quality-nonconformance)"),
("research", r"(firecrawl|exa-|deep-research|scientific-|pubmed|market-research|competitive-anal|scientific-pkg|scientific-thinking|article-writing|iterative-retrieval|search-first|^scrape$|^browse$|fact-checker|lead-intelligence|landing-report|content-engine)"),
("data", r"(data-|xls|clickhouse|postgres|mysql|prisma|jpa-|database|sql-pattern|clean-data|datapack|dashboard-builder|nav-tieout|roll-forward|regex-vs-llm)"),
("docs", r"(doc-|writing-|pptx|pdf|book|copywrit|humaniz|non-fiction|pptx-author|xlsx-|make-pdf|notebooklm|guizang-ppt|client-report|pitch-deck|deck-refresh|document-generate|document-release|edit-article|process-letter|teaser|to-issues|to-prd|^spec$|nutrient-document|ppt-template|ralphinho-rfc|^client-review$)"),
("mobile", r"(ios-|android|swift-|flutter|kotlin|harmonyos|arkts|watchos|tvos|ipados|visionos|macos-design|foundation-models-on-device|mobile-application-management)"),
("agentops", r"(agent-|skill-|^loop-|^loop$|orchestrat|harness|swarm|council|hook|memory|capability|mcp-builder|context-|continuous-learning|subagent|team-builder|autonomous|agentic|cost-tracking|token-budget|benchmark-model|caveman|sync-|instinct-|gsd-list|dispatching-parallel|claude-devfleet|^codex$|^gstack$|gstack-|kb-pipeline|pair-agent|parallel-execution|cost-aware-llm|^ai-first-engineering$|^ai-readiness$|^benchmark$|^skillify$|^skills$|write-a-skill|using-superpowers|^canary$|^guard$|^freeze$|^unfreeze$|^health$|^versions$|^contribute$|configure-ecc|^ecc$|ecc-tools|model-update|improve-codebase|^benchmark-models$|^kb$|^autoplan$|code-tour|\.md$|\.toml$|^qa-only$|^setup$|verification-loop|^hatch-pet$)"),
("devops", r"(build-|deploy-|docker-pattern|terraform|ci-cd|pm2|^setup-|migrat|github-ops|netmiko|land-and-deploy|git-guardrails|finishing-a-development|deployment-patterns|using-git-worktrees|validated-build|verification-before|systematic-debug|^diagnose$|^error-handling$|latency-critical|production-audit|^performance$|^ship$|^review$|^triage$|^investigate$|^retro$|executing-plans|requesting-code-review|receiving-code-review|request-refactor-plan|^record-demo$|plankton-code-quality|api-connector-builder|^template$|terminal-ops|^learn$|content-hash-cache|^break-trace$|^connect-chrome$|^connections-optimizer$|^cso$|^office-hours$|^workspace-surface-audit$|^ax-audit$|^automation-audit-ops$|^devex-review$|thesis-tracker|recursive-decision-ledger|scaffold-exercises|^plan-ceo|^plan-devex|^plan-eng|^plan-tune$|^dd-checklist$|^dd-meeting-prep$|project-flow|project-builder|research-ops|^strategic-compact$)"),
("testing", r"(test-|tdd|e2e-|webapp-testing|regression|eval-|playwright-generate|playwright-explore|playwright-recording|browser-testing|benchmark-optim|^qa$)"),
("comms", r"(email-ops|messages-ops|slack|notification|chief-of-staff|crosspost|x-api|google-workspace-ops|knowledge-ops|obsidian-vault|social-graph|lead-intelligence|investor-outreach|investor-materials|investment-proposal|^handoff$|grill-me|grill-with-docs|^idea-generation$|brainstorming|best-practices|^impeccable$|cheat-on-content|prompt-master|prompt-optimizer|enhance-prompt|qwen-edit|quill-context|^careful$|asset-manager|jira-integration|^blueprint$|marketing-agent)"),
]
def domains_for(sid, desc):
hay = sid.lower() # id only — ids here are highly descriptive; desc adds verb noise
hits = [d for d, pat in DOMAIN_RULES if re.search(pat, hay)]
return hits[:2] if hits else ["misc"]
def stars_norm(s):
return (math.log10(s + 1) / STARS_CEIL_LOG) if s else 0.0
def effectiveness(stars, rating, parity_warn, usage_norm=0.0,
success_rate=None, runs=0, archived=False, fresh=0.7):
"""Effectiveness score 0-100 — QUALITY-led, not popularity.
Goal: best product outcome per token. quality(rating) dominates; stars demoted
to weak proof. proven uses real success-rate once runs accrue, else stars proxy.
Token-efficiency + project-fit + right-sizing are applied at SELECTION time
(see REGISTRY.md Selection Policy), not bakeable into a context-free number."""
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))
if parity_warn:
val -= 10
if archived:
val -= 30
return max(0, val)
COST_HEAVY = re.compile(
r"(deep-research|full-scope|end-to-end|comprehensive|engagement|pipeline|playbook|"
r"tabletop|workstream|multi-file|swarm|orchestrat|harness|autonomous|dispatching-parallel|"
r"council|board|spawn|subagent|multi-agent|conducting-full|executing-red-team|"
r"performing-purple-team|building-soc|building-incident|building-threat-intelligence|"
r"implementing-zero-trust|performing-cloud-penetration|firecrawl-agent|firecrawl-crawl|"
r"firecrawl-deep|3-statement|lbo-model|dcf-model|merger-model|non-fiction-book|"
r"manim-video|remotion-video|gsd-ultraplan|gsd-workstream|gsd-autonomous|agent-harness|agent-sort)")
COST_LIGHT = re.compile(
r"(lint|format|prettier|eslint|stylelint|tsc-check|^versions$|^health$|^freeze$|^unfreeze$|"
r"^canary$|^guard$|caveman|token-budget|cost-report|cost-tracking|fact-checker|best-practices|"
r"code-simplifier|refactor-cleaner|code-tour|screenshot|^scrape$|^browse$|search-first|"
r"lookup|quick|single|guideline|checklist|^template$|^spec$|^learn$|regex-vs-llm|"
r"nodejs-keccak256|evm-token-decimals|gsd-note|gsd-quick|gsd-stats|gsd-progress|gsd-next|"
r"^retro$|^handoff$|^ship$)")
def cost_tier(sid, typ, purpose):
"""Token/effort footprint of RUNNING the skill (for right-sizing)."""
hay = (sid + " " + (purpose or "")).lower()
if COST_HEAVY.search(hay):
return "heavy"
if COST_LIGHT.search(hay):
return "light"
return "medium"
def freshness(pushed, archived):
"""0-1 maintenance signal from upstream push date (sync_stars). Unknown -> 0.7."""
if archived:
return 0.0
if not pushed:
return 0.7
try:
days = (datetime.now(timezone.utc) - datetime.fromisoformat(pushed.replace("Z", "+00:00"))).days
except Exception:
return 0.7
return 1.0 if days < 180 else 0.7 if days < 365 else 0.4 if days < 730 else 0.2
# ---------- enumerate ----------
claude_skills = list_dirs(f"{CLA}/skills")
codex_skills = list_dirs(f"{COD}/skills")
claude_agents = list_dirs(f"{CLA}/agents")
codex_agents = list_dirs(f"{COD}/agents")
records = []
def build(sid, kind, base_claude, base_codex, in_claude, in_codex):
lk = lock.get(sid, {})
repo = norm_repo(lk.get("sourceUrl")) if lk.get("sourceUrl") else None
stars = stars_by_repo.get(repo) if repo else None
cd = cache_get(lk.get("sourceUrl") or "")
pushed = checked = None
archived = False
if cd:
if cd.get("stars") is not None:
stars = cd["stars"]
pushed, checked, archived = cd.get("pushed"), cd.get("checked_at"), cd.get("archived", False)
# description from claude copy preferred
path = None
if kind == "skill":
p1 = f"{CLA}/skills/{sid}/SKILL.md"
p2 = f"{COD}/skills/{sid}/SKILL.md"
path = p1 if os.path.exists(p1) else (p2 if os.path.exists(p2) else None)
else:
p1 = f"{CLA}/agents/{sid}"
p2 = f"{COD}/agents/{sid}"
path = p1 if os.path.exists(p1) else (p2 if os.path.exists(p2) else None)
_, desc = parse_frontmatter(path) if path else (None, "")
ov = overrides.get(sid, {})
parity_warn = not (in_claude and in_codex)
rating = ov.get("rating")
doms = ov.get("domains") or domains_for(sid, desc)
uc = usage_count_map.get(sid, 0)
un = uc / MAXUSE
rec = {
"id": sid,
"type": ov.get("type", kind),
"purpose": ov.get("purpose") or (desc[:120] if desc else ""),
"use_when": ov.get("use_when") or desc[:160],
"domains": doms,
"projects": ov.get("projects", ["any"]),
"model": ov.get("model", "S"),
"harness": {"claude": "installed" if in_claude else "missing",
"codex": "installed" if in_codex else "missing"},
"parity": "synced" if in_claude and in_codex else ("claude-only" if in_claude else "codex-only"),
"source": lk.get("source"),
"repo_url": (f"https://github.com/{lk['source']}" if lk.get("source") else None),
"local_path": lk.get("skillPath"),
"installed_at": (lk.get("installedAt") or "")[:10] or None,
"updated_at_local": (lk.get("updatedAt") or "")[:10] or None,
"stars": stars,
"repo_pushed_at": pushed,
"stars_checked_at": checked,
"usage_count": uc,
"usage_30d": usage30_map.get(sid, 0),
"last_used_at": last_map.get(sid),
"success_runs": 0,
"rating": rating,
"status": "stale" if archived else "active",
"health": "unknown",
"cost_tier": cost_tier(sid, ov.get("type", kind), ov.get("purpose") or desc),
"score": effectiveness(stars, rating, parity_warn, un, None, uc, archived,
freshness(pushed, archived)),
}
records.append(rec)
for sid in sorted(claude_skills | codex_skills):
if sid.startswith("."):
continue
build(sid, "skill", claude_skills, codex_skills, sid in claude_skills, sid in codex_skills)
for sid in sorted(claude_agents | codex_agents):
if sid.startswith("."):
continue
build(sid, "agent", claude_agents, codex_agents, sid in claude_agents, sid in codex_agents)
# plugin caveman: installed on Claude as plugin (active). Upsert -> claude installed.
if os.path.isdir(f"{CLA}/plugins/cache/caveman"):
cav = next((r for r in records if r["id"] == "caveman"), None)
codex_has = "caveman" in codex_skills or os.path.isdir(f"{COD}/skills/caveman")
cav_un = usage_count_map.get("caveman", 0) / MAXUSE
if cav:
cav["type"] = "plugin"
cav["harness"] = {"claude": "installed", "codex": "installed" if codex_has else "partial"}
cav["parity"] = "synced" if codex_has else "claude-primary"
cav["cost_tier"] = "light"
cav["score"] = effectiveness(cav.get("stars"), cav.get("rating"), not codex_has, cav_un)
else:
ov = overrides.get("caveman", {})
records.append({
"id": "caveman", "type": "plugin",
"purpose": ov.get("purpose", "Terse inter-agent/user comms, token save"),
"use_when": ov.get("use_when", "be brief, caveman mode, less tokens"),
"domains": ov.get("domains", ["comms"]), "projects": ["any"],
"model": ov.get("model", "H"),
"harness": {"claude": "installed", "codex": "installed" if codex_has else "partial"},
"parity": "synced" if codex_has else "claude-primary",
"source": "plugin-marketplace", "repo_url": None, "local_path": None,
"installed_at": None, "updated_at_local": None,
"stars": None, "repo_pushed_at": None, "stars_checked_at": None,
"usage_count": usage_count_map.get("caveman", 0),
"usage_30d": usage30_map.get("caveman", 0),
"last_used_at": last_map.get("caveman"), "success_runs": 0,
"rating": ov.get("rating", 5), "status": "active", "health": "ok",
"cost_tier": "light",
"score": effectiveness(None, ov.get("rating", 5), not codex_has, cav_un),
})
# ---------- write ----------
with open(OUT, "w", encoding="utf-8") as f:
for r in sorted(records, key=lambda x: (-x["score"], x["id"])):
f.write(json.dumps(r, ensure_ascii=False) + "\n")
# ---------- report ----------
from collections import Counter
dc = Counter(d for r in records for d in r["domains"])
tc = Counter(r["type"] for r in records)
withstars = sum(1 for r in records if r["stars"])
print(f"records: {len(records)} types: {dict(tc)}")
print(f"with stars: {withstars} with usage: 0 (reset)")
print("top domains:", dict(dc.most_common(12)))
print("sample top-5 by score:")
for r in sorted(records, key=lambda x: -x["score"])[:5]:
print(f" {r['score']:>3} {r['id']:32} ★{r['stars']} dom={r['domains']}")
@@ -0,0 +1,284 @@
#!/usr/bin/env python3
"""registry.jsonl -> INDEX.md + domains/<dom>.md shards + both REGISTRY.md (Tier-1).
Run after build_registry.py. Usage columns reflect registry (0 now)."""
import json, os
from collections import defaultdict
HOME = os.path.expanduser("~")
REG = f"{HOME}/.agents/registry"
DOMDIR = f"{REG}/domains"
CLA_OUT = f"{HOME}/.claude/capabilities/REGISTRY.md"
COD_OUT = f"{HOME}/.codex/capabilities/REGISTRY.md"
recs = [json.loads(l) for l in open(f"{REG}/registry.jsonl", encoding="utf-8") if l.strip()]
by_id = {r["id"]: r for r in recs}
PINNED = ["frontend-design","performance-optimization","accessibility","nothing-design",
"threejs-animation","caveman","firecrawl-search","deep-research",
"agent-capability-installer","dcf-model"]
def star(s):
if not s: return "—"
return f"{s/1000:.1f}k" if s >= 1000 else str(s)
def parity(r):
m = {"installed":"✅","partial":"⚠","missing":"❌"}
h = r.get("harness", {})
return f'{m.get(h.get("claude"),"❓")}·{m.get(h.get("codex"),"❓")}'
# ---------- domain index ----------
dom = defaultdict(list)
for r in recs:
for d in r["domains"]:
dom[d].append(r)
dom_sorted = sorted(dom.items(), key=lambda kv: -len(kv[1]))
def domain_map_md():
out = ["| domain | n | top by score | shard |", "|---|--:|---|---|"]
for d, rs in dom_sorted:
top = sorted(rs, key=lambda x: -x["score"])[:3]
tops = " · ".join(f"{t['id']}({t['score']})" for t in top)
out.append(f"| {d} | {len(rs)} | {tops} | `domains/{d}.md` |")
return "\n".join(out)
# ---------- shards ----------
os.makedirs(DOMDIR, exist_ok=True)
for d, rs in dom.items():
rows = ["# domain: " + d + f" ({len(rs)} capabilities)",
"", "> Tier-2 shard. Canonical: `../registry.jsonl`. Sorted by score.", "",
"| id | type | purpose | model | wt | ★ | score | parity | ⟳C | ⟳X |",
"|---|---|---|:--:|:--:|--:|--:|:--:|--:|--:|"]
for r in sorted(rs, key=lambda x: (-x["score"], x["id"])):
pur = (r["purpose"] or "").replace("|", "/")[:80]
rows.append(f'| {r["id"]} | {r["type"]} | {pur} | {r.get("model","S")} | '
f'{r.get("cost_tier","medium")[0].upper()} | '
f'{star(r["stars"])} | {r["score"]} | {parity(r)} | '
f'{r["usage_count"]} | {r["usage_count"]} |')
open(f"{DOMDIR}/{d}.md", "w", encoding="utf-8").write("\n".join(rows) + "\n")
# ---------- INDEX.md ----------
total = len(recs)
idx = f"""# Capability Index — domain map (Tier-1)
> Canonical DB: `registry.jsonl` ({total} capabilities). Per-domain detail: `domains/<dom>.md`.
> Selection: match task → domain here → open that shard → trigger/disambiguation → top score.
## Domains
{domain_map_md()}
## How to pick
1. Map task to domain(s) above.
2. Open `domains/<dom>.md` (Tier-2) — full list sorted by score.
3. Cross-cutting overlap? See REGISTRY.md §Disambiguation.
4. Open SKILL.md only for the 1-2 finalists (Tier-3).
"""
open(f"{REG}/INDEX.md", "w", encoding="utf-8").write(idx)
# ---------- shared static sections ----------
DISAMBIG = """## Disambiguation (overlap → pick this, not that) [SHARED]
#1 selection error = wrong one of N similar. Resolve here first.
| task signal | PICK | NOT | why |
|---|---|---|---|
| find page/fact, pull content, one-shot | `firecrawl-search` | deep-research | search ≠ multi-source synthesis |
| investigate topic, compare options, cited report | `deep-research` | firecrawl-search | needs cross-source synth (firecrawl-search = sub-fetch) |
| build any distinctive UI | `frontend-design` | nothing-design | nothing-design = ONE brand aesthetic |
| explicitly want Nothing look (mono/industrial) | `nothing-design` | frontend-design | brand-specific override |
| page slow / CWV / bundle | `performance-optimization` | accessibility | perf axis ≠ a11y axis |
| keyboard/contrast/WCAG | `accessibility` | performance-optimization | different axis — often run BOTH |
| 3d motion in scene | `threejs-animation` | frontend-design | DOM build ≠ WebGL anim |
**skip-when:** `nothing-design` unless Nothing brand asked. `deep-research` for single-fact lookup (opus overkill)."""
CHAINS = """## Chains (pairs-with → pipeline) [SHARED]
```
build web surface : frontend-design → accessibility → performance-optimization
research → deliver : deep-research → firecrawl-search (gap-fill) → frontend-design
3d landing : frontend-design + threejs-animation
any task (style) : caveman wraps comms layer, orthogonal
```"""
TRIGGERS = """## Trigger index (keyword → skill) [SHARED]
| keyword / phrase | → skill |
|---|---|
| search web · scrape · fetch page · crawl | firecrawl-search |
| deep research · investigate · compare options | deep-research |
| a11y · WCAG · contrast · screen reader | accessibility |
| CWV · LCP · slow · bundle size | performance-optimization |
| build UI · component · landing · page | frontend-design |
| Nothing · monochrome · industrial | nothing-design |
| 3d · GLTF · animate mesh · scene | threejs-animation |
| DCF · valuation · intrinsic value | dcf-model |
| install skill · mirror codex · catalog | agent-capability-installer |
| be brief · save tokens · caveman | caveman |"""
POLICY = """## 0 · Selection Policy — effectiveness per token for THIS project [SHARED]
Goal: the **best product outcome per token**, not the cheapest pick. Choose what makes the product amazing — but right-sized, never more than the task actually needs.
**Decision (apply per candidate at selection time):**
```
value(skill | project, task) = eff × fit × right_size − switch_cost
pick = argmax value ; tie-break → lower cost_tier (more quality per token)
```
- **eff** = `score`/100 (quality-led effectiveness).
- **fit** ∈ 0..1 — project match: stack + domain + quality-bar alignment (read project CLAUDE.md/AGENTS.md). Wrong stack ≈ 0.2; exact stack+domain = 1.0.
- **right_size** — match skill `wt` (cost_tier) to task need:
| task need ↓ \\ skill wt → | L light | M medium | H heavy |
|---|:--:|:--:|:--:|
| trivial / one-shot | 1.0 | 0.6 | 0.2 ⟵ overkill |
| standard | 0.7 | 1.0 | 0.8 |
| product-critical / hero | 0.5 | 0.9 | 1.0 |
- **switch_cost** — small penalty for adding a new tool when an in-flight one already suffices.
**Token-efficiency clause:** equal `eff×fit` → take lower `wt` (more quality per token). UNequal → **quality wins**: a 2× token skill that yields a materially better product beats the cheap one. Never sacrifice the product to save tokens.
**Anti-overkill clause:** don't escalate past the task. Single fact → `firecrawl-search`, not `deep-research`. One component tweak → not a whole design-system skill. Lightest capability that still clears the quality bar.
**Model tier by effectiveness-per-token** (replaces "always minimal-sufficient"):
| work | model | why |
|---|:--:|---|
| product-critical surface · hard synthesis · architecture · final pass | **Opus** | quality dominates; tokens cheap vs a worse product |
| standard build / analysis / code | **Sonnet** | best quality-per-token for most work |
| bulk / mechanical: grep, classify, format, sort, leaf-workers | **Haiku** | quality saturates → throughput & tokens dominate |"""
def provenance_md():
out = ["## Provenance appendix (for UPDATE, not selection) [SHARED]", "",
"| id | source | repo | local upd | upstream push |", "|---|---|---|---|---|"]
for pid in PINNED:
r = by_id.get(pid, {})
repo = f'[link]({r["repo_url"]})' if r.get("repo_url") else "—"
out.append(f'| {pid} | {r.get("source") or "—"} | {repo} | '
f'{r.get("updated_at_local") or "—"} | — *(pending sync-stars)* |')
return "\n".join(out)
# ---------- pinned selection table ----------
def pinned_table(primary): # primary = 'C' or 'X'
cu = "**⟳C**" if primary == "C" else "*⟳C*"
xu = "*⟳X*" if primary == "C" else "**⟳X**"
head = (f"| id | type | purpose · *use-when* | dom | model | wt | ★ | score | ✓% | parity | {cu} | {xu} |\n"
"|---|---|---|---|:--:|:--:|--:|--:|:--:|:--:|--:|--:|")
rows = []
for pid in PINNED:
r = by_id.get(pid)
if not r: continue
cw = f'**{r["usage_count"]}**' if primary == "C" else f'*{r["usage_count"]}*'
xw = f'*{r["usage_count"]}*' if primary == "C" else f'**{r["usage_count"]}**'
rows.append(f'| {pid} | {r["type"]} | {r["purpose"]} · *{r["use_when"]}* | '
f'{"·".join(r["domains"])} | {r.get("model","S")} | {r.get("cost_tier","medium")[0].upper()} | '
f'{star(r["stars"])} | {r["score"]} | — | {parity(r)} | {cw} | {xw} |')
return head + "\n" + "\n".join(rows)
# ---------- assemble REGISTRY.md ----------
def registry_md(view): # view = 'CLAUDE' or 'CODEX'
me, sib = ("CLAUDE","Codex") if view=="CLAUDE" else ("CODEX","Claude")
sibpath = (COD_OUT if view=="CLAUDE" else CLA_OUT)
primary = "C" if view=="CLAUDE" else "X"
auth = ("`⟳ Claude` = source of truth. `⟳ Codex` = mirror." if view=="CLAUDE"
else "`⟳ Codex` = source of truth. `⟳ Claude` = mirror.")
if view=="CLAUDE":
split = (" ├─ Claude step → bump ⟳C HERE\n ├─ Codex step → bump ⟳X in SIBLING")
else:
split = (" ├─ Codex step → bump ⟳X HERE\n ├─ Claude step → bump ⟳C in SIBLING")
return f"""# Capability Registry — {me} view ⟢ you are here
> **Sibling ({sib}):** `{sibpath}`
> **Canonical DB:** `{REG}/registry.jsonl` ({total} capabilities) · **Domain map:** `{REG}/INDEX.md`
Selection order: **trigger-index → disambiguation → domain shard score**. This file = Tier-1 (pinned + maps); full lists in `domains/<dom>.md`.
---
## Interdependence rules (why two files)
1. **Install = shared** (one `.agents/.skill-lock.json` + mirrored skill dirs) → `parity C·X` identical both files.
2. **Usage = local.** Each harness counts own `⟳`. Edit **bold** column here; *italic* = mirror (edit in sibling).
3. **Split work → touch both.** Each harness logs its run in ITS OWN `⟳`. Shared field change (★/repo/purpose/parity/score/new skill) → SAME row to BOTH files, one commit.
4. **Parity guard.** `⚠`/`❌` on YOUR harness → install or route step to sibling.
**Authority here:** {auth}
---
## Legend
- **type** — skill · plugin · mcp · agent · command · rule · bundle
- **model** — tier by effectiveness-per-token: `O` opus (product-critical / hard synth) · `S` sonnet (standard build/analysis) · `H` haiku (bulk/mechanical). See Selection Policy.
- **wt** — cost_tier (run footprint): `L` light · `M` medium · `H` heavy → drives right-sizing
- **score** — EFFECTIVENESS 0-100, quality-led: `0.42·rating + 0.25·proven + 0.18·stars + 0.10·usage + 0.05·fresh` − penalty(parity⚠ −10, archived −30). NOT popularity. Final pick = score × project-fit × right-size (Selection Policy). Sort desc WITHIN domain.
- **★** stars = weak community-proof only · **✓%** success rate (n runs), empty until usage accrues
- **parity C·X** — ✅installed · ⚠partial · ❌missing (C=Claude, X=Codex)
---
{POLICY}
---
## 1 · Domain map ({total} total) [SHARED]
Pick domain → open shard `{REG}/domains/<dom>.md` → score-sorted full list.
{domain_map_md()}
---
## 2 · Pinned selection table (curated examples, usage baseline 0)
{pinned_table(primary)}
---
{DISAMBIG}
---
{CHAINS}
---
{TRIGGERS}
---
{provenance_md()}
---
## Split-work protocol
```
task splits Claude ⇄ Codex
{split}
└─ shared field (★/repo/purpose/parity/score/disambig/new skill) → BOTH files, one commit
```
## Auto-fill sources
| field | source | trigger |
|---|---|---|
| id,type,repo,path,installed,parity | `.agents/.skill-lock.json` + skill dirs | install → `build_registry.py` |
| ★, upstream push | `gh api` → `stars-cache.json` | weekly → `sync_stars.py` (needs gh) |
| ⟳, ✓%, last_used | `usage.log` (Skill hook) | per use → `build_registry.py` |
| purpose, use-when | `SKILL.md` frontmatter | build_registry |
| model, score | computed (legend formula) | build_registry |
| domains, rating, disambig | `overrides.jsonl` (manual) | by hand |
## Status / Pending
- [x] Domains refined: 29 precise domains, misc≈5
- [x] Usage hooks LIVE both harnesses (Claude + Codex PostToolUse `Skill` → usage.log)
- [x] Effectiveness scoring (quality-led) + §0 Selection Policy + cost_tier right-sizing
- [ ] Rate `effectiveness` on more skills (most default 3/5 — quality signal grows as you rate via overrides.jsonl)
- [ ] Outcome logging (success/fail) → real ✓% (hook logs invocation only now)
"""
os.makedirs(os.path.dirname(CLA_OUT), exist_ok=True)
os.makedirs(os.path.dirname(COD_OUT), exist_ok=True)
open(CLA_OUT, "w", encoding="utf-8").write(registry_md("CLAUDE"))
open(COD_OUT, "w", encoding="utf-8").write(registry_md("CODEX"))
print(f"INDEX.md + {len(dom)} shards + 2 REGISTRY.md written")
print("domains:", ", ".join(f"{d}({len(rs)})" for d,rs in dom_sorted[:14]))
@@ -0,0 +1,345 @@
#!/usr/bin/env node
import { promises as fs } from "node:fs";
import path from "node:path";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
const HOME = process.env.HOME;
const graphPath = path.join(HOME, ".agents/registry/capability-system-graph/graphify-out/graph.json");
const routerPath = path.join(HOME, ".agents/registry/scripts/route-skills.mjs");
// Local-first cascade gate. Top finalist must clear this route_score floor to count
// as a "strong" local hit; below it, --external-fallback emits a discovery step so the
// arsenal can grow instead of recycling the same skills.
// Calibrated 2026-06-13: HAVE matches scored 148-351, MISS 77-130 -> floor 140.
// Override per-run via env CAP_FALLBACK_FLOOR.
const FALLBACK_FLOOR = Number(process.env.CAP_FALLBACK_FLOOR || 140);
function usage() {
console.error('Usage: capability-plan.mjs "task text" [--cwd PATH] [--limit N] [--json] [--external-fallback] [--log]');
process.exit(2);
}
const args = process.argv.slice(2);
if (!args.length) usage();
let task = "";
let cwd = process.cwd();
let limit = 10;
let jsonOut = false;
let externalFallback = false;
let logWeak = false;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === "--cwd") {
cwd = args[++i] || cwd;
} else if (arg === "--limit") {
limit = Number(args[++i] || "10");
} else if (arg === "--json") {
jsonOut = true;
} else if (arg === "--external-fallback") {
externalFallback = true;
} else if (arg === "--log") {
logWeak = true;
} else if (!task) {
task = arg;
} else {
task += ` ${arg}`;
}
}
task = task.trim();
if (!task) usage();
async function exists(file) {
try {
await fs.access(file);
return true;
} catch {
return false;
}
}
async function run(command, args, options = {}) {
try {
const result = await execFileAsync(command, args, {
cwd,
timeout: options.timeout || 15000,
maxBuffer: options.maxBuffer || 1024 * 1024,
});
return { ok: true, stdout: result.stdout.trim(), stderr: result.stderr.trim() };
} catch (error) {
return {
ok: false,
stdout: String(error.stdout || "").trim(),
stderr: String(error.stderr || error.message || "").trim(),
};
}
}
async function findUp(names, start) {
const found = [];
let current = path.resolve(start);
for (;;) {
for (const name of names) {
const file = path.join(current, name);
if (await exists(file)) found.push(file);
}
const parent = path.dirname(current);
if (parent === current || current === HOME) break;
current = parent;
}
return found;
}
async function scanFilesNative(root, maxDepth = 3, maxFiles = 3000) {
const skip = new Set([
".git",
"node_modules",
"Library",
"session-env",
"sessions",
"cache",
".cache",
"Caches",
]);
const files = [];
async function visit(dir, depth) {
if (files.length >= maxFiles || depth > maxDepth) return;
let entries = [];
try {
entries = await fs.readdir(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (files.length >= maxFiles) break;
if (entry.isDirectory()) {
if (skip.has(entry.name)) continue;
await visit(path.join(dir, entry.name), depth + 1);
} else if (entry.isFile()) {
files.push(path.relative(root, path.join(dir, entry.name)) || entry.name);
}
}
}
await visit(path.resolve(root), 0);
return files;
}
async function listProjectSignals() {
const rules = await findUp(["AGENTS.md", "CLAUDE.md", "claud.md"], cwd);
const rg = await run("rg", [
"--files",
"--hidden",
"-g", "!**/.git/**",
"-g", "!**/node_modules/**",
"-g", "!**/Library/**",
"-g", "!**/session-env/**",
"-g", "!**/sessions/**",
"-g", "!**/cache/**",
"-g", "!**/.cache/**",
], { timeout: 10000, maxBuffer: 2 * 1024 * 1024 });
let files = rg.ok ? rg.stdout.split(/\r?\n/).filter(Boolean) : [];
if (!files.length) files = await scanFilesNative(cwd);
const configPatterns = /(^|\/)(package\.json|pnpm-lock\.yaml|yarn\.lock|requirements\.txt|pyproject\.toml|Cargo\.toml|go\.mod|deno\.json|vite\.config\.[jt]s|next\.config\.[jm]s|tsconfig\.json|README\.md)$/;
const configs = files
.filter((file) => configPatterns.test(file))
.filter((file) => !/\.agents\/skills\/[^/]+\/README\.md$/.test(file))
.slice(0, 18);
const tests = files.filter((file) => /(^|\/)(test|tests|spec|__tests__)\/|(\.test|\.spec)\.[jt]sx?$/.test(file)).slice(0, 12);
const graph = await findUp(["graphify-out/graph.json"], cwd);
return {
cwd,
rules: rules.slice(0, 8),
file_count: files.length,
configs,
tests,
local_graphs: graph.slice(0, 5),
};
}
function trimGraphOutput(text) {
return text
.split(/\r?\n/)
.filter((line) => /^(NODE|EDGE|Traversal|Start:|NODE |EDGE )/.test(line) || line.includes("src="))
.slice(0, 36)
.join("\n")
.slice(0, 3600);
}
async function graphQueries() {
if (!(await exists(graphPath))) return [];
const questions = [
`For this task, what capability planning rules and files should be consulted first? Task: ${task}`,
`Which Skill plugin MCP capability families are relevant to this task? Task: ${task}`,
`What is the fastest cheap path from root contract to route-skills and selected capabilities? Task: ${task}`,
];
const outputs = [];
for (const question of questions) {
const res = await run("graphify", ["query", question, "--graph", graphPath, "--budget", "900"], {
timeout: 12000,
maxBuffer: 512 * 1024,
});
outputs.push({
question,
ok: res.ok,
excerpt: trimGraphOutput(res.stdout || res.stderr),
});
}
return outputs;
}
async function routeCapabilities() {
const res = await run("node", [routerPath, task, "--limit", String(limit), "--json"], {
timeout: 15000,
maxBuffer: 2 * 1024 * 1024,
});
if (!res.ok) return { ok: false, error: res.stderr || res.stdout };
try {
return { ok: true, ...JSON.parse(res.stdout) };
} catch {
return { ok: false, error: "router returned invalid JSON", raw: res.stdout };
}
}
function choose(results = []) {
const selected = [];
const byType = new Map();
for (const result of results) {
const type = result.type || "skill";
if (!byType.has(type)) byType.set(type, result);
}
for (const type of ["skill", "mcp", "plugin", "agent"]) {
if (byType.has(type)) selected.push(byType.get(type));
}
for (const result of results) {
if (selected.length >= 5) break;
if (!selected.some((item) => item.id === result.id && item.type === result.type)) selected.push(result);
}
return selected;
}
function reasonFor(record) {
const parts = [];
if (record.domains?.length) parts.push(`domains=${record.domains.join("/")}`);
if (record.registry_score) parts.push(`registry=${record.registry_score}`);
if (record.usage_count) parts.push(`usage=${record.usage_count}`);
if (record.stars) parts.push(`stars=${record.stars}`);
if (record.cost_tier) parts.push(`cost=${record.cost_tier}`);
return parts.length ? parts.join(", ") : "direct route fit";
}
// Decide whether the best local finalist is a strong enough hit to stop here, or
// whether the cascade should widen to the external ecosystem (gated discovery).
function assessLocal(items = []) {
const top = items[0];
if (!top) {
return { level: "none", floor: FALLBACK_FLOOR, reason: "no local candidate with route_score>0" };
}
const route = Number(top.route_score || 0);
const lex = Number(top.lexical_score || 0);
if (route < FALLBACK_FLOOR) {
return { level: "weak", floor: FALLBACK_FLOOR, top: top.name, route_score: route,
reason: `top "${top.name}" route_score=${route} < floor ${FALLBACK_FLOOR}` };
}
if (lex <= 0) {
return { level: "weak", floor: FALLBACK_FLOOR, top: top.name, route_score: route,
reason: `top "${top.name}" is popularity-only (lexical_score=0, no term overlap)` };
}
return { level: "strong", floor: FALLBACK_FLOOR, top: top.name, route_score: route,
reason: `top "${top.name}" route_score=${route} lexical=${lex}` };
}
// Read-only external discovery recipe (no execution here — the agent runs it visibly).
function externalDiscovery(taskText) {
const terms = taskText.toLowerCase().split(/\s+/).filter((t) => t.length > 2).slice(0, 6).join(" ");
return {
trigger: "local match below floor — widen to external skills ecosystem",
search_command: `npx skills find "${terms}"`,
safety: "READ-ONLY discovery. Before install: read SKILL.md + run `uvx mcp-scan@latest --skills` + explicit user approval. Never `add -y` or blind `-g`.",
after_adopt: "register in SHARED-SKILLS-WORKFLOWS.md + rebuild index (build-skill-index.mjs) + /graphify, so next run resolves it locally (Tier-0). This is the growth loop.",
};
}
const [repo, graph, routed] = await Promise.all([
listProjectSignals(),
graphQueries(),
routeCapabilities(),
]);
const results = routed.ok ? routed.results || [] : [];
const selected = choose(results);
const skipped = results
.filter((record) => !selected.some((item) => item.id === record.id && item.type === record.type))
.slice(0, 4);
const localMatch = assessLocal(selected);
const report = {
task,
repo,
graph,
routed,
selected,
skipped,
local_match: localMatch,
};
if (externalFallback && localMatch.level !== "strong") {
report.external_fallback = externalDiscovery(task);
}
// Auto-capture weak/none matches so the self-learning loop needs no discipline.
if (logWeak && localMatch.level !== "strong") {
try {
const stamp = new Date().toISOString().slice(0, 10);
const row = [stamp, cwd, localMatch.level, localMatch.top || "-", localMatch.route_score || 0, task]
.join("\t") + "\n";
await fs.appendFile(path.join(HOME, ".claude/references/routing-auto.log"), row);
} catch {}
}
if (jsonOut) {
console.log(JSON.stringify(report, null, 2));
} else {
console.log("Capability preflight");
console.log(`Task: ${task}`);
console.log("");
console.log("Repo signal:");
console.log(`- cwd: ${repo.cwd}`);
console.log(`- files: ${repo.file_count}`);
if (repo.rules.length) console.log(`- rules: ${repo.rules.map((file) => path.basename(file)).join(", ")}`);
if (repo.configs.length) console.log(`- configs: ${repo.configs.slice(0, 8).join(", ")}`);
if (repo.tests.length) console.log(`- tests: ${repo.tests.slice(0, 5).join(", ")}`);
if (repo.local_graphs.length) console.log(`- local graphs: ${repo.local_graphs.join(", ")}`);
console.log("");
console.log("Graph signal:");
if (!graph.length) {
console.log("- no capability graph found");
} else {
for (const item of graph) {
const firstNode = (item.excerpt.match(/^NODE .+$/m) || [""])[0].replace(/^NODE /, "");
console.log(`- ${item.ok ? "ok" : "miss"}: ${firstNode || item.question.slice(0, 96)}`);
}
}
console.log("");
console.log("Capability plan:");
console.log("- note: draft from graph + router; agent must refine before action");
for (const item of selected) {
console.log(`- use: ${item.name} [${item.type || "skill"}] — ${reasonFor(item)}`);
if (item.path) console.log(` source: ${item.path}`);
}
for (const item of skipped) {
console.log(`- skip: ${item.name} [${item.type || "skill"}] — lower priority after selected finalists`);
}
console.log("");
console.log(`Local match: ${localMatch.level} — ${localMatch.reason}`);
if (report.external_fallback) {
console.log("External fallback (local below floor):");
console.log(`- search: ${report.external_fallback.search_command}`);
console.log(`- safety: ${report.external_fallback.safety}`);
console.log(`- after adopt: ${report.external_fallback.after_adopt}`);
}
console.log("- next: read/call only selected finalists, then execute task");
}
@@ -0,0 +1,131 @@
#!/usr/bin/env node
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
const DEFAULT_LIMIT = 200;
const TARGET_NAMES = new Set(["AGENTS.md", "CLAUDE.md"]);
const SKIP_DIRS = new Set([
".git",
"node_modules",
".next",
"dist",
"build",
".venv",
"venv",
"__pycache__",
".pytest_cache",
".mypy_cache",
".ruff_cache",
".cache",
"sessions",
"file-history",
"backups",
"archive",
"skills",
"plugins",
"cache",
"marketplaces",
"capability-system-graph",
"graphify-out",
]);
function argValue(name, fallback = null) {
const i = process.argv.indexOf(name);
if (i === -1 || i + 1 >= process.argv.length) return fallback;
return process.argv[i + 1];
}
function hasFlag(name) {
return process.argv.includes(name);
}
function real(p) {
return path.resolve(p.replace(/^~(?=$|\/)/, os.homedir()));
}
function countLines(file) {
const text = fs.readFileSync(file, "utf8");
if (!text) return 0;
return text.endsWith("\n") ? text.split("\n").length - 1 : text.split("\n").length;
}
function shouldSkipDir(dir) {
const base = path.basename(dir);
if (SKIP_DIRS.has(base)) return true;
if (dir.includes(`${path.sep}.codex${path.sep}sessions${path.sep}`)) return true;
if (dir.includes(`${path.sep}.claude${path.sep}projects${path.sep}`)) return true;
if (dir.includes(`${path.sep}.agents${path.sep}skills${path.sep}`)) return true;
if (dir.includes(`${path.sep}.codex${path.sep}skills${path.sep}`)) return true;
if (dir.includes(`${path.sep}.claude${path.sep}skills${path.sep}`)) return true;
if (dir.includes(`${path.sep}.codex${path.sep}plugins${path.sep}`)) return true;
if (dir.includes(`${path.sep}.claude${path.sep}plugins${path.sep}`)) return true;
return false;
}
function walk(root, out) {
let entries = [];
try {
entries = fs.readdirSync(root, { withFileTypes: true });
} catch {
return;
}
for (const ent of entries) {
const p = path.join(root, ent.name);
if (ent.isDirectory()) {
if (!shouldSkipDir(p)) walk(p, out);
} else if (ent.isFile() && TARGET_NAMES.has(ent.name)) {
out.add(p);
}
}
}
function collectFiles(roots, includeGlobal) {
const out = new Set();
for (const root of roots) {
const p = real(root);
if (!fs.existsSync(p)) continue;
const stat = fs.statSync(p);
if (stat.isFile() && TARGET_NAMES.has(path.basename(p))) out.add(p);
if (stat.isDirectory()) walk(p, out);
}
if (includeGlobal) {
for (const p of [
"~/AGENTS.md",
"~/.codex/AGENTS.md",
"~/.claude/AGENTS.md",
"~/.claude/CLAUDE.md",
]) {
const rp = real(p);
if (fs.existsSync(rp)) out.add(rp);
}
}
return [...out].sort();
}
const limit = Number(argValue("--limit", String(DEFAULT_LIMIT)));
const roots = [];
for (let i = 2; i < process.argv.length; i += 1) {
if (process.argv[i] === "--root" && process.argv[i + 1]) {
roots.push(process.argv[i + 1]);
i += 1;
}
}
if (!roots.length) roots.push(process.cwd());
const includeGlobal = !hasFlag("--no-global");
const files = collectFiles(roots, includeGlobal);
const rows = files.map((file) => ({ file, lines: countLines(file) }));
const failures = rows.filter((r) => r.lines > limit);
for (const r of rows) {
const mark = r.lines > limit ? "FAIL" : "OK";
console.log(`${mark}\t${r.lines}\t${r.file}`);
}
if (failures.length) {
console.error(`\nInstruction budget failed: ${failures.length} file(s) over ${limit} lines.`);
process.exit(1);
}
console.log(`\nInstruction budget ok: ${rows.length} file(s), limit ${limit}.`);
@@ -0,0 +1,35 @@
#!/usr/bin/env bash
# Append one capability-routing outcome line to agents-routing-log.md (top of journal).
# Part of the local-first cascade self-learning loop (see CAPABILITY-PLANNING.md).
#
# Usage:
# log-route.sh "<task class>" "<capability used>" "<✅|⚠️|❌>" "<note: local=… fell_back=… adopted=…>"
# Example:
# log-route.sh "react hooks bug" "react-reviewer" "✅" "local=strong fell_back=no adopted=–"
set -euo pipefail
LOG="${HOME}/.claude/references/agents-routing-log.md"
if [ $# -lt 4 ]; then
echo "usage: log-route.sh <task class> <capability> <✅|⚠️|❌> <note>" >&2
exit 2
fi
D="$(date +%F)"
LINE="$D | $1 | $2 | $3 | $4"
MARK="<!-- append below, newest on top -->"
python3 - "$LOG" "$MARK" "$LINE" <<'PY'
import sys
path, mark, line = sys.argv[1], sys.argv[2], sys.argv[3]
with open(path, encoding="utf-8") as fh:
s = fh.read()
i = s.find(mark)
if i == -1: # marker missing -> append at end
s = s.rstrip() + "\n\n" + line + "\n"
else: # insert right after marker (newest on top)
j = i + len(mark)
s = s[:j] + "\n\n" + line + s[j:]
with open(path, "w", encoding="utf-8") as fh:
fh.write(s)
print("logged:", line)
PY
@@ -0,0 +1,246 @@
#!/usr/bin/env node
import { promises as fs } from "node:fs";
import path from "node:path";
const HOME = process.env.HOME;
const indexPath = `${HOME}/.agents/registry/skill-index.json`;
const legacyIndexPath = `${HOME}/.codex/agent-system-ops/routing/skill-index.json`;
const registryPath = `${HOME}/.agents/registry/registry.jsonl`;
function usage() {
console.error('Usage: route-skills.mjs "task text" [--limit N] [--json]');
process.exit(2);
}
const args = process.argv.slice(2);
if (!args.length) usage();
let query = "";
let limit = 7;
let jsonOut = false;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === "--limit") {
limit = Number(args[++i] || "7");
} else if (arg === "--json") {
jsonOut = true;
} else if (!query) {
query = arg;
} else {
query += ` ${arg}`;
}
}
if (!query.trim()) usage();
function terms(text) {
return (text.toLowerCase().match(/[a-zа-я0-9][a-zа-я0-9_.-]{2,}/giu) || [])
.map((w) => w.trim())
.filter(Boolean);
}
function score(record, qTerms) {
const reg = record.registry || {};
const fields = {
id: record.id || "",
name: record.name || "",
description: `${record.description || ""} ${reg.purpose || ""} ${reg.use_when || ""}`,
headings: (record.headings || []).join(" "),
keywords: (record.keywords || []).join(" "),
path: `${record.path || ""} ${(reg.domains || record.domains || []).join(" ")}`,
};
let s = 0;
for (const t of qTerms) {
const esc = t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const re = new RegExp(`(^|[^a-zа-я0-9])${esc}($|[^a-zа-я0-9])`, "iu");
if (re.test(fields.id.toLowerCase())) s += 18;
if (re.test(fields.name.toLowerCase())) s += 16;
if (re.test(fields.keywords.toLowerCase())) s += 8;
if (re.test(fields.description.toLowerCase())) s += 6;
if (re.test(fields.headings.toLowerCase())) s += 4;
if (re.test(fields.path.toLowerCase())) s += 3;
}
const phrase = query.toLowerCase();
if (`${fields.name} ${fields.description}`.toLowerCase().includes(phrase)) s += 20;
return s;
}
let activeIndexPath = indexPath;
let index;
try {
index = JSON.parse(await fs.readFile(indexPath, "utf8"));
} catch {
activeIndexPath = legacyIndexPath;
index = JSON.parse(await fs.readFile(legacyIndexPath, "utf8"));
}
let registry = new Map();
try {
const lines = (await fs.readFile(registryPath, "utf8")).split(/\r?\n/).filter(Boolean);
registry = new Map(lines.map((line) => {
const record = JSON.parse(line);
return [record.id, record];
}));
} catch {
registry = new Map();
}
const qTerms = [...new Set(terms(query))];
const overlays = [
{
when: /(front.?end|ui|ux|dashboard|responsive|layout|landing|component|accessibility|a11y|wcag)/iu,
ids: ["frontend-builder", "frontend-design", "frontend-designer", "accessibility", "frontend-design-audit", "impeccable", "playwright", "browser"],
domains: ["web", "design"],
boost: 180,
},
{
when: /(graphify|graph|knowledge graph|obsidian|vault|knowledge base)/iu,
ids: ["capability-system-graph", "graphify", "gsd-graphify", "obsidian-vault", "knowledge-ops"],
domains: ["agentops", "docs", "research"],
boost: 180,
},
{
when: /(capabilit|skill|plugin|mcp|router|routing|planning|preflight|selection|select)/iu,
ids: ["capability-planning-gate", "cheap-skill-router", "capability-system-graph", "graphify", "context7", "exa", "github", "memory", "agentmemory"],
domains: ["agentops", "planning", "graph"],
boost: 190,
},
{
when: /(skill.?optimizer|skill.?miner|mine.*skill|skill candidate|candidate.*skill|repeated workflow|recurring workflow|session history|scan sessions|weekly skill|skill.?personalizer|personaliz.*skill|audit.*skill|skill audit|trigger.*skill|skill.?generalizer|generaliz.*skill|publish.*skill)/iu,
ids: ["skill-miner", "skill-personalizer", "skill-generalizer"],
domains: ["skills"],
boost: 360,
},
{
when: /(research|compare|sources|reddit|hacker news|github|deep)/iu,
ids: ["deep-research", "firecrawl-deep-research", "firecrawl-search", "browse", "exa", "firecrawl-mcp", "scrapegraph-mcp", "github"],
domains: ["research", "osint", "docs"],
boost: 120,
},
{
when: /(brief|terse|short|caveman)/iu,
ids: ["caveman"],
domains: ["comms"],
boost: 160,
},
{
when: /(dcf|valuation|intrinsic value|wacc|lbo|3-statement|financial model|sensitivity)/iu,
ids: ["dcf-model", "3-statement-model", "lbo-model", "merger-model", "returns-analysis"],
domains: ["finance"],
boost: 180,
},
{
when: /(debug|bug|failing|error|broken|diagnos|fix|test|tdd|regression|trace)/iu,
ids: ["systematic-debugging", "diagnose", "tdd", "test-driven-development", "receiving-code-review", "verification-before-completion", "playwright", "codegraph", "github"],
domains: ["devops", "testing"],
boost: 170,
},
{
when: /(docs|documentation|api|sdk|library|framework|version|release)/iu,
ids: ["context7", "firecrawl-search", "exa"],
domains: ["docs", "code"],
boost: 150,
},
{
when: /(spreadsheet|excel|xls|google sheets|table|csv)/iu,
ids: ["spreadsheets", "audit-xls", "clean-data-xls", "dcf-model", "3-statement-model"],
domains: ["data", "finance"],
boost: 150,
},
{
when: /(slides|presentation|deck|powerpoint|ppt)/iu,
ids: ["presentations", "client-report"],
domains: ["slides", "docs"],
boost: 150,
},
];
function overlayBoost(record) {
let boost = 0;
const reg = record.registry || {};
const regDomains = reg.domains || record.domains || [];
for (const overlay of overlays) {
if (!overlay.when.test(query)) continue;
if (overlay.ids?.includes(record.id)) boost += overlay.boost;
if (overlay.pathIncludes?.some((part) => record.path.includes(part))) boost += overlay.boost;
if (overlay.domains?.some((domain) => regDomains.includes(domain))) boost += Math.round(overlay.boost * 0.25);
}
return boost;
}
function qualityBoost(record, lexicalScore, routeBoost) {
const reg = record.registry || {};
const registryScore = Number(reg.score || 0);
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);
}
function costRank(cost) {
const normalized = String(cost || "").toLowerCase();
if (normalized === "light" || normalized === "l") return 0;
if (normalized === "medium" || normalized === "m") return 1;
if (normalized === "heavy" || normalized === "h") return 2;
return 1;
}
const scored = index.records
.map((record) => {
const registryRecord = registry.get(record.id) || {};
const merged = { ...record, registry: registryRecord };
const lexicalScore = score(merged, qTerms);
const routeBoost = overlayBoost(merged);
const finalScore = lexicalScore + routeBoost + qualityBoost(merged, lexicalScore, routeBoost);
return {
...merged,
route_score: finalScore,
type: record.type || registryRecord.type || "skill",
lexical_score: lexicalScore,
registry_score: registryRecord.score || 0,
domains: registryRecord.domains || record.domains || [],
stars: registryRecord.stars || null,
usage_count: registryRecord.usage_count || 0,
usage_30d: registryRecord.usage_30d || 0,
cost_tier: registryRecord.cost_tier || record.cost_tier || "",
model: registryRecord.model || record.model || "",
};
})
.filter((record) => record.route_score > 0)
.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 ||
costRank(a.cost_tier) - costRank(b.cost_tier) ||
a.path.localeCompare(b.path)
);
const seen = new Set();
const results = [];
for (const record of scored) {
const key = `${record.type}:${record.id}`;
if (seen.has(key)) continue;
seen.add(key);
results.push(record);
if (results.length >= limit) break;
}
if (jsonOut) {
console.log(JSON.stringify({ query, limit, count: results.length, results }, null, 2));
} else {
console.log(`Query: ${query}`);
console.log(`Index: ${index.count} capabilities · candidates: ${results.length}`);
for (const [i, r] of results.entries()) {
const rel = r.path.replace(`${path.dirname(path.dirname(path.dirname(activeIndexPath)))}/`, "");
console.log("");
console.log(`${i + 1}. ${r.name} type=${r.type} route=${r.route_score} registry=${r.registry_score}`);
console.log(` path: ${r.path}`);
if (r.domains?.length) console.log(` domains: ${r.domains.join(", ")} · cost: ${r.cost_tier || "?"} · model: ${r.model || "?"}`);
if (r.stars || r.usage_count) console.log(` signals: stars=${r.stars || 0} · usage=${r.usage_count || 0} · usage30=${r.usage_30d || 0}`);
if (r.description) console.log(` desc: ${r.description.slice(0, 220)}`);
if (r.headings?.length) console.log(` headings: ${r.headings.slice(0, 4).join(" · ")}`);
if (rel !== r.path) console.log(` rel: ${rel}`);
}
console.log("");
console.log("Next: explain selected capabilities, then read/call only the chosen finalists.");
}
@@ -0,0 +1,66 @@
#!/usr/bin/env node
// Surface standing capability gaps from the auto-captured routing log.
//
// Reads ~/.claude/references/routing-auto.log (TSV: date, cwd, level, top, route_score, task)
// written by capability-plan.mjs --log on weak/none matches. Buckets rows by task signature;
// a signature seen >= MIN times is a STANDING GAP worth filling proactively (find + vet + adopt)
// instead of falling back to the external ecosystem every single time.
//
// Silent (no output, exit 0) when there are no standing gaps — safe to wire into a
// SessionStart hook once the log has accumulated data.
//
// Usage: node routing-gaps.mjs (GAP_MIN env overrides the >=2 threshold)
import { promises as fs } from "node:fs";
import path from "node:path";
const HOME = process.env.HOME;
const LOG = path.join(HOME, ".claude/references/routing-auto.log");
const MIN = Number(process.env.GAP_MIN || 2);
const STOP = new Set([
"the","a","an","for","with","and","to","of","in","on","my","me","that","this",
"is","be","it","how","do","i","using","use","from","new","app","code","please",
]);
function signature(task) {
return [...new Set(
task.toLowerCase()
.replace(/[^0-9a-zа-яё\s-]/gi, " ")
.split(/\s+/)
.filter((w) => w.length > 3 && !STOP.has(w)),
)].sort().slice(0, 6).join(" ");
}
let raw = "";
try {
raw = await fs.readFile(LOG, "utf8");
} catch {
process.exit(0); // no log yet -> nothing to report
}
const groups = new Map();
for (const line of raw.split("\n")) {
if (!line.trim()) continue;
const [date, , level, , , ...rest] = line.split("\t");
const task = rest.join("\t");
const sig = signature(task || "");
if (!sig) continue;
if (!groups.has(sig)) groups.set(sig, { n: 0, last: "", sample: task, levels: {} });
const g = groups.get(sig);
g.n += 1;
if ((date || "") > g.last) g.last = date || "";
g.levels[level] = (g.levels[level] || 0) + 1;
}
const gaps = [...groups.values()]
.filter((g) => g.n >= MIN)
.sort((a, b) => b.n - a.n);
if (!gaps.length) process.exit(0); // silent when nothing actionable
console.log(`Standing capability gaps (weak/none local matches seen >= ${MIN}x):`);
for (const g of gaps.slice(0, 15)) {
const lv = Object.entries(g.levels).map(([k, v]) => `${k}:${v}`).join(",");
console.log(`- ${g.n}x [${lv}] "${(g.sample || "").slice(0, 60)}" (last ${g.last})`);
}
console.log("Fill these: find + vet (mcp-scan) + adopt -> they become Tier-0 local hits, gap closes.");
@@ -0,0 +1,20 @@
// PostToolUse hook (matcher: Skill). Appends one line per skill invocation.
// Fast, side-effect-only, never throws into the harness. harness=claude.
let d = "";
process.stdin.on("data", (c) => (d += c));
process.stdin.on("end", () => {
try {
const i = JSON.parse(d || "{}");
if (i.tool_name !== "Skill") return;
const ti = i.tool_input || {};
const sk = ti.skill || ti.command || "";
if (!sk) return;
const fs = require("fs");
const os = require("os");
const logPath = require("path").join(os.homedir(), ".agents/registry/usage.log");
const line = new Date().toISOString() + "\tclaude\t" + sk + "\n";
fs.appendFileSync(logPath, line);
} catch (e) {
/* never break the tool pipeline */
}
});
@@ -0,0 +1,24 @@
// PostToolUse hook (matcher: Skill). Appends one line per skill invocation.
// Fast, side-effect-only, never throws into the harness. harness=codex.
// Mirrors usage_hook.js (claude) — same log file, same format.
let d = "";
const t = setTimeout(() => process.exit(0), 10000);
process.stdin.setEncoding("utf8");
process.stdin.on("data", (c) => (d += c));
process.stdin.on("end", () => {
clearTimeout(t);
try {
const i = JSON.parse(d || "{}");
if (i.tool_name !== "Skill") return;
const ti = i.tool_input || {};
const sk = ti.skill || ti.command || "";
if (!sk) return;
const fs = require("fs");
const os = require("os");
const logPath = require("path").join(os.homedir(), ".agents/registry/usage.log");
const line = new Date().toISOString() + "\tcodex\t" + sk + "\n";
fs.appendFileSync(logPath, line);
} catch (e) {
/* never break the tool pipeline */
}
});
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""Validate registry.jsonl: required keys, parity↔harness consistency, dup ids,
score range, orphan overrides. Exit 1 on hard errors. Run after each rebuild."""
import json, sys, os
HOME = os.path.expanduser("~")
REG = f"{HOME}/.agents/registry"
DB = f"{REG}/registry.jsonl"
REQUIRED = ["id", "type", "purpose", "domains", "harness", "parity",
"usage_count", "score", "rating", "status"]
recs, errors, warns = [], [], []
ids = set()
for n, line in enumerate(open(DB, encoding="utf-8"), 1):
line = line.strip()
if not line:
continue
try:
r = json.loads(line)
except Exception as e:
errors.append(f"line {n}: bad json: {e}")
continue
recs.append(r)
for k in REQUIRED:
if k not in r:
errors.append(f"{r.get('id','?')}: missing key '{k}'")
if r["id"] in ids:
errors.append(f"duplicate id: {r['id']}")
ids.add(r["id"])
if not (0 <= r.get("score", -1) <= 100):
warns.append(f"{r['id']}: score out of range ({r.get('score')})")
h = r.get("harness", {})
both = h.get("claude") == "installed" and h.get("codex") == "installed"
if both and r.get("parity") not in ("synced",):
warns.append(f"{r['id']}: both installed but parity={r.get('parity')}")
if not both and r.get("parity") == "synced":
errors.append(f"{r['id']}: parity=synced but harness={h}")
# orphan overrides (id not in registry)
ovp = f"{REG}/overrides.jsonl"
if os.path.exists(ovp):
for line in open(ovp, encoding="utf-8"):
line = line.strip()
if line:
oid = json.loads(line).get("id")
if oid not in ids:
warns.append(f"override for unknown id: {oid}")
print(f"validated {len(recs)} records | {len(errors)} errors | {len(warns)} warnings")
for e in errors[:20]:
print(" ERROR:", e)
for w in warns[:20]:
print(" warn:", w)
if len(warns) > 20:
print(f" ... +{len(warns)-20} more warnings")
sys.exit(1 if errors else 0)