Publish ctx snapshot 90952e7
Browse filesClean git-tracked snapshot of ctx, including the shipped knowledge graph tarball, Skills.sh catalog metadata, and text-to-cad harness graph entry.
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .claude/commands/toolbox-init.mdAdded+54
- .dedup-allowlist.txtAdded+18
- .githooks/pre-commitAdded+168
- .github/ISSUE_TEMPLATE/bug_report.mdAdded+36
- .github/ISSUE_TEMPLATE/feature_request.mdAdded+23
- .github/pull_request_template.mdAdded+15
- .github/workflows/clean-host-contract.ymlAdded+29
- .github/workflows/docs.ymlAdded+69
- .github/workflows/publish.ymlAdded+138
- .github/workflows/test.ymlAdded+241
- .gitignoreAdded+87
- AGENTS.mdAdded+70
- CHANGELOG.mdAdded+1235
- CONTRIBUTING.mdAdded+77
- LICENSEAdded+21
- README.mdAdded+85
- docs/SKILL.mdAdded+690
- docs/backup-hook-install.mdAdded+224
- docs/dashboard.mdAdded+262
- docs/entity-onboarding.mdAdded+273
- docs/harness/attaching-to-hosts.mdAdded+259
- docs/harness/clean-host-contract.mdAdded+101
- docs/index.mdAdded+197
- docs/knowledge-graph.mdAdded+210
- docs/marketplace-registry.mdAdded+157
- docs/memory-anchor.mdAdded+102
- docs/plans/001-model-agnostic-harness.mdAdded+467
- docs/roadmap/skill-quality.mdAdded+209
- docs/roadmap/toolbox.mdAdded+141
- docs/services/macos/com.claude.backup.watchdog.plistAdded+58
- docs/services/systemd/claude-backup-watchdog.serviceAdded+40
- docs/services/windows/install-backup-watchdog.ps1Added+120
- docs/skill-lifecycle-and-dashboard.mdAdded+171
- docs/skill-quality-install.mdAdded+171
- docs/skill-router/index.mdAdded+49
- docs/skill-stack-matrix.mdAdded+165
- docs/skills-health.mdAdded+108
- docs/stack-signatures.mdAdded+164
- docs/toolbox/behavior-miner.mdAdded+90
- docs/toolbox/configuration.mdAdded+143
- docs/toolbox/council-runner.mdAdded+81
- docs/toolbox/hooks.mdAdded+80
- docs/toolbox/index.mdAdded+75
- docs/toolbox/intent-interview.mdAdded+94
- docs/toolbox/starters.mdAdded+96
- docs/toolbox/templates/docs-review.jsonAdded+30
- docs/toolbox/templates/fresh-repo-init.jsonAdded+29
- docs/toolbox/templates/refactor-safety.jsonAdded+31
- docs/toolbox/templates/security-sweep.jsonAdded+31
- docs/toolbox/templates/ship-it.jsonAdded+33
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354# /toolbox init
Run the intent interview to bootstrap this repo's toolbox set.
## What it does
Drives `src/intent_interview.py init` to:
1. Detect the repo's state (git? commits? languages? existing toolbox config?).2. Load the current behaviour profile from `~/.claude/user-profile.json`.3. Ask up to three questions: - which starter toolboxes to activate (ship-it, security-sweep, refactor-safety, docs-review, fresh-repo-init) - which behaviour-miner suggestions to accept (if any exist) - default analysis mode for new toolboxes4. Persist the chosen toolboxes to `~/.claude/toolboxes.json` when `--apply` is passed.
The interview can be skipped at any prompt by typing `skip`.
## Usage
```bash# Default: interactive flow, dry run (no write to global config)python src/intent_interview.py init
# Preset flow (no prompts)python src/intent_interview.py init --preset blank --applypython src/intent_interview.py init --preset existing --applypython src/intent_interview.py init --preset docs-heavy --applypython src/intent_interview.py init --preset security-first --apply
# Fully structured (for CI or scripted setup)python src/intent_interview.py init \ --non-interactive \ --starters ship-it,security-sweep \ --suggestions 1,2 \ --analysis dynamic \ --apply
# Just detect state without running the interviewpython src/intent_interview.py detect```
## Exit codes
- `0` — success, JSON payload printed to stdout- non-zero — unrecoverable error (unknown preset, malformed args)
## Related
- `src/toolbox.py` — CLI for managing the toolbox set directly.- `src/behavior_miner.py` — produces the suggestions this command surfaces.- `src/toolbox_hooks.py` — the bridge between Claude Code hooks and the runner.123456789101112131415161718# Dedup allowlist — pairs that look duplicate by cosine similarity# but are legitimately distinct. The dedup gate skips these in the# report.## Format: one pair per line:## <slug_a> <slug_b> # reason## Slugs are matched case-sensitively against the entity's directory# name (e.g. `mattpocock-tdd`, not `mattpocock_tdd`). Order doesn't# matter — the gate canonicalises (low, high) before matching.## Anything after `#` on a line is a comment.## Examples (uncomment after reviewing the actual finding):## strix-vulnerabilities-csrf strix-vulnerabilities-xss # both web vuln playbooks; structurally similar but cover different attack classes# python-pro python-patterns # one is the agent prompt, the other is the pattern guide; intentional overlap123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168#!/usr/bin/env bash# pre-commit -- keep README numbers and wiki tarball in sync with reality.## Enable with: git config core.hooksPath .githooks# Disable with: git config --unset core.hooksPath## Two stages run on every commit:## 1. Stat refresh: regenerate skill/agent/graph/test counts in README.md# from authoritative sources. Re-stages README.md if it drifted.## 2. Wiki rebuild (only when skills/ or agents/ changed in this commit):# rebuild entity pages + knowledge graph, repack the wiki tarball at# graph/wiki-graph.tar.gz, and re-stage it so the committed state of# the repo always matches the deployed wiki.## Behaviour on failure is *permissive*: if a tool can't resolve something# (wiki not deployed, pytest missing, tar unavailable), it warns and leaves# the affected file untouched. The commit is never blocked.
set -u
REPO_ROOT="$(git rev-parse --show-toplevel)"UPDATER="$REPO_ROOT/src/update_repo_stats.py"WIKI_DIR="$HOME/.claude/skill-wiki"TARBALL="$REPO_ROOT/graph/wiki-graph.tar.gz"SKILLS_SH_CATALOG="$REPO_ROOT/graph/skills-sh-catalog.json.gz"SKILLS_SH_IMPORTER="$REPO_ROOT/src/import_skills_sh_catalog.py"
PYTHON="${PYTHON:-python3}"command -v "$PYTHON" >/dev/null 2>&1 || PYTHON="python"
log() { echo "[pre-commit] $*" >&2; }
# ── Stage 1: README stat refresh ──────────────────────────────────────────────if [[ -f "$UPDATER" ]]; then if ! "$PYTHON" "$UPDATER" 2> >(sed 's/^/[pre-commit stats] /' >&2); then log "stats updater failed — continuing without README refresh" elif ! git diff --quiet -- README.md; then git add README.md log "README.md refreshed and re-staged" fifi
# ── Stage 2: Wiki tarball refresh ─────────────────────────────────────────────# Trigger conditions (any one fires a rebuild):## A. The commit touches repo-tracked entity sources:# - skills/ agents/ (legacy locations)# - any src/*mirror*.py / src/*_install.py (behavioural contract# changes for how entities flow from local -> wiki -> tarball)# B. The tarball itself is already staged (force-rebuild signal —# e.g. a manual repack the author wants preserved).# C. WIKI DRIFT: ~/.claude/skill-wiki/ carries content newer than# graph/wiki-graph.tar.gz. Covers the case where# ctx-skill-mirror / ctx-agent-mirror / ctx-mcp-ingest wrote into# the wiki OUTSIDE a commit and the tarball is now stale. Prior# to this rule MCP ingests were invisible to the hook — MCPs# don't live under repo-tracked skills/ or agents/.STAGED_CHANGES=$(git diff --cached --name-only)NEEDS_WIKI_REBUILD=0WIKI_REBUILD_REASON=""
if echo "$STAGED_CHANGES" | grep -qE '^(skills|agents)/' ; then NEEDS_WIKI_REBUILD=1 WIKI_REBUILD_REASON="skills/ or agents/ source changed"elif echo "$STAGED_CHANGES" | grep -qE '^graph/wiki-graph\.tar\.gz$' ; then NEEDS_WIKI_REBUILD=1 WIKI_REBUILD_REASON="tarball staged (force-rebuild signal)"elif [[ -f "$TARBALL" && -d "$WIKI_DIR" ]]; then # Cheap drift check: find the newest relevant wiki file and compare # against the tarball's mtime. Bounded to the dirs we actually pack # (exclude raw/, .embedding-cache/, checkpoints) so unrelated # regenerable state doesn't fire a rebuild. WIKI_NEWEST=$(find "$WIKI_DIR" \ -path "$WIKI_DIR/raw" -prune -o \ -path "$WIKI_DIR/.embedding-cache" -prune -o \ -path "$WIKI_DIR/.ingest-checkpoint" -prune -o \ -path "$WIKI_DIR/.enrich-checkpoint" -prune -o \ -type f -newer "$TARBALL" -print 2>/dev/null | head -1) if [[ -n "$WIKI_NEWEST" ]]; then NEEDS_WIKI_REBUILD=1 WIKI_REBUILD_REASON="wiki drift — ${WIKI_NEWEST#$WIKI_DIR/} newer than tarball" fifi
if [[ $NEEDS_WIKI_REBUILD -eq 1 ]]; then if [[ ! -d "$WIKI_DIR" ]]; then log "$WIKI_REBUILD_REASON, but wiki not deployed at $WIKI_DIR — skipping rebuild" else log "$WIKI_REBUILD_REASON — rebuilding wiki + graph + tarball (skills + agents + MCPs)"
# Regenerate entity pages + graph. These two scripts already warn but # don't abort on individual failures. if ! "$PYTHON" "$REPO_ROOT/src/wiki_batch_entities.py" --all \ 2> >(sed 's/^/[pre-commit wiki] /' >&2); then log "entity regen failed — continuing" fi if ! PYTHONPATH="$REPO_ROOT/src${PYTHONPATH:+:$PYTHONPATH}" "$PYTHON" -m ctx.core.wiki.wiki_graphify \ 2> >(sed 's/^/[pre-commit wiki] /' >&2); then log "graph rebuild failed — continuing" fi
# Repack the tarball. We exclude .obsidian, .trash, and venv artifacts. # Working dir = $WIKI_DIR's parent so the tarball contents are relative # to skill-wiki/. if command -v tar >/dev/null 2>&1; then mkdir -p "$(dirname "$TARBALL")" # --force-local: GNU tar on Windows/MSYS otherwise parses the # colon in ``c:/path`` as a host:path remote-tar spec and fails # with "Cannot connect to c: resolve failed". This flag tells # tar the path is always local regardless of any colon it contains. # # .obsidian is intentionally included — graph/README documents # that the tarball opens directly as an Obsidian vault. Dropping # it silently removes a shipped feature. # Exclusions beyond .trash / __pycache__: # - raw/: MCP catalog HTML dumps (pulsemcp scraper). 700MB+ # of regenerable content; the ingest cache is pointless # to ship and pushed the tarball past GitHub's 100MB # single-file limit. # - .embedding-cache/: 60MB+ of sentence-transformer vectors # keyed by content hash. Auto-regenerated on the first # graphify after unpack. # - .ingest-checkpoint/ + .enrich-checkpoint/: per-user # resume state for catalog scrapes. Useless to another # user and could leak partial enrichment history. # - graphify-out/graph-delta.json + graph.pickle: the delta # is a single-run artifact; pickle was removed as an RCE # vector in 86a1688 but a stale one on disk must not ship. if ( cd "$WIKI_DIR" && tar --force-local -czf "$TARBALL" \ --exclude='.trash' \ --exclude='__pycache__' \ --exclude='./raw' \ --exclude='./.embedding-cache' \ --exclude='./.ingest-checkpoint' \ --exclude='./.enrich-checkpoint' \ --exclude='./graphify-out/graph-delta.json' \ --exclude='./graphify-out/graph.pickle' \ . ); then if [[ -f "$SKILLS_SH_CATALOG" && -f "$SKILLS_SH_IMPORTER" ]]; then "$PYTHON" "$SKILLS_SH_IMPORTER" \ --from-catalog "$SKILLS_SH_CATALOG" \ --catalog-out "$SKILLS_SH_CATALOG" \ --wiki-tar "$TARBALL" \ --update-wiki-tar \ 2> >(sed 's/^/[pre-commit skills.sh] /' >&2) \ || log "Skills.sh overlay refresh failed — continuing with curated tarball" fi git add "$TARBALL" [[ -f "$SKILLS_SH_CATALOG" ]] && git add "$SKILLS_SH_CATALOG" log "wiki tarball rebuilt and re-staged ($(du -h "$TARBALL" | cut -f1))" else log "tar repack failed — tarball left as-is" fi else log "tar not available — skipping tarball repack" fi
# Refresh README stats again (counts likely changed). if [[ -f "$UPDATER" ]]; then "$PYTHON" "$UPDATER" 2>/dev/null || true git diff --quiet -- README.md || { git add README.md; log "README refreshed after wiki rebuild"; } fi fifi
exit 0123456789101112131415161718192021222324252627282930313233343536---name: Bug reportabout: Something is brokentitle: "[bug] "labels: bugassignees: ""---
## Describe the bug
A clear description of what went wrong.
## To reproduce
Steps to reproduce:
1. Run `...`2. See error
## Expected behaviour
What you expected to happen.
## Actual behaviour
What actually happened. Include the full traceback if applicable.
## Environment
- OS:- Python version:- ctx version / commit:
## Additional context
Any other context (config snippets, related issues, etc.).1234567891011121314151617181920212223---name: Feature requestabout: Suggest an improvement or new capabilitytitle: "[feat] "labels: enhancementassignees: ""---
## Problem statement
What problem does this feature solve? Who is affected?
## Proposed solution
Describe your preferred solution. Include any API or CLI surface you have in mind.
## Alternatives considered
Any other approaches you considered and why you ruled them out.
## Additional context
Relevant links, prior art, or examples.123456789101112131415## Summary
<!-- What does this PR do? One paragraph is fine. -->
## Related issue
<!-- Closes #<issue-number>, or "N/A" -->
## Test plan
- [ ] Existing tests pass (`pytest -q`)- [ ] New tests added for changed behaviour- [ ] `ruff check src/` passes- [ ] `mypy src/` passes- [ ] Integration tests checked if embedding code was touched (`pytest -q -m integration`)1234567891011121314151617181920212223242526272829name: Clean Host Contract
on:
workflow_dispatch:
schedule:
- cron: "17 3 * * 1"
jobs:
clean-host-contract:
name: Clean wheel install and A-Z contract
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python 3.12
uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
cache-dependency-path: pyproject.toml
- name: Upgrade pip
run: python -m pip install --upgrade pip
- name: Run clean-host contract
run: python scripts/clean_host_contract.py --fast123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869name: Deploy docs to GitHub Pages
# Build the MkDocs Material site and publish to GitHub Pages on every push# to main. Also deployable on demand via the workflow_dispatch trigger.
on: push: branches: - main paths: - "docs/**" - "mkdocs.yml" - "requirements-docs.txt" - ".github/workflows/docs.yml" workflow_dispatch:
# GitHub Pages requires these permissions on the deploy job.permissions: contents: read pages: write id-token: write
# Allow only one concurrent deploy; cancel in-progress runs on a new push.concurrency: group: "pages" cancel-in-progress: true
jobs: build: name: Build site runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 with: fetch-depth: 0 # Required by mkdocs git-revision plugins if added.
- name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11" cache: "pip" cache-dependency-path: requirements-docs.txt
- name: Install docs dependencies run: | python -m pip install --upgrade pip python -m pip install -r requirements-docs.txt
- name: Build site (strict) run: | python -m mkdocs build --strict
- name: Upload Pages artifact uses: actions/upload-pages-artifact@v3 with: path: site
deploy: name: Deploy to GitHub Pages needs: build runs-on: ubuntu-latest environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} steps: - name: Deploy id: deployment uses: actions/deploy-pages@v4123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138name: Publish to PyPI
# Publish claude-ctx to PyPI on every tag that looks like a version
# (v0.5.0, v0.5.0-rc1, v1.0.0, …). Uses PyPI Trusted Publishing —
# no API token needed once the pending publisher is configured at
# https://pypi.org/manage/account/publishing/.
#
# Also deployable on demand via workflow_dispatch (useful for
# re-publishing to TestPyPI).
on:
push:
tags:
- "v*"
workflow_dispatch:
inputs:
repository:
description: "PyPI repository (pypi or testpypi)"
required: true
default: "pypi"
type: choice
options:
- pypi
- testpypi
permissions:
id-token: write # required for Trusted Publishing
contents: read
jobs:
build:
name: Build sdist + wheel
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install release tooling
run: |
python -m pip install --upgrade pip
python -m pip install build packaging twine
- name: Validate tag matches package version
if: github.event_name == 'push'
run: |
python - <<'PY'
import os
import tomllib
from packaging.version import Version
tag = os.environ["GITHUB_REF_NAME"]
if not tag.startswith("v"):
raise SystemExit(f"release tag must start with v: {tag}")
with open("pyproject.toml", "rb") as fh:
package_version = tomllib.load(fh)["project"]["version"]
tag_version = str(Version(tag[1:]))
normalized_package_version = str(Version(package_version))
if tag_version != normalized_package_version:
raise SystemExit(
f"tag {tag!r} does not match pyproject version {package_version!r}"
)
print(f"release version {package_version} matches tag {tag}")
PY
- name: Build distributions
run: python -m build
- name: Check distributions
run: python -m twine check dist/*
- name: Smoke install wheel
run: |
python -m venv .venv-smoke
. .venv-smoke/bin/activate
python -m pip install --upgrade pip
python -m pip install dist/*.whl
python -m pip check
python - <<'PY'
from importlib.metadata import entry_points, version
import ctx
dist_version = version("claude-ctx")
if ctx.__version__ != dist_version:
raise SystemExit(
f"ctx.__version__={ctx.__version__!r} != metadata {dist_version!r}"
)
scripts = [
ep for ep in entry_points(group="console_scripts")
if ep.name == "ctx" or ep.name.startswith("ctx-")
]
failures = []
for ep in scripts:
try:
ep.load()
except Exception as exc:
failures.append(f"{ep.name}: {exc!r}")
if failures:
raise SystemExit("console script load failures:\n" + "\n".join(failures))
print(f"loaded {len(scripts)} ctx console scripts from wheel {dist_version}")
PY
- name: Upload dist artifact
uses: actions/upload-artifact@v4
with:
name: dist
path: dist/
publish:
name: Publish to PyPI
needs: build
runs-on: ubuntu-latest
environment:
name: pypi
url: https://pypi.org/project/claude-ctx/
steps:
- name: Download dist artifact
uses: actions/download-artifact@v4
with:
name: dist
path: dist/
- name: Publish to PyPI
if: github.event_name == 'push' || github.event.inputs.repository == 'pypi'
uses: pypa/gh-action-pypi-publish@release/v1
- name: Publish to TestPyPI
if: github.event_name == 'workflow_dispatch' && github.event.inputs.repository == 'testpypi'
uses: pypa/gh-action-pypi-publish@release/v1
with:
repository-url: https://test.pypi.org/legacy/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241name: Tests
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
name: pytest (${{ matrix.os }} / py${{ matrix.python-version }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
python-version: ["3.11", "3.12"]
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
cache: pip
cache-dependency-path: pyproject.toml
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]"
- name: Run static quality gates run: python -m ruff check src hooks scripts && python -m mypy src && python -m pip check
- name: Run tests with coverage gate
# --cov-fail-under=40 is the FLOOR, not the goal. QA-expert
# flagged zero coverage on install CLIs, install_utils,
# semantic_edges, and others; the immediate ask is that a PR
# which DROPS coverage below the current baseline fails CI.
# Bump this number as the coverage sprint ships — never
# lower it.
run: pytest -q -m "not browser" --cov=src --cov-report=term-missing --cov-fail-under=40
- name: Upload coverage artifact
if: matrix.os == 'ubuntu-latest' && matrix.python-version == '3.11'
uses: actions/upload-artifact@v4
with:
name: coverage
path: .coverage
retention-days: 7
e2e-canary:
name: "A-Z alive-loop E2E canary"
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python 3.11
uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
cache-dependency-path: pyproject.toml
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]"
- name: Run E2E + fuzz canary suite
# These two files pin the critical-path invariants:
# test_alive_loop_e2e.py: A-Z user journey (signals → bundle →
# install → unload → purge) — any handoff regression trips it.
# test_fuzz_yaml_rendering.py: property-based YAML injection
# coverage on install/enrich render_scalar.
# They live in the main matrix job already, but pulling them
# forward as a separate fail-fast canary surfaces the regression
# in seconds instead of waiting for the full 2500-test run.
run: |
pytest -q --no-cov \
src/tests/test_alive_loop_e2e.py \
src/tests/test_fuzz_yaml_rendering.py
browser-security:
name: "Browser monitor security"
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python 3.12
uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
cache-dependency-path: pyproject.toml
- name: Install browser test dependencies
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev,browser]"
python -m playwright install --with-deps chromium
- name: Run browser security tests
run: pytest -q --no-cov -m browser src/tests/test_ctx_monitor_browser.py
package-smoke:
name: "Wheel package smoke"
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python 3.12
uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
cache-dependency-path: pyproject.toml
- name: Build and inspect wheel
run: |
python -m pip install --upgrade pip
python -m pip install build twine
python -m build
python -m twine check dist/*
- name: Install wheel in clean venv
run: |
python -m venv .venv-smoke
. .venv-smoke/bin/activate
python -m pip install --upgrade pip
python -m pip install dist/*.whl
python -m pip check
python - <<'PY'
from importlib.metadata import entry_points, version
import ctx
dist_version = version("claude-ctx")
if ctx.__version__ != dist_version:
raise SystemExit(
f"ctx.__version__={ctx.__version__!r} != metadata {dist_version!r}"
)
scripts = [
ep for ep in entry_points(group="console_scripts")
if ep.name == "ctx" or ep.name.startswith("ctx-")
]
failures = []
for ep in scripts:
try:
ep.load()
except Exception as exc:
failures.append(f"{ep.name}: {exc!r}")
if failures:
raise SystemExit("console script load failures:\n" + "\n".join(failures))
print(f"loaded {len(scripts)} ctx console scripts from wheel {dist_version}")
PY
ctx-init --help >/dev/null
ctx-scan-repo --help >/dev/null
ctx-wiki-graphify --help >/dev/null
ctx --help >/dev/null
clean-host-contract:
name: "Clean host contract"
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python 3.12
uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
cache-dependency-path: pyproject.toml
- name: Upgrade pip
run: python -m pip install --upgrade pip
- name: Run clean-host contract
run: python scripts/clean_host_contract.py --fast
no-test-no-merge:
name: "Every src/*.py change must touch a src/tests/*.py"
runs-on: ubuntu-latest
if: github.event_name == 'pull_request'
steps:
- name: Checkout with full history
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Enforce test-coverage-per-PR policy
# Policy: any source change under src/ that isn't itself a test
# must be accompanied by at least one test file change in the
# same PR. Exemptions:
# - Pure docs / comment changes (matched by a trivial heuristic)
# - Config JSON (src/config.json) — schema changes get tests
# for the accessor, not the JSON itself.
# - Changes ONLY inside __pycache__, .pyc files, etc.
run: |
set -euo pipefail
BASE="${{ github.event.pull_request.base.sha }}"
HEAD="${{ github.event.pull_request.head.sha }}"
LABELS='${{ toJson(github.event.pull_request.labels.*.name) }}'
CHANGED=$(git diff --name-only "$BASE" "$HEAD" -- 'src/**/*.py' 'src/**/*.json' || true)
SRC=$(echo "$CHANGED" | grep -E '^src/.*\.py$' | grep -v '^src/tests/' || true)
TEST=$(echo "$CHANGED" | grep -E '^src/tests/.*\.py$' || true)
if [ -z "$SRC" ]; then
echo "No src/*.py changes — policy not applicable."
exit 0
fi
if [ -z "$TEST" ]; then
if echo "$LABELS" | grep -q '"no-tests-needed"'; then
echo "Policy exempted by no-tests-needed label."
exit 0
fi
echo "::error::Policy violation — src/*.py changed but no src/tests/*.py touched in this PR."
echo "Source files changed without accompanying test:"
echo "$SRC"
echo ""
echo "Fix: add or update tests in src/tests/ that cover the change."
echo "If the change is genuinely untestable (e.g. a release-version"
echo "bump), label the PR 'no-tests-needed' and leave a comment."
exit 1
fi
echo "Policy satisfied — src changes accompanied by test changes."
echo ""
echo "Source files:"
echo "$SRC"
echo ""
echo "Test files:"
echo "$TEST"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687# Babysitter orchestration — runs, state, and local SDK install
.a5c/
# Python
__pycache__/
*.py[cod]
*.pyo
*.pyd
.Python
*.egg-info/
dist/
build/
*.egg
.eggs/
.venv/
venv/
env/
.env
# Node / npm
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
package-lock.json
# Temp / runtime outputs
/tmp/
*.tmp
*.bak
*.swp
*.swo
.DS_Store
Thumbs.db
# Skill system runtime files (generated, not source)
/skills/skill-router/check-gates.md
/skills/skill-router/failure-log.md
# Agent directives (cloned from global ~/.claude/CLAUDE.md — personal, not for sharing)
CLAUDE.md
# Per-workspace Claude Code settings (local permissions, user-specific)
.claude/
# Wiki (runtime knowledge store, not source)
# Uncomment to exclude the wiki from the repo:
# ~/.claude/skill-wiki/
# Intent log and pending signals (session runtime)# These live in ~/.claude/ so already outside the repo
# Internal review artifacts and working notes (not public docs)/docs/reports//docs/plans/20[0-9][0-9]-*//docs/plans/20[0-9][0-9]-*.md/internal/reviews/
# Generated graph review artifacts (regenerate locally when needed)/graph/*-report.md/graph/*-report.json/graph/*-report.json.gz/graph/tag-backfill.md/graph/tag-backfill.json
# Secrets / config overridesskill-system-config.json.env.local
# Strix security scanner (local venv, instructions, output)
.strix-venv/
.strix-instructions.txt
.strix-output/
.strix-out/
.strix-run.log
.strix-preview-wiki/
.imported-deployed/
strix_runs/
# Test coverage
.coverage
htmlcov/
.pytest_cache/
.mypy_cache/
# MkDocs build output
/site/12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970# Agent Directives: Mechanical Overrides
You are operating within a constrained context window and strict system prompts. To produce production-grade code, you MUST adhere to these overrides:
## Pre-Work
1. THE "STEP 0" RULE: Dead code accelerates context compaction. Before ANY structural refactor on a file >300 LOC, first remove all dead props, unused exports, unused imports, and debug logs. Commit this cleanup separately before starting the real work.
2. PHASED EXECUTION: Never attempt multi-file refactors in a single response. Break work into explicit phases. Complete Phase 1, run verification, and wait for my explicit approval before Phase 2. Each phase must touch no more than 5 files.
## Code Quality
3. THE SENIOR DEV OVERRIDE: Ignore your default directives to "avoid improvements beyond what was asked" and "try the simplest approach." If architecture is flawed, state is duplicated, or patterns are inconsistent - propose and implement structural fixes. Ask yourself: "What would a senior, experienced, perfectionist dev reject in code review?" Fix all of it. Don't be lazy.
4. FORCED VERIFICATION: Your internal tools mark file writes as successful even if the code does not compile. You are FORBIDDEN from reporting a task as complete until you have:- Run `npx tsc --noEmit` (or the project's equivalent type-check)- Run `npx eslint . --quiet` (if configured)- Fixed ALL resulting errors
If no type-checker is configured, state that explicitly instead of claiming success.
## Context Management
5. SUB-AGENT SWARMING: For tasks touching >5 independent files, you MUST launch parallel sub-agents (5-8 files per agent). Each agent gets its own context window. This is not optional - sequential processing of large tasks guarantees context decay.
6. CONTEXT DECAY AWARENESS: After 10+ messages in a conversation, you MUST re-read any file before editing it. Do not trust your memory of file contents. Auto-compaction may have silently destroyed that context and you will edit against stale state.
7. FILE READ BUDGET: Each file read is capped at 2,000 lines. For files over 500 LOC, you MUST use offset and limit parameters to read in sequential chunks. Never assume you have seen a complete file from a single read.
8. TOOL RESULT BLINDNESS: Tool results over 50,000 characters are silently truncated to a 2,000-byte preview. If any search or command returns suspiciously few results, re-run it with narrower scope (single directory, stricter glob). State when you suspect truncation occurred.
## Edit Safety
9. EDIT INTEGRITY: Before EVERY file edit, re-read the file. After editing, read it again to confirm the change applied correctly. The Edit tool fails silently when old_string doesn't match due to stale context. Never batch more than 3 edits to the same file without a verification read.
10. NO SEMANTIC SEARCH: You have grep, not an AST. When renaming or changing any function/type/variable, you MUST search separately for: - Direct calls and references - Type-level references (interfaces, generics) - String literals containing the name - Dynamic imports and require() calls - Re-exports and barrel file entries - Test files and mocks Do not assume a single grep caught everything.
## Coding Discipline (Karpathy Principles)
11. THINK BEFORE CODING: Don't assume. Don't hide confusion. Surface tradeoffs. Before implementing: - State assumptions explicitly. If uncertain, ask. - If multiple interpretations exist, present them - don't pick silently. - If a simpler approach exists, say so. Push back when warranted. - If something is unclear, stop. Name what's confusing. Ask.
12. SIMPLICITY FIRST: Minimum code that solves the problem. Nothing speculative. No features beyond what was asked. No abstractions for single-use code. No "flexibility" or "configurability" that wasn't requested. If you write 200 lines and it could be 50, rewrite it. **Note:** This complements rule #3 (Senior Dev Override) - fix real architectural flaws, but don't overbuild.
13. SURGICAL CHANGES: When editing existing code, match existing style. Don't "improve" adjacent code, comments, or formatting that aren't part of the task. If your changes create orphans, remove them. If you notice unrelated dead code, mention it - don't delete it. Every changed line should trace directly to the user's request. **Note:** Rule #1 (Step 0) is the exception - dead code cleanup is done as a separate, explicit commit before refactoring.
14. GOAL-DRIVEN EXECUTION: Transform vague tasks into verifiable goals before starting. For multi-step tasks, state a brief plan with success criteria: ``` 1. [Step] -> verify: [check] 2. [Step] -> verify: [check] ``` Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification. **Note:** This extends rule #4 (Forced Verification) from tool-level checks to task-level planning.
## Post-Work
15. CODEX REVIEW: Every completed task is reviewed by Codex after you hand off. Before declaring "done": - Re-read every file you edited and confirm the change actually persisted. - Re-run the verification commands from rule #4 and quote the output, not the intent. - Separate what you **observed** from what you **inferred** — Codex will catch inferences dressed up as observations. - Leave a short "for-the-reviewer" note at the end of your response: what you touched, what you verified, what you did NOT verify and why. This is non-negotiable — a downstream reviewer seeing no caveats assumes everything was checked, and that assumption is what gets shipped.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235# Changelog
All notable changes to the `ctx` project will be documented in this file.
Format loosely follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## [Unreleased]
- No unreleased changes yet.
## [0.7.0] - 2026-04-28
This release is the hardening and model-agnostic harness release. It
consolidates the MCP phase work that had accumulated under Unreleased,
then adds the full review remediation stack: shared recommendation
semantics, safer harness execution/resume/tooling, locked and durable
state writes, cleaner package/CI gates, and typed skill/agent/MCP
handling across the dashboard, resolver, manifest, and wiki.
### Security
- Hardened monitor mutations with same-origin and token checks.
- Locked manifest and wiki read-modify-write paths that can be hit by
concurrent sessions or dashboard actions.
- Made MCP subprocess environment inheritance opt-in and validated
live MCP `inherit_env` configs as strict booleans.
- Hardened install/archive/wiki paths against traversal, symlink, and
unsafe extraction cases.
- Added an explicit approval/policy gate for model-driven tool calls.
### Harness
- Added the generic `ctx run`/`ctx resume`/`ctx sessions` harness and
standalone `ctx-mcp-server` surface.
- Fixed resume ordering/tool restoration, terminal budget accounting,
empty/truncated completion handling, compaction usage charging, and
MCP request timeout behavior.
- Added opt-in live-host gates for Claude Code and MCP compatibility
checks without spending quota or running third-party code by default.
### Recommendation And Wiki
- Unified recommendation behavior behind shared tag/entity logic across
CLI, library, MCP, and harness surfaces.
- Made scan/resolve/manifests preserve typed skill, agent, and MCP
entries.
- Made wiki sync write agents and MCP servers into their typed entity
locations, including sharded MCP paths, instead of treating every
manifest load as a skill.
- Added durable atomic writes for wiki/state files.
### CI And Release
- Added wheel/package smoke checks, version/tag alignment protections,
clean-host contract coverage, and browser-monitor CI coverage.
- Updated package license metadata to the modern SPDX string form.
- Raised the local type gate to `python -m mypy src`.
- This release bumps package metadata from `0.6.4` to `0.7.0`; do not
reuse the existing remote `v0.6.4` tag.
Detailed phase notes for the MCP work included in 0.7.0 are retained below.
## [0.7.0] — MCP Phase 6a — cheap wins before scale
Three small items from the Phase 2.5, 5, and 6 backlogs, bundled so
the scale work (6b–6f) starts from a clean base.
### Security
- **``_fs_utils.atomic_write_{text,bytes,json}``** now ``chmod 0o600``
the temp file before ``os.replace`` so the renamed inode lands
owner-only. Phase 2.5 security-reviewer MEDIUM: ``tempfile.mkstemp``
creates with 0o600 on POSIX but ``os.replace`` onto an existing
file can inherit the destination's more-permissive mode. Explicit
chmod closes that window. Windows ignores the bits (OSError swallowed).
### Added
- **``ctx-mcp-fetch -v / --verbose``** — wires up ``logging.basicConfig``
so library-module ``_logger.info`` / ``_logger.debug`` calls
(Phase 2.5 print→logging cleanup) surface on stderr. ``-v`` = INFO,
``-vv`` = DEBUG. Default silent so JSONL pipe consumers stay clean.
- **``ctx-scan-repo --recommend``** — after stack detection, runs
``resolve()`` and prints a three-section summary to stdout: Skills
(from ``manifest["load"]``), Agents (filtered from load by type),
MCP Servers (``manifest["mcp_servers"]`` from Phase 5). Default
off — scan stays fast for callers who only want the profile.
### Tests
- 4 new ``TestVerboseFlag`` cases in ``test_mcp_fetch_cli.py``: no-op
at verbosity 0, INFO at -v, DEBUG at -vv, argparser accepts the flag.
- 5 new tests in ``test_fs_utils_permissions.py`` (POSIX-only via
``pytest.mark.skipif``): 0o600 on text/bytes/json writes, and the
critical regression for the Phase 2.5 finding — overwriting a 0o644
file must pin the result to 0o600.
- Total: **1626 passed, 6 skipped** (was 1621 → +5 new tests + 4
new platform-skips, 0 regressions).
### Live verification
```
$ ctx-mcp-fetch --source awesome-mcp --limit 2 -v 2>&1 >/dev/null
[mcp_sources.awesome_mcp] parsed 2023 entries, skipped 0
[awesome-mcp] emitted 2 record(s)
$ ctx-scan-repo --repo . --recommend
... 16 Skills / 0 MCP Servers (with helpful hint to populate) / 4 Notes
```
## [0.7.0] — MCP Phase 5 — cross-type recommendations
Closes the loop on MCP integration: the graph already contained MCP
nodes with cross-type edges (Phase 3c) and had per-MCP quality scores
(Phase 4); Phase 5 wires them into the recommender so a user scanning
a repo sees MCP suggestions alongside skill/agent recommendations.
### Changed
- **``resolve_skills.resolve``**: graph-walk hits with
``type=="mcp-server"`` now land in ``manifest["mcp_servers"]`` as
``{name, reason, score, via, shared_tags}`` entries. Previously they
were silently filtered out because the skill-availability check
(``name in available``) dropped them — ``available`` contains only
installed SKILLS.
- **Noise floor per hit type**: skills remain at ``>= 1.5`` (calibrated
for the 1789-node / 454k-edge dense skill graph where single-tag
overlaps are noise). MCPs get ``>= 1.0`` since the corpus is sparse
(42 today, projected ~12k in Phase 6) so a single matched edge is
already a meaningful signal.
- **Graph-walk pool widened from top_n=12 to top_n=30**: without this,
equal-score-1.0 skills filled all 12 slots before any MCPs could
surface. The downstream noise floor + availability filter keep the
final manifest tight regardless of pool size.
- **``resolve_graph.resolve_by_seeds``** now recognizes the
``mcp-server:`` node prefix in addition to ``skill:`` and ``agent:``
so a seed name that matches an MCP slug (e.g. ``github``,
``filesystem``) can kick off a walk from MCP territory too.
- **``wiki_graphify._attach_quality_attrs``** scans both
``~/.claude/skill-quality/*.json`` (skills + agents) and
``~/.claude/skill-quality/mcp/*.json`` (MCPs). Phase 4 put MCP
sidecars in the ``mcp/`` subdir for isolation; without this Phase 5
change, MCP graph nodes would never pick up their quality scores
for Obsidian-graph coloring etc.
### Live verification
```
Synthetic GitHub Actions repo → resolve()
load: 2 skills
mcp_servers: 4 MCPs surfaced:
github-mcp-server-awesome-variant score=1.00 shared=['_t:github']
github score=1.00 shared=['_t:github']
tadas-github-a2asearch-mcp score=1.00 shared=['_t:github']
data-everything-mcp-server-templates score=1.00 shared=['_t:templates']
```
Each MCP recommendation carries a reason string and the shared graph
tags that produced it. Cross-type edges are the mechanism proven in
Phase 3c; Phase 5 is the presentation layer.
### Tests
- 5 new ``TestResolveMcpRecommendations`` cases in
``test_resolve_skills.py``: MCP lands in correct bucket (not load),
reason+score preserved, dedup on repeat hits, noise floor respected,
mixed skill+mcp hits route correctly.
- 3 new cases in ``test_wiki_graphify_quality.py``: mcp/ subdir
loaded, missing ``subject_type`` field inferred from subdir,
backward compat when mcp/ doesn't exist.
- Total: **1621 passed, 2 skipped** (was 1613 → +8 new, 0 regressions).
### Not yet done (Phase 5.5 or Phase 6)
- The ``scan_repo`` CLI doesn't yet print MCP recommendations to the
terminal. The manifest is populated correctly but only consumers
that read it (monitor, hooks) see MCPs. Minor UX gap.
- ``## Related MCP Servers`` section header on MCP entity pages can
show skills as neighbors (accurate links, misleading header). Same
neighbors-list works; just cosmetic. Defer to when all entity pages
are regenerated.
- Data sparsity: the 42 MCPs in the wiki today are github/aggregator/
playwright-themed. A random Python+JS repo may surface 0 MCP
recommendations because no topical overlap exists. Phase 6 full
ingest (~12k MCPs) will fix this organically.
## [0.7.0] — MCP Phase 4 — six-signal quality scorer
Adds the MCP-specific quality scorer with the six-signal model designed
in the Phase 4 interview: popularity / freshness / structural / graph /
trust / runtime. Config-overridable weights (default sum 1.0 with
popularity-heavy distribution per the locked decision). Reuses
``SignalResult`` from the existing skill quality system; otherwise
stands as a parallel module to preserve the working skill scorer
contract.
### Added
- **`mcp_quality_signals`** (NEW, ~370 lines): six pure-function signal
extractors, all returning ``SignalResult`` with bounded score [0,1]
and rich evidence dicts.
- ``popularity_signal``: log-scaled GitHub stars, neutral 0.5 when
star data missing
- ``freshness_signal``: exponential decay with 90-day half-life on
days-since-last-commit, neutral when missing
- ``structural_signal``: 5 binary checks (description / repo_url /
tags / transports / language) each contributing 1/5
- ``graph_signal``: degree + cross-type-degree weighted score
- ``trust_signal``: official-or-org tag, license presence, author
presence
- ``runtime_signal``: invocation telemetry placeholder (neutral 0.5
until Phase 5+ runtime instrumentation lands)
- **`mcp_quality`** (NEW, ~1000 lines): orchestrator + ``ctx-mcp-quality``
CLI mirroring the skill quality scorer pattern.
- ``McpQualityConfig`` frozen dataclass with weight + threshold
validation (sum-to-1.0, monotone A>=B>=C, etc.)
- ``McpQualityScore`` frozen dataclass with ``to_dict`` for the
sidecar JSON sink
- ``compute_quality`` pure: weighted sum + grade map. Grade F band
added for very low scores (<0.20) since MCP scorer has no hard-floor
mechanism today
- ``extract_signals_for_slug`` reads entity from
``entities/mcp-servers/<shard>/<slug>.md``, builds graph degrees
from optional pre-loaded ``graph_index``
- ``load_graph_index`` parses ``graphify-out/graph.json`` into
{node_id: {degree, cross_type_degree}} index for cheap per-slug
lookups
- ``persist_quality`` writes three sinks atomically: sidecar JSON at
``~/.claude/skill-quality/mcp/<slug>.json`` (note the ``mcp/``
subdir for clean separation from skill scores), entity-page
frontmatter (``quality_score``/``quality_grade``/``quality_updated_at``),
body block between ``<!-- quality:begin -->`` markers
- CLI verbs: ``recompute --slug X | --all``, ``show <slug>``,
``explain <slug>``, ``list``. ``--wiki-dir PATH`` accepted on
every verb so users can target a non-default wiki without exporting
env vars.
- **``mcp_quality`` block in `config.json`**: weights + thresholds +
saturation knobs + sidecar path. User can override via
``~/.claude/skill-system-config.json``.
- **`pyproject.toml`**: registers ``mcp_quality`` and
``mcp_quality_signals`` modules, plus the ``ctx-mcp-quality`` console
script.
### Live verification
```
$ ctx-mcp-quality recompute --all
... (41 MCPs scored in 1.9 seconds)
$ ctx-mcp-quality list | sort -k2 | head -5
atlassian-cloud B score=0.61
github B score=0.61
ariekogan-ateam-mcp B score=0.62
arikusi-deepseek-mcp-server B score=0.62
playwright-browser-automation B score=0.67
Grade distribution: 16 B (40%), 25 C (60%) across 41 entities.
```
`playwright-browser-automation` top scorer (graph=1.00 from 104 cross-
type neighbors, trust=1.00 from official+org+license, structural=0.80
from 4/5 fields). Popularity/freshness/runtime all neutral 0.5 pending
Phase 6 detail-page enrichment.
### Tests
- 38 cases in ``test_mcp_quality_signals.py``: per-signal happy/edge,
monotonicity, saturation, negative-input ValueError raises
- 30 cases in ``test_mcp_quality.py``: config validation, compute
formula, signal extraction with/without graph_index, persist 3-sink
idempotency, CLI for all 4 verbs (--help, recompute, show, list)
- Total: **1613 passed, 2 skipped** (was 1545 → +68 new, 0 regressions)
### Limitations
- Popularity, freshness, and runtime signals all return neutral 0.5
until Phase 6 enrichment lands the missing fields (stars, last
commit age, invocation telemetry). The infrastructure is in place;
signals will become discriminating automatically once data arrives.
- Sidecar JSONs land at ``~/.claude/skill-quality/mcp/<slug>.json`` —
``wiki_graphify._attach_quality_attrs`` currently scans only the
parent ``~/.claude/skill-quality/`` dir, so MCP scores don't yet
decorate graph nodes. Phase 5 (recommender wiring) will update
``wiki_graphify`` to look in the ``mcp/`` subdir too.
## [0.7.0] — MCP Phase 3.6 — cross-source canonical-key dedup
Phase 3c surfaced that two MCP catalog sources slugify the same upstream
repo differently — awesome-mcp slugifies the README name, pulsemcp uses
the URL path — so the slug-based existence check in ``add_mcp`` would
create two separate entities for the same repo. This phase adds a
github_url-based canonical-key lookup that runs **before** the slug
check so the second source merges into the first entity rather than
duplicating.
### Added
- ``mcp_add._normalize_github_url(url)`` — lowercases host+path, strips
trailing ``/``. Returns None for non-GitHub URLs. Mirrors
``McpRecord.canonical_dedup_key()`` so an existing-entity scan can
match against new records on the same key.
- ``mcp_add._find_existing_by_github_url(mcp_dir, target)`` —
scan-on-demand lookup across all entity files. Substring-greps the
raw text first to avoid parsing 12k YAML frontmatters when the
answer is almost always None, then confirms via frontmatter parse.
### Changed
- ``add_mcp`` runs the canonical-key lookup before the slug existence
check. When a match is found at a different path than the new
record's slug-based path, ``target_path`` is rewritten to the
existing entity's path so the merge fires there.
### Limitations (will be addressed in Phase 6)
- Pulsemcp listing-page records (Phase 2b.5) carry only
``homepage_url: pulsemcp.com/servers/<slug>``, not ``github_url``.
Cross-source dedup against awesome-mcp records won't fire for
pulsemcp until Phase 6 detail-page enrichment populates the
github_url field. The infrastructure is in place; only the data
is missing.
- Scan cost is O(n) per add. Acceptable at the current ~40 entity
scale and tolerable up to ~1k. At Phase 6's projected ~12k+ scale
this needs a sidecar index (canonical_key → entity_relpath).
### Tests
- 7 new ``TestCrossSourceCanonicalKeyDedup`` cases covering
normalize_github_url canonicalization, missing-dir tolerance,
cross-source merge into existing path, no-github_url fallback,
and non-collision proof for entities with mismatched URL fields.
- Total: 1545 passed, 2 skipped (was 1538 → +7 new, 0 regressions).
### Live verification
```
$ ctx-mcp-add --from-jsonl /tmp/cross_source_test.jsonl
[1/2] [added] github-mcp-server-awesome-variant
[2/2] [merged] example-org-cross-source-test
Done: 1 added, 1 merged, 0 rejected, 0 errors
```
Both records carried github_url=``https://github.com/example-org/cross-source-test-repo``
under different slugs and from different sources. Result: 1 entity
file (not 2), sources field merged to ``[awesome-mcp, pulsemcp]``.
Wiki entity count went 40 → 41 (not 42), proving the dedup blocked
the duplicate.
## [0.7.0] — MCP Phase 2.5 — reviewer cleanup
Rolls up the deferred python-reviewer + security-reviewer findings
from Phase 2a/2b/2b.5 that didn't block merge but were worth a
focused cleanup pass.
### Changed
- **`mcp_sources.awesome_mcp`**: replaced two `print(..., file=sys.stderr)`
diagnostic calls with `logging.getLogger(__name__)` calls (per house
rule: library code must not print). Removed the dead
`if TYPE_CHECKING: pass` block and the dead `try/except ImportError`
fallback that was needed only during the parallel-write Phase 2a.
- **`mcp_fetch.py`**: inlined the one-line `_iter_records` wrapper —
it added no error handling beyond the existing `except` block in
`_run_one`. Removed the now-unused `Source` import.
- **`mcp_sources/base.py`**: removed the `#!/usr/bin/env python3`
shebang. `base.py` is a library, not an entry point — the shebang
was a leftover from the Foundation Engineer's template.
### Deferred (still pending)
- `_fs_utils.atomic_write_text` `chmod 0o600` (security MEDIUM): touches
a shared utility used by 14+ modules; warrants its own focused
commit with broader testing rather than rolling into this cleanup.
- `_parse_readme` lazy-yield refactor (Python LOW): current 1.2 MB
peak for the awesome-mcp README is fine.
- `@dataclass(frozen=True)` for Source classes (Python LOW): style
only, no behavior change.
- TypedDict for JSON shapes in old pulsemcp.py: the API mode that
used those shapes was removed in 2b.5.
### Verification
- 1535 passed, 2 skipped (no regressions vs. Phase 2b.5)
- ruff + mypy clean on all touched files
- Live `ctx-mcp-fetch --source awesome-mcp --limit 2` and
`ctx-mcp-fetch --source pulsemcp --limit 2` both produce valid
JSONL with progress emitted to stderr (no longer pollutes stdout)
## [0.7.0] — MCP Phase 2b.5 — pulsemcp switched to public HTML scraping
The pulsemcp.com Sub-Registry API requires per-account credentials
that aren't broadly available. Phase 2b.5 swaps the auth-gated JSON
client for a stdlib HTML scraper of the public listing pages
(`https://www.pulsemcp.com/servers?page=N`), making the source
usable by anyone without contacting PulseMCP for an API key.
### Changed
- **`mcp_sources.pulsemcp` rewritten** for HTML scraping mode. Walks
pages 1..310 (current total: ~12,975 servers / 42 per page = 310
pages). Cards are delineated by `data-test-id="mcp-server-card-<slug>"`
attributes — content-addressed so a frontend restyle of class names
doesn't silently break the parser. Per-card extraction uses
`html.parser.HTMLParser` (stdlib) for robustness against malformed
markup.
- **Per-card data**: slug, name, creator (author), description,
classification (official / community / reference → tag). Detail-page
enrichment (github_url, language, transports) deferred to Phase 6.
- **No credentials required**. The PULSEMCP_API_KEY / PULSEMCP_TENANT_ID
env vars are no longer read; the credential-injection guard, cursor
URL-encoding guard, and 429 handling all dropped along with the API
client. Attack surface for the source is now strictly the HTML
parser.
### Removed
- `src/tests/fixtures/pulsemcp_page1.json` and `pulsemcp_page2.json`
(API-mode fixtures). Replaced with `pulsemcp_listing_excerpt.html`
— a 3-card real-HTML snippet captured from page 1 of the live site.
- `_credentials`, `_MissingPulsemcpCredentialsError`,
`_InvalidPulsemcpCredentialError`, `_build_url`,
`_to_record(server_obj, meta)` API-shape mapper. Replaced with
HTML-shape `_to_record(card_html)`, `_split_cards`, `_parse_listing`,
and `_CardTextExtractor`.
### Tests
- 20 new tests in `test_mcp_sources_pulsemcp.py` covering split,
parse, mapping, and pagination paths against the real-HTML fixture.
- Total: **1,535 passed, 2 skipped** (was 1,546 → -11 net because
the 31 API-mode tests were swapped for 20 HTML tests; 0 regressions
in any unrelated suite).
### Live verification
```
$ ctx-mcp-fetch --source pulsemcp --limit 5 | ctx-mcp-add --from-stdin
[1/5] [added] playwright-browser-automation
[2/5] [added] duckdb
[3/5] [added] excel-file-manipulation
[4/5] [added] office-word
[5/5] [added] context7-documentation-database
Done: 5 added, 0 merged, 0 rejected, 0 errors
```
Sharded paths verified: `entities/mcp-servers/{c,d,e,o,p}/<slug>.md`.
Cleaned up before commit.
## [0.7.0] — MCP Phase 2b — pulsemcp source
Adds the second catalog source: `www.pulsemcp.com` Sub-Registry API
(~12,975 servers as of today). Uses the official JSON API
(`/api/v0.1/servers`) with cursor-based pagination, gated by API
credentials (`PULSEMCP_API_KEY` + `PULSEMCP_TENANT_ID` env vars).
### Added
- **`mcp_sources.pulsemcp`** — Source implementation against the
Generic MCP Registry API spec with PulseMCP `_meta` extensions.
Maps `repository.source == "github"` to `github_url`, infers
`language` from `packages[].registry_name` (`npm` → typescript,
`pypi` → python, `cargo` → rust, etc.), and tags entries with
`_meta["com.pulsemcp/server"].isOfficial == true` as `"official"`.
Caches raw page JSON under `~/.claude/skill-wiki/raw/marketplace-dumps/pulsemcp/<date>--page-NNNN.json`.
- **`fetch_text(headers=...)`** in `mcp_sources.base` — optional
per-call header dict, merged on top of the User-Agent default.
Existing callers unchanged.
### Security
- **CRLF header-injection guard** in `_credentials()`: rejects API key
or tenant ID values containing `\r`, `\n`, or `:`. Python's
`urllib.request.Request` does NOT sanitize header values on 3.11+,
so a malicious env-var value would otherwise inject arbitrary
headers into every authenticated request. Error message does not
echo the rejected value (no secret leakage).
- **Cursor URL-encoding** in `_build_url`: opaque cursors from the
upstream API are wrapped with `urllib.parse.quote(safe='')` to
prevent query-string smuggling (a cursor containing `&` would
inject extra parameters; `#` would silently truncate).
- **Stripped diagnostic output**: malformed-entry warnings no longer
echo the full server object repr to stderr — they emit only the
fact that `name` was missing, in case upstream payloads ever
contain sensitive fields.
### Tests
- **31 new tests** in `test_mcp_sources_pulsemcp.py`:
- 11 `_to_record` mapping tests (happy path, missing fields, github
vs gitlab, official tag, language inference, round-trip through
`McpRecord.from_dict`)
- 4 credential-handling tests
- 4 NEW credential-injection regression tests (CR, LF, colon, secret
not echoed in error)
- 3 NEW cursor URL-encoding regression tests
- 5 pagination tests (single page, two pages with cursor, limit
short-circuits second-page fetch, limit spans pages, 429 raises)
- 4 SOURCE singleton tests
- Tests use an autouse `_isolate_wiki` fixture so cache writes don't
pollute the user's real `~/.claude/skill-wiki/`.
- **Total**: 1,546 passed, 2 skipped (was 1,515 → +31 net, 0 regressions).
- **`pytestmark skipif` removed** — the module now ships, so a broken
import should fail the suite rather than silently skip.
### Live verification
```
$ ctx-mcp-fetch --list-sources
awesome-mcp https://github.com/punkpeye/awesome-mcp-servers
pulsemcp https://www.pulsemcp.com/servers
$ ctx-mcp-fetch --source pulsemcp --limit 1
Error: source 'pulsemcp' failed: Missing required environment
variable(s): PULSEMCP_API_KEY, PULSEMCP_TENANT_ID. Obtain API
credentials from https://www.pulsemcp.com/settings/api-keys and
set them before running the pulsemcp source.
```
Authenticated end-to-end fetch was NOT verified live — the test author
does not have PulseMCP API credentials. The fetch path is exercised
through the recorded JSON fixtures (`pulsemcp_page1.json`,
`pulsemcp_page2.json`) covering both single-page and multi-page cursor
pagination. Users with credentials can run
`PULSEMCP_API_KEY=... PULSEMCP_TENANT_ID=... ctx-mcp-fetch --source pulsemcp --limit 5 | ctx-mcp-add --from-stdin`
to confirm.
### Reviewer findings deferred (Phase 2.5 cleanup)
- File permission tightening on cache writes (Sec MEDIUM): `atomic_write_text` doesn't `chmod 0o600` — affects all sources, not just pulsemcp
- HTTPError body sanitization in non-429 re-raise path (Sec MEDIUM)
- TypedDict for JSON shapes in `pulsemcp.py` (Python MEDIUM)
- `@dataclass(frozen=True)` for `_PulsemcpSource` (Python LOW)
- Consolidate `noqa: no-any-return` suppressions (Python LOW)
## [0.7.0] — MCP Phase 2a — fetcher + first source
Adds the `Source` protocol, an SSRF-hardened HTTP fetcher, and the
first real catalog source: `github.com/punkpeye/awesome-mcp-servers`.
Live verification fetched 2,023 entries from the actual README; the
end-to-end pipe `ctx-mcp-fetch --source awesome-mcp --limit 5 |
ctx-mcp-add --from-stdin` ingested 5 records into the wiki, all of
which entered the knowledge graph and clustered together via shared
tags (e.g. all five `aggregator`-tagged MCPs formed a clique).
### Added
- **`mcp_sources.base`** — `Source` Protocol (`fetch(*, limit, refresh)
→ Iterator[dict]`), `cache_path` / `read_cache` / `write_cache`
helpers under `~/.claude/skill-wiki/raw/marketplace-dumps/<source>/`,
and an SSRF-defended `fetch_text(url)` HTTP client.
- **`mcp_sources.awesome_mcp`** — parses the punkpeye README into
raw record dicts. Walks `## Server Implementations` → `### <Section>`
→ `- [name](url) - description` hierarchy. Tags inferred from
section header (emoji-stripped). Language inferred from per-line
emoji flags. ~2,000 records on the live README.
- **`mcp_fetch.py` + `ctx-mcp-fetch` CLI** — JSONL stream to stdout,
progress to stderr (clean to pipe into `ctx-mcp-add --from-stdin`).
`--list-sources`, `--source <name>`, `--limit N`, `--refresh`.
### Security
- **`fetch_text` defense in depth**: HTTPS-only, allowlist of 5 hosts
(`raw.githubusercontent.com`, `github.com`, `api.github.com`,
`pulsemcp.com`, `www.pulsemcp.com`), no redirects (3xx raises),
10 MB response body cap (raises `_ResponseTooLargeError` rather
than silently truncating).
- **`cache_path` path-traversal guard** — both `source_name` and
`basename` validated as plain filenames (no `/`, `\`, leading dot).
- **`mcp_add._build_corpus_text` YAML safety** — frontmatter now
rendered via `yaml.safe_dump` rather than f-string interpolation
so a malicious description can't escape the YAML scalar.
### Fixed
- **Reload safety** in `mcp_sources.base`: imports the `ctx_config`
module rather than `cfg` directly, so `ctx_config.reload()` (used
by tests) doesn't leave a stale singleton reference.
### Changed
- `pyproject.toml` — adds `mcp_fetch` to `py-modules`, `mcp_sources`
to `packages`, and registers the `ctx-mcp-fetch` console script.
### Tests
- 49 new tests across `test_mcp_sources_base.py` (24, including 4
path-traversal regressions and 1 response-size cap regression),
`test_mcp_sources_awesome.py` (12), `test_mcp_fetch_cli.py` (10),
plus 3 new `TestCorpusTextStructure` cases pinning the YAML safety
in `mcp_add`. Total: 1,515 / 1,517 passed (2 pre-existing skips,
0 regressions).
## [0.7.0] — MCP Phase 1 — foundation
First-class **MCP server** entity type alongside skills and agents.
Phase 1 ships the data model, intake hooks, and ingest CLI; no fetcher
yet (Phase 2) and no quality scoring yet (Phase 4).
### Added
- **`mcp_entity.McpRecord`** — frozen dataclass capturing one MCP
server: slug, description, sources, github URL, tags, transports,
language, license, author, stars, last commit. Normalizes slug to
`[a-z0-9-]+`, canonicalizes GitHub URLs, filters transports to the
known subset, deduplicates and sorts tags. Provides `from_dict`,
`to_frontmatter`, `entity_relpath` (sharded `<first-letter>/<slug>.md`,
`0-9/` for digit-leading slugs), and `canonical_dedup_key` (github URL
> slug fallback).
- **`mcp_add.add_mcp` + `ctx-mcp-add` CLI** — orchestrator that
installs one MCP record into `~/.claude/skill-wiki/entities/mcp-servers/`
via the existing intake gate. Idempotent: re-adding the same record
is a no-op; re-adding from a different source merges sources into one
page. CLI flags: `--from-json`, `--from-jsonl`, `--from-stdin`,
`--dry-run`, `--skip-existing`, `--wiki`. Non-fatal embedding failure
matches the agent_add convention.
- **`generate_mcp_page`** in `wiki_batch_entities.py` — renderer that
matches the existing skill / agent page layout, with sections for
Sources (links to GitHub + homepage), Tags, Transports, and a
placeholder Related block for graph backlinks.
- **`mcp-servers` subject type** in `intake_pipeline._SUBJECT_TYPES` —
MCPs get their own embedding cache namespace, isolated from skills
and agents.
### Changed
- `pyproject.toml` — registers `mcp_add` and `mcp_entity` modules and
the `ctx-mcp-add` console script.
### Notes
- Storage is sharded from day one (`entities/mcp-servers/<first-letter>/<slug>.md`)
to keep listings fast at the projected ~12k+ scale.
- Quality scoring, fetchers, and cross-type recommendations land in
Phases 2-5. Phase 1 is infra only.
- `wiki_sync.update_index` writes the `## Skills` section header for
every subject type (pre-existing limitation also affecting agents).
Subject-aware index updates deferred to a follow-up cleanup.
## [0.6.4] — 2026-04-20
Dashboard-tab release. v0.6.3 added docs for the graph and the KPI
pipeline; v0.6.4 exposes both (plus a proper wiki browser) as
top-level navigation tabs in `ctx-monitor`, so the docs pages match
what's actually reachable in the UI.
### Added
- **`/kpi` HTML route** — renders `kpi_dashboard.generate()` as a
browser view. Six sections: grade distribution, lifecycle tiers
(active/watch/demote/archive), hard-floor reasons, by-category
A/B/C/D/F mix, top-25 demotion candidates (active/watch entries
graded D/F, sorted by D-streak desc then score asc), and the
archived list. Each demotion-candidate slug is a link to
`/skill/<slug>`. Empty-state page points at `ctx-skill-quality
score --all` when the sidecar dir is empty.
- **`/api/kpi.json`** — JSON passthrough of the `DashboardSummary`
dataclass for scripting. Same shape as `python -m kpi_dashboard
render --json`.
- **`/wiki` index route** — card grid of every entity page under
`~/.claude/skill-wiki/entities/{skills,agents}/`. Left sidebar:
text search (slug · description · tag), skill/agent checkboxes,
live "N of M match" counter. Each card shows the slug, quality
grade pill (when a sidecar exists), description, and tag preview.
Slug allowlist (`^[a-z0-9][a-z0-9_.-]{0,127}$`) applied to every
file glob to keep path-traversal bugs out of the index.
- **`/graph` landing-page seeds** — when no slug is selected, the
graph page now shows a "Popular seed slugs" panel with the 18
highest-degree entities as clickable chips, plus a stats line with
node + edge counts. First-time visitors no longer land on a blank
cytoscape canvas with nothing to click.
- **Wiki + KPI tabs in the top nav** — every page now shows
`Home · Loaded · Skills · Wiki · Graph · KPIs · Sessions · Logs ·
Live`.
### Changed
- **`ctx_monitor.py` module docstring** — updated the route
catalogue to the full 15 routes (was 8). New dev-reference table
matches what the server actually exposes.
- **`docs/dashboard.md`** — added a Usage section with three
walkthroughs (Browse the LLM wiki, Explore the knowledge graph,
Read the quality KPIs). Route tables extended with `/wiki`,
`/kpi`, `/api/kpi.json` rows.
### Tests
- +9 tests in `src/tests/test_ctx_monitor.py` covering the new
routes (empty + populated states), the slug-allowlist gate on the
wiki index, the seed-chip panel on `/graph` landing, and nav-bar
tab presence. Full suite: 1,372 passing, 2 skipped.
## [0.6.3] — 2026-04-19
Docs-only release. The two marquee features of ctx — the pre-built
knowledge graph and the `ctx-monitor` dashboard — were referenced all
over the docs but had no dedicated page explaining them. This release
adds both and wires them into the home page and the top of the nav.
### Added
- **`docs/knowledge-graph.md`** — dedicated page for the pre-built
graph: authoritative counts (2,253 nodes / 454,719 edges / 93
communities / 416.6 avg degree / 1,152 max degree / 195,226 skill↔
agent cross-edges / 71 isolated), install via the shipped tarball,
how edges are built (explicit frontmatter tags + slug-token
pseudo-tags with `DENSE_TAG_THRESHOLD=500` and the `SLUG_STOP`
filter), community detection details (greedy modularity
`resolution=1.2`), query recipes via the dashboard + Python +
recommendation path, rebuild instructions, and a postmortem section
explaining why the edge count is 454K and not the stale 642K bundle
referenced in earlier releases.
- **`docs/dashboard.md`** — full `ctx-monitor` reference: startup
commands (with the `--host 0.0.0.0` opt-in warning), complete HTML
route catalog (`/`, `/loaded`, `/skills`, `/skill/<slug>`,
`/wiki/<slug>`, `/graph`, `/sessions`, `/session/<id>`, `/logs`,
`/events`), JSON API (`/api/sessions.json`, `/api/manifest.json`,
`/api/skill/<slug>.json`, `/api/graph/<slug>.json`,
`/api/events.stream`), mutation endpoints with CSRF/same-origin
notes, a **KPIs / measures / scores** section explaining the six
home stat cards, the grade + raw-score view on `/skills`, the full
four-signal breakdown on `/skill/<slug>` (Telemetry 0.40, Intake
0.20, Graph 0.25, Routing 0.15) with hard-floor reasons, and the
`load → score_updated → unload` observability triad on
`/session/<id>`. Also documents the security posture (loopback
default, same-origin gating on POST, slug allowlist on every
path-resolving route).
### Changed
- **`mkdocs.yml` nav** — knowledge graph and dashboard hoisted to
positions 2 and 3 (right after Home), above Toolbox / Skill router /
Health. They are the two observables users are most likely looking
for, so the nav now matches the mental model.
- **`docs/index.md`** — added two grid cards at the top of the "Explore
the docs" section pointing at the new pages, so the home page
surfaces the graph + dashboard as first-class features rather than
burying them inside the router/health sections.
## [0.6.2] — 2026-04-20
Verification-pass patch after v0.6.1 shipped. Three items the v0.6.1
for-the-reviewer note flagged as "not verified" all got verified; one
surfaced a real bug (pre-commit tar repack silently failing on
Windows/MSYS).
### Fixed
- **`.githooks/pre-commit` — tar repack crashed on Windows/MSYS**:
GNU tar parses `c:/path` as `host:path` for legacy rsh remote tar,
tries to resolve host `c`, and fails with `Cannot connect to c:
resolve failed`. The hook swallowed the error (by design — a hook
failure must not block a commit) but the tarball was never
regenerated, so developer-side rebuilds on Windows silently shipped
stale counts. Fixed by passing `--force-local` to the tar invocation.
- **`.obsidian/` Obsidian vault config was being excluded from the
tarball** despite `graph/README.md` advertising "Obsidian vault
config, so the extracted tree opens as a graph directly in Obsidian."
Removed the `--exclude='.obsidian'` from the pre-commit repack so the
tarball actually ships what the docs promise.
### Verified (v0.6.1 "not verified" items)
- **PyPI 0.6.1 published**: wheel `claude_ctx-0.6.1-py3-none-any.whl`
(267 KB) + sdist (232 KB) live, uploaded 2026-04-19T23:45 UTC.
Publish / Tests / Deploy-docs workflows all succeeded.
- **Cytoscape layout quality verified via headless Chromium**:
Playwright loaded `http://127.0.0.1:8811/graph?slug=cloud-architect`,
waited for `cy.nodes().length > 0`, then read the live cytoscape
instance: 40 nodes / 39 edges rendered, center `skill:cloud-architect`
at depth 0, COSE layout placed nodes (bounding box 400×297px, none
at origin), status panel showed "40 nodes · 39 edges", zero JS errors
on `pageerror` or `console.error`. Screenshot captured for proof.
- **Tarball content**: same 1,789 skills / 464 agents / 2,253 nodes
/ 454,719 edges after the hook fix, `.obsidian/` now included as
advertised.
[0.6.2]: https://github.com/stevesolun/ctx/releases/tag/v0.6.2
## [0.6.1] — 2026-04-20
Harvested **`0xNyk/council-of-high-intelligence`** on top of v0.6.0.
The repo contributes a `council` orchestrator skill plus 18 named
persona agents (Karpathy, Sutskever, Taleb, Munger, Feynman, Socrates,
Aristotle, Ada Lovelace, Aurelius, Kahneman, Lao Tzu, Machiavelli,
Meadows, Musashi, Rams, Sun Tzu, Torvalds, Watts). Every agent was
re-intaked with a prepended H1 derived from its `council.figure`
frontmatter field — legitimate data-cleanup, not a gate bypass.
Also fixes a documentation audit: every stale count reference across
README + docs + graph/README had drifted from the shipped tarball
(some said 2,211/642K, others 2,235/448K, community count varied
between 93 and 95). Single sweep + tightened `update_repo_stats`
regex to match "N nodes and N edges" phrasing the old regex missed.
### Graph: final shipped state
| Metric | v0.6.0 | v0.6.1 |
|---|---:|---:|
| Nodes | 2,235 | **2,253** |
| Skills | 1,789 | **1,789** |
| Agents | 446 | **464** |
| Edges | 448,799 | **454,719** |
| Communities | 95 | **93** |
| Avg degree | 414.8 | **416.6** |
| Max degree | 1,144 | **1,152** |
| Skill↔agent cross-edges | 191,770 | **195,226** |
### Added
- **1 skill + 18 agents** from `0xNyk/council-of-high-intelligence`:
`council` (orchestrator) + `council-{ada, aristotle, aurelius,
feynman, kahneman, karpathy, lao-tzu, machiavelli, meadows, munger,
musashi, rams, socrates, sun-tzu, sutskever, taleb, torvalds,
watts}`. Every one passed the intake gate after a minimal H1
transform that preserved the original `## Identity` body.
### Fixed
- **README + docs stale number drift**: 12 locations across README,
graph/README, and 5 docs pages had references to the v0.5.x stale
bundle numbers (2,211/642K/865/952/1,768/443). Single audit pass
updates all to the current live tarball (2,253/454,719/93/956/
1,789/464).
- **`update_repo_stats` regex coverage**: added patterns for
"N nodes and N edges" (missed by the old "N nodes, N edges, N
communities" regex) plus the Python example comment form
"# N nodes, N edges". Any future README sentence using the "and"
connector will auto-refresh correctly.
- **Cytoscape rendering verified live**: `/api/graph/cloud-architect.json`
returns 60 nodes / 59 edges with sensible edge-weight-ranked
neighbors (database-admin, hybrid-cloud-architect,
terraform-engineer all at weight 6 sharing automation+azure+security
tags). The `/graph?slug=<slug>` HTML page embeds cytoscape.js from
CDN with the initial slug JSON-encoded and the tap→/wiki/<slug>
navigation wired.
### Known limitation carried from v0.6.0
Graph rebuild regenerates from the **live wiki**, not from a pinned
baseline. If someone else also re-graphifies locally with slightly
different wiki content, their edge count will differ from the
shipped tarball's. The `update_repo_stats` tarball-first source of
truth (v0.5.1) keeps README honest, but post-install users who
re-graphify will see their own numbers. Documented in `graph/README.md`.
[0.6.1]: https://github.com/stevesolun/ctx/releases/tag/v0.6.1
## [0.6.0] — 2026-04-20
Harvested 11 upstream Claude Code / context-management / token-optimizer
repos and ingested their skills + agents through our intake gate into
the LLM wiki. Every candidate that landed passed the gate's structural
checks (frontmatter name, body H1, minimum body length, no duplicate
embedding) and was rendered in our canonical wiki format (YAML
frontmatter with tags / use_count / last_used / status + Overview +
Tags + Obsidian `[[wikilinks]]` to related skills).
### Added
- **+20 truly new skills** ingested and vetted:
`build-graph`, `caveman-compress`, `caveman-help`, `compress`,
`context-mode`, `context-mode-ops`, `ctx-doctor`, `ctx-insight`,
`ctx-purge`, `ctx-stats`, `ctx-upgrade`, `fleet-auditor`,
`review-delta`, `review-pr`, `rtk-tdd`, `rtk-triage`, `tdd-rust`,
`token-coach`, `token-dashboard`, `token-optimizer`.
- **+3 new agents**: `rtk-testing-specialist`, `rust-rtk`,
`system-architect`.
- **3 existing pages refreshed** with intake-vetted replacements
(`design-patterns`, `issue-triage`, `pr-triage`).
- **`graph/wiki-graph.tar.gz`** re-archived with the new entity pages:
**1,788 skills · 446 agents** (was 1,768 / 443 in v0.5.x).
### Harvest sources
| Upstream repo | Accepted | Rejected |
|---|---:|---:|
| alexgreensh/token-optimizer | 4 skills | 0 |
| juliusbrussee/caveman | 3 skills | 3 (missing H1) |
| mksglu/context-mode | 7 skills | 0 |
| tirth8205/code-review-graph | 2 skills | 5 (missing H1) |
| rtk-ai/rtk | 7 skills + 3 agents | 4 (frontmatter missing `name:`) + 4 (dup agents) |
| russelleNVy/three-man-team | 0 | 3 (dup agents) |
| drona23/claude-token-efficient | 0 | 1 (dup agent) |
| mibayy/token-savior, nadimtuhin, ooples, zilliztech | 0 | (README-only, no SKILL.md/agent files) |
### Intake-gate rejections (preserved for reference)
- `BODY_MISSING_H1` (9 skills): `caveman`, `caveman-commit`,
`caveman-review`, `debug-issue`, `explore-codebase`,
`refactor-safely`, `review-changes` + 2 others.
- `FRONTMATTER_FIELD_MISSING_NAME` (4 skills): `performance`,
`pr-review`, `repo-recap`, `security-guardian`, `ship`.
- Duplicate-agent short-circuit (6): `architect`, `builder`,
`code-reviewer`, `debugger`, `reviewer`, `technical-writer` —
already installed in the wiki; intake gate correctly skipped.
### Fixed
- **Graph sparsity regression** (`src/wiki_graphify.py`): the
`DENSE_TAG_THRESHOLD` constant was `20`, which silently dropped
every tag that appeared on more than 20 nodes. On a wiki where
`python`, `frontend`, `security`, and `testing` each tag hundreds
of entities, this collapsed the graph from the canonical 642,468
edges down to 861 on every rebuild. Bumped to **500** (now pinned
by `src/tests/test_wiki_graphify_density.py`) and added
**slug-token pseudo-tags** — e.g. the slug `fastapi-pro`
contributes an implicit `fastapi` token so skills that share a
topic keyword get connected even when their explicit tags don't
overlap. Stop-word filter keeps noise tokens (`skill`, `agent`,
`pro`, `core`, etc.) out of the index.
- **Multi-line YAML list parsing** (`src/wiki_utils.py`):
`parse_frontmatter` only handled inline `tags: [a, b, c]` lists;
the block form
```yaml
tags:
- python
- frontend
```
returned an empty string, silently invalidating every real wiki
entity page (all 2,234 of them use the block form). Extended the
parser to collect `- item` lines following an empty-value key.
### Graph: final shipped state
| Metric | v0.5.x | v0.6.0 |
|---|---:|---:|
| Nodes | 2,211 | **2,235** |
| Edges | 861 (effective; bundle had 642K stale) | **448,799** |
| Communities | 2,110 (mostly singletons) | **95** |
| Avg degree | <1 | **414.8** |
| Max degree | 40 | **1,144** |
| Skill↔agent cross-edges | — | **191,770** |
| Isolated nodes | 390+ | **71** |
The full recommendation pipeline can now walk edges from a detected
stack signal (e.g. `fastapi`) to installed agents (`code-reviewer`,
`test-automator`) via shared-tag and slug-token pseudo-edges. Verified
via `ctx-monitor`'s `/graph?slug=<any-tagged-slug>` view: every
tag-heavy entity now lights up its neighborhood with 200+ edges on
average.
[0.6.0]: https://github.com/stevesolun/ctx/releases/tag/v0.6.0
## [0.5.1] — 2026-04-20
Point release. Same day as the GA cut, issued to correct one
behavior: the pre-commit stats hook was silently rewriting README
numbers from the user's *live* `~/.claude/skill-wiki/` — which can be
a locally-rebuilt sparse graph — rather than from the shipped
`graph/wiki-graph.tar.gz`. The tag `v0.5.0` therefore pointed at a
commit whose README showed the user's local 885-edge rebuild instead
of the canonical 642,468-edge shipped graph.
### Fixed
- **`src/update_repo_stats.py` source of truth**: the stats refresher
now reads node/edge/skill/agent/community counts from
`graph/wiki-graph.tar.gz` first (the pinned release asset), and
only falls back to `~/.claude/skill-wiki/` when the tarball is
absent. Counts no longer drift across developer machines.
- **README badges + tagline**: restored the authoritative numbers
(1,768 skills · 443 agents · 2,211 nodes · 642K edges · 865
communities) that the v0.5.0 commit accidentally clobbered.
## [0.5.0] — 2026-04-20
First stable release. MIT-licensed, CI-matrixed (ubuntu-latest +
windows-latest × Python 3.11/3.12), **1,360 tests passing**, installable
via `pip install claude-ctx` with 10 console scripts on PATH.
### Highlights
- **Pre-built knowledge graph** (`graph/wiki-graph.tar.gz`, 11.7 MB
compressed): **2,211 nodes** (1,768 skills + 443 agents), **642,468
edges**, **865 communities**, 61 auto-generated concept pages, 952
converted micro-skill pipelines, Obsidian-compatible vault config.
- **Live dashboard** (`ctx-monitor serve` → `http://127.0.0.1:8765/`):
six-card stat grid home, currently-loaded-skills view with load/unload
buttons, Cytoscape graph explorer (`/graph?slug=…`), LLM-wiki entity
browser (`/wiki/<slug>`), filterable skills card grid with left
sidebar, session timeline, audit-log viewer, SSE live event stream.
- **Unified audit log** (`~/.claude/ctx-audit.jsonl`): append-only,
rotates at 25 MB, 24 canonical event types covering the full
skill/agent lifecycle from added → loaded → score_updated →
archived → deleted.
- **Graph load-bearing on recommendations** (`resolve_skills.py`):
matrix-matched skills seed a graph walk that adds 1-hop neighbors
scored by edge weight. On a trivial FastAPI+SQLAlchemy+pytest
repo the manifest now loads 14 relevant skills (fastapi-pro,
async-python-patterns, python-pro, test-automator,
backend-security-coder, etc.) with mixed `fuzzy match` and
`graph neighbor of …` reasons. Previous releases returned 1.
- **One-command setup**: `ctx-init --hooks` creates the standard
`~/.claude/` tree, seeds the five starter toolboxes, and
optionally injects the PostToolUse + Stop hooks into
`~/.claude/settings.json` — replacing the legacy `install.sh` flow
for pip-installed users.
### Added
- **Console scripts**: `ctx-init`, `ctx-install-hooks`, `ctx-monitor`,
`ctx-scan-repo`, `ctx-skill-quality`, `ctx-skill-health`,
`ctx-toolbox`, `ctx-lifecycle`, `ctx-skill-add`,
`ctx-wiki-graphify`.
- **`src/ctx_audit_log.py`** — concurrent-safe append-only audit log
with session attribution, threading lock for in-process safety,
`rotate_if_needed(max_bytes=25MB)` called on every `session.ended`.
- **`src/ctx_monitor.py`** — stdlib-only `http.server` dashboard
(no Flask/Starlette dep). Cytoscape.js loaded from unpkg on the
`/graph` route. Binds to 127.0.0.1 by default; same-origin check
on POST endpoints; slug allowlist regex gates all mutation.
- **`src/ctx_init.py`** — idempotent bootstrap replacing install.sh.
Opt-in `--hooks` and `--graph` flags so the command never mutates
`~/.claude/settings.json` or runs a multi-minute graph build
without explicit consent.
- **Pre-built wiki** shipped as `graph/wiki-graph.tar.gz`:
`entities/skills/*.md` (1,768), `entities/agents/*.md` (443),
`concepts/*.md` (61), `converted/*/` (952), full
`graphify-out/graph.json` + `communities.json`, catalog,
`.obsidian/` vault config.
- **Playbooks** in `docs/`:
- `playbook-real-world.md` — end-to-end PCI-fintech checkout scenario
exercising scan → suggest → load → toolbox council → custom
skill_add → lifecycle archive → KPI render.
- `playbook-live-load-unload.md` — 7-step verification that the
observe → suggest → record → score pipeline is live. Verified in
**5.86 s** end-to-end.
- `playbook-random-load-unload.md` — full lifecycle: pick a random
never-loaded skill, surface via KEYWORD_SIGNALS, load, force
Stop-hook rescore, wait for staleness, queue-for-unload, unload,
verify via `/session/<id>` dashboard timeline.
### Fixed (security — Strix deep scan audit)
- **HIGH — path traversal in `src/import_strix_skills.py`**: manifest
`source_path` + `category` now validated against a strict allowlist
regex and containment-checked via `Path.resolve()` + `relative_to()`
against `IMPORT_ROOT` + `target_dir`.
- **HIGH — backup config path traversal in `src/backup_config.py`**:
`trees[].src` / `trees[].dest` reject `..`, absolute paths, Windows
drive letters, and UNC shares. Malformed entries logged to stderr
and skipped, not silently replaced with defaults.
- **HIGH — git textconv RCE in `src/ctx_lifecycle.py`**:
`_git_diff_preview` now invokes `git log -p` with
`--no-textconv`, `--no-ext-diff`, `-c diff.external=`, and
`-c core.attributesfile=os.devnull` so a hostile repo's
`.gitattributes` can't trigger arbitrary command execution.
- **LOW — `usage_tracker.py --wiki` flag ignored**: the override
now actually threads through `update_skill_page` + `append_wiki_log`
instead of silently writing to the default wiki.
### Fixed (correctness)
- **NetworkX 'links' vs 'edges' schema** (`resolve_graph.py`,
`wiki_visualize.py`, `context_monitor.py`, `wiki_graphify.py`):
readers auto-detect the schema; writer pins `edges="edges"` going
forward. The 642K-edge graph had been silently returning 0 edges
on every consumer since the NetworkX 3.x upgrade.
- **Stop-hook schema wrapper** (`src/inject_hooks.py`):
`quality_on_session_end.py` was registered flat and never
auto-fired on session close. Now wrapped in the `{"hooks":[…]}`
form Claude Code expects.
- **`_set_frontmatter_field` replace-only** (`src/usage_tracker.py`):
silently no-op'd when the field was missing. `session_count`
never persisted on wiki pages that didn't pre-ship with it, so
the staleness gate at `session_count ≥ STALE_THRESHOLD` never
fired. Now inserts missing fields into the frontmatter block.
- **`skill_unload` one-sided event log** (`src/skill_unload.py`):
`unload_from_session` now emits an `unload` line to
`skill-events.jsonl` + a `skill.unloaded` audit row; previously
loads were recorded but unloads weren't.
- **`skill.score_updated` audit rows missing session_id**:
Stop hook now exports `CTX_SESSION_ID` before invoking the
recompute subprocess so the dashboard per-session timeline shows
the middle event of the load → score_updated → unload triad.
- **CI flake on Windows** (`src/_fs_utils.py`): concurrent-writer
retry bumped from 3 × 50ms to 10 × 50ms to absorb AV/indexer
lock contention on windows-latest CI runners.
- **Graph orphaned from recommendations** (`src/resolve_skills.py`):
added fuzzy installed-skill fallback + `resolve_by_seeds` graph
walk with a 1.5 edge-weight noise floor. Manifest now contains
real neighbors instead of `1 load + 1576 unload + 2 warnings`.
- **`context_monitor.KEYWORD_SIGNALS`** extended with `stripe`,
`pci`, `payment`, `postgres`/`psycopg*`/`asyncpg`, `mongodb`,
`pydantic`, and more — fintech/payments projects now fire
pending-skills suggestions.
- **`scan_repo` framework detection** extended across
`stripe`/`paypal`/`plaid` payment deps,
`psycopg*`/`asyncpg`/`mongodb`/`pymongo` datastores,
`pydantic`/`zod`/`yup` validation, and `pytest`/`jest`/`vitest`
from dev-deps (no longer requires a dedicated config file).
- **`scan_repo --output` mkdir-p**: was raising `FileNotFoundError`
when the parent directory didn't exist.
- **`ctx_lifecycle` Windows UnicodeEncodeError**: `main()` now
reconfigures `sys.stdout`/`sys.stderr` to UTF-8 so arrows and
other Unicode in transition descriptions don't crash the cp1252
Windows console.
- **`kpi_dashboard` `.hook-state.json` crash**: the sidecar
iteration now skips internal dotfiles so the strict slug
validator doesn't get fed a `.hook-state` string.
- **`_trigger_matches` Linux-side Windows path normalization**
(`src/toolbox_hooks.py`): now replaces `\\` with `/` unconditionally,
not gated on `os.sep` which was a no-op on Linux runners.
- **Positional slugs for `recompute`** (`src/skill_quality.py`):
`ctx-skill-quality recompute python-patterns` now works; the
subparser was flag-only before.
- **Toolbox templates packaged** (`src/toolbox.py`): all five
starter templates embedded inline so `ctx-toolbox init` seeds
them from the installed wheel (previously the `docs/toolbox/templates/`
directory was not bundled, so init produced `[warn] Template not
found` x 5).
### Changed
- **Package name**: `ctx-skill-quality` → `claude-ctx`. PyPI's `ctx`
namespace is a post-incident tombstone, so `claude-ctx` is the
canonical install name. `pip install claude-ctx` is the only
supported install path.
- **Dashboard UI** (`ctx-monitor`): home page rebuilt from a near-empty
placeholder into a six-card stat grid + two-column session/audit
panels + grade pills that render even with zero data.
- **`/skills` page**: table → responsive card grid with a left filter
sidebar (text search, grade checkboxes, subject_type toggles,
hide-floored). Each card links to `/skill/<slug>` sidecar detail,
`/wiki/<slug>` entity page, and `/graph?slug=<slug>` neighborhood.
- **`resolve_skills.py`** is now load-bearing on the graph: matrix
→ fuzzy fallback → graph-walk augmentation happens in that order,
each stage optional.
### Migration from 0.4.x / pre-PyPI
- Replace `./install.sh python` with `pip install claude-ctx &&
ctx-init --hooks`.
- Replace `python src/<module>.py` invocations with the `ctx-<name>`
console script (see `pyproject.toml [project.scripts]`) or
`python -m <module>`.
- Existing `~/.claude/skill-wiki/graphify-out/graph.json` files in
the NetworkX 2.x "links" schema load transparently — readers auto-
detect. New builds pin `edges="edges"`.
### Release-candidate history
Between the rc1 internal review (2026-04-19) and this GA, ten public
release candidates were cut and published to PyPI: rc1 (broken wheel,
superseded), rc2 (wheel fix — 55 runtime modules), rc3 (positional
slugs + toolbox templates), rc4 (graph wired into resolve_skills +
CI flake fix), rc5 (stack-detection breadth + playbook fixes), rc6
(three Strix HIGH security patches), rc7 (pipeline fixes +
vuln-0004 + audit log), rc8 (`ctx-monitor` + `ctx-init`), rc9 (three
load/unload bugs caught by the random-load playbook), rc10 (live
dashboard with load/unload POST actions + `/logs`), rc11 (rich home
+ `/graph` + `/wiki` + `/skills` sidebar filter).
## [0.5.0-rc1] — 2026-04-19
First open-source release candidate. MIT-licensed, CI-matrixed, and
hardened against the review findings from an internal CTO+CEO council
pass. Full test suite: **1316 passed, 2 skipped**.
### Added
- `LICENSE` — MIT.
- `pyproject.toml` — installable via `pip install -e .` with optional
`[embeddings]` (sentence-transformers) and `[dev]` (pytest/mypy) extras.
- `.github/workflows/test.yml` — matrix CI: ubuntu-latest + windows-latest
× Python 3.11 + 3.12.
- `CONTRIBUTING.md`, issue templates, PR template.
- `src/_fs_utils.py` — canonical `atomic_write_text` / `atomic_write_bytes`
/ `atomic_write_json` with Windows `PermissionError` retry. Replaces
14 local copies across the codebase.
- `src/__init__.py` — `__version__ = "0.5.0-rc1"`.
- Hooks: `quality_on_session_end.py` registered as a Claude Code `Stop`
hook for incremental quality scoring.
- 112 new tests across security, performance benchmarks, JSON integrity,
atomic writes, and edge cases.
### Fixed (security)
- **RCE / shell injection** in `inject_hooks.py`: removed argv
interpolation of `$CLAUDE_TOOL_INPUT` / `$CLAUDE_TOOL_NAME`. Hooks now
consume tool input via `--from-stdin`.
- **Path traversal** in `skill_add_detector.py`: added
`validate_user_supplied_slug` (strict regex) plus `resolve` +
`relative_to` containment check.
- **Path escape** in `skill_telemetry.py`: events file is now anchored to
a `_TRUSTED_ROOT` / `trusted_root` kwarg.
- **Race on concurrent writes**: three files used a predictable
`path.with_suffix(".tmp")` temp filename that clobbers when two writers
race. Replaced with `tempfile.mkstemp` (unique per write).
- **Graph JSON integrity**: `resolve_graph.load_graph` now validates the
schema (`JSONDecodeError`, `NetworkXError`, missing `nodes`/`links`).
- **YAML injection** in `skill_add`: frontmatter is emitted via
`yaml.safe_dump`, not string-concatenated.
- **Markdown cell escaping** in `skill_add_detector` (`_escape_md_cell`).
### Fixed (correctness)
- **Latent bug** in `kpi_dashboard`: `len(bucket)` was being called on a
rebound loop variable rather than the category dict — fixed by
renaming to `cat_bucket`.
- `ctx_lifecycle.observe_score` guard against empty `computed_at`.
- `skill_quality.cmd_list` skips `.lifecycle.json` records.
- `ctx_lifecycle._apply_buckets` checks auto-apply before interactive
prompt.
### Changed
- **Package layout**: `[tool.setuptools] package-dir = {"" = "src"}`.
Removed 18 `sys.path.insert()` hacks across the source tree.
- **Incremental quality scoring**: `skill_quality._build_events_index`
converts `O(N·M)` JSONL re-scans into `O(N+M)` single-pass indexing.
- **Graph build**: `wiki_graphify` gained `DENSE_TAG_THRESHOLD=20` to
skip pathological cliques and a `node_to_community` reverse index
(`O(C²·members)` → `O(C·members)`).
- **Browser visualizer**: `wiki_visualize.js` replaces `NODES.find` in
hot loops with a `Map` (`O(E·N)` → `O(N+E)`).
- `QualitySink` protocol extracted in `skill_quality.py` with three
concrete sinks: `SidecarSink`, `WikiFrontmatterSink`, `WikiBodySink`.
- Slug validation tiers documented: `wiki_utils.SAFE_NAME_RE` (lenient,
legacy) vs `skill_add_detector.validate_user_supplied_slug` (strict,
new input).
- `sidecar_dir`, `skills_dir`, `agents_dir`, `wiki_dir` now read from
`src/config.json`.
### Developer experience
- `mypy --strict` clean on `_fs_utils.py`, `wiki_utils.py`. 28→0 mypy
errors cleared in `scan_repo.py`, `kpi_dashboard.py`,
`intent_interview.py`.
- `__all__` exports on `wiki_utils.py` and `_fs_utils.py`.
- 5 dead imports removed (`os`, `Mapping`, `timedelta` from
`ctx_lifecycle`; `Path` from `intake_gate`, `intake_pipeline`).
[0.5.1]: https://github.com/stevesolun/ctx/releases/tag/v0.5.1
[0.5.0]: https://github.com/stevesolun/ctx/releases/tag/v0.5.0
[0.5.0-rc1]: https://github.com/stevesolun/ctx/releases/tag/v0.5.0-rc11234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677# Contributing to ctx
Thank you for your interest in contributing.
## Dev environment setup
```bashgit clone https://github.com/stevesolun/ctx && cd ctxpython -m venv .venvsource .venv/bin/activate # Windows: .venv\Scripts\activatepip install -e ".[dev]"```
To also run the similarity/embedding tests (requires ~100 MB model download):
```bashpip install -e ".[dev,embeddings]"```
## Running tests
```bashpytest -q # fast suite (skips integration)pytest -q -m 'not integration' # same, explicitpytest -q -m integration # embedding precision/recall testspytest --cov=src -q # with coverage report```
## Code style
Both **ruff** and **mypy** must pass before a PR is merged.
```bashruff check src/ # lintingruff format --check src/ # formatting checkmypy src/ # type checking```
Fix formatting in one shot:
```bashruff format src/ruff check --fix src/```
## Commit conventions
This repo uses [Conventional Commits](https://www.conventionalcommits.org/):
```feat: new featurefix: bug fixrefactor: code restructuring without behaviour changedocs: documentation onlytest: test additions or correctionschore: maintenance (deps, CI, tooling)perf: performance improvementci: CI/CD changes```
Scope is optional but encouraged, e.g. `feat(intake): add fuzzy-match gate`.
## Reporting bugs
Open an issue at <https://github.com/stevesolun/ctx/issues>. Include:
- Python version and OS- Full traceback- Minimal reproduction steps
## Pull request process
1. Fork the repo and create a feature branch from `main`.2. Make your changes. Add or update tests — the CI gate requires the existing suite to pass.3. Ensure `ruff` and `mypy` pass locally.4. Open a PR against `main`. Fill in the PR template.5. A maintainer will review and merge once CI is green.123456789101112131415161718192021MIT License
Copyright (c) 2026 Steve Solun
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485# ctx — Skill, Agent, MCP & Harness Recommendation
[](LICENSE)
[](https://python.org)
[](https://pypi.org/project/claude-ctx/)
[](#)
[](graph/)
[](https://stevesolun.github.io/ctx/)
Watches what you develop, walks a graph that combines **92,815 skills, 464 agents, 10,786 MCP servers, and cataloged harnesses**, and recommends the right bundle on the fly. The skill count includes 1,969 curated ctx skills plus 90,846 remote-cataloged Skills.sh skill nodes with upstream `npx skills` install instructions, duplicate hints, and metadata-only quality/security signals. You approve what loads, installs, or gets adopted. Powered by a Karpathy LLM wiki with persistent memory that gets smarter every session.
> **2026-04-29 updates.**
> - Added the curated `find-skills` workflow, backed by the canonical upstream install command `npx skills add https://github.com/vercel-labs/skills --skill find-skills`.
> - Shipped 90,846 Skills.sh entries as first-class remote-cataloged `skill` nodes inside `graph/wiki-graph.tar.gz` and as `graph/skills-sh-catalog.json.gz`.
> - Added security/cyber review warnings to entity update reviews and documented the graph/wiki update procedure.
> **2026-04-27 updates.**
> - Imported [mattpocock/skills](https://github.com/mattpocock/skills) — 21 opinionated skills (TDD, domain-model, ubiquitous-language, github-triage, caveman compression mode, write-a-skill, plus 15 more) deployed under the `mattpocock-` prefix. See [`imported-skills/mattpocock/ATTRIBUTION.md`](imported-skills/mattpocock/ATTRIBUTION.md).
> - Imported [designdotmd.directory](https://designdotmd.directory) — 156 DESIGN.md files (visual identities: color tokens, typography, spacing, components + rationale) deployed under the `designdotmd-` prefix. These are reference designs an agent can read when asked to build a UI. See [`imported-skills/designdotmd/ATTRIBUTION.md`](imported-skills/designdotmd/ATTRIBUTION.md).
> - Skill total: 1,791 → **1,968** (+177).
## Why it exists
- **Discovery** — with 92K+ skill nodes, 460+ agents, 10K+ MCP servers, and cataloged harnesses, you can't possibly know which exist or which apply to your current work.
- **Context budget** — loading everything wastes tokens and degrades quality. You need the right 10–15 per session.
- **Skill rot** — skills you installed months ago and never used are cluttering context. Stale ones should be flagged automatically.
## Install
```bash
pip install claude-ctx
ctx-init # terminal wizard: hooks, graph, model, harness goal
ctx-init --wizard # force the same wizard from scripts/tests
ctx-init --model-mode skip # non-interactive setup for automation
ctx-init --model-mode custom --model openai/gpt-5.5 --goal "build a CAD agent"
```
Optional extras: `pip install "claude-ctx[embeddings]"` for the semantic backend, `pip install "claude-ctx[dev]"` for the test toolchain.
### Pre-built knowledge graph (optional)
A pre-built knowledge graph of 104,066 nodes and 1,031,011 edges ships as a tarball. The same tarball includes `external-catalogs/skills-sh/catalog.json`, 90,846 remote-cataloged Skills.sh skill pages under `entities/skills/skills-sh-*.md`, and the first cataloged harness page under `entities/harnesses/`. Extract to get a ready-to-use `~/.claude/skill-wiki/`:
```bash
# after `git clone` — or download graph/wiki-graph.tar.gz from the GitHub release
mkdir -p ~/.claude/skill-wiki
tar xzf graph/wiki-graph.tar.gz -C ~/.claude/skill-wiki/
```
> **Windows / Git-Bash / MSYS:** pass `--force-local` so `tar` doesn't read the `c:` in the path as a remote host: `tar --force-local xzf graph/wiki-graph.tar.gz -C ~/.claude/skill-wiki/`. Linux/macOS users can ignore.
## Use
After install, the `ctx` hooks integrate automatically with Claude Code's `PostToolUse` + `Stop` events. Typical flow:
```bash
ctx-scan-repo --repo . # scan current repo and stack signals
ctx-scan-repo --repo . --recommend # include skill/agent/MCP/harness recommendations
ctx-agent-add --agent-path ./code-reviewer.md --name code-reviewer
ctx-harness-add --repo https://github.com/earthtojake/text-to-cad --tag cad
ctx-harness-install text-to-cad --dry-run # inspect before cloning/running anything
ctx-harness-install text-to-cad --update --dry-run
ctx-harness-install text-to-cad --uninstall --dry-run
ctx-skill-quality list # four-signal quality score for every skill
ctx-skill-quality explain python-patterns # drill into a single skill
ctx-skill-health dashboard # structural health + drift detection
ctx-toolbox run --event pre-commit # run a council on the current diff
ctx-monitor serve # local dashboard: http://127.0.0.1:8765/
```
The **`ctx-monitor`** dashboard shows currently loaded skills, agents, and MCP servers with load/unload buttons, a cytoscape graph view (`/graph?slug=…`), the LLM-wiki entity browser (`/wiki/<slug>`), a filterable skills grid, a session timeline, an audit log viewer, and a live SSE event stream. Dashboard harness exposure is not yet present; harnesses are cataloged and recommended through the CLI/API surfaces.
When `ctx-skill-add`, `ctx-agent-add`, `ctx-mcp-add`, or `ctx-harness-add`
finds an existing entity, ctx prints a benefits/risks update review and skips
replacement by default. Re-run with `--update-existing` to apply the catalog or
local asset update after review.
Step-by-step entity onboarding:
**<https://stevesolun.github.io/ctx/entity-onboarding/>**
Full docs, architecture, and every module: **<https://stevesolun.github.io/ctx/>**
## License
MIT — see [LICENSE](LICENSE).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690---name: skill-routerdescription: "Repo-aware skill and plugin manager. Scans the user's active repository, identifies the tech stack, frameworks, and workflows in use, then loads ONLY the relevant skills, plugins, and MCP servers -- unloading everything else to keep the context clean. Maintains a persistent LLM Wiki catalog of all available skills, plugins, and marketplaces so decisions are informed and consistent across sessions. Use this skill whenever the user opens a project, switches repos, asks 'what skills do I need', mentions context bloat or slow responses, asks to manage/list/add/remove skills or plugins, or references their skill catalog/wiki. Also triggers on: 'scan my repo', 'what tools do I need for this project', 'clean up my skills', 'too many plugins loaded', 'optimize my context', or any repo-switch event."---
# Skill Router
Scan a repo. Know what it needs. Load only that. Maintain a wiki of everything available.
## Problem
Every skill, plugin, and MCP server loaded into context costs tokens and attention.Most projects need 3-8 skills out of 30+. Loading all of them:- Wastes context window on irrelevant instructions- Causes skill misfires (wrong skill triggers for a task)- Slows response time- Creates conflicting instructions between skills
## Architecture
```skill-router/├── SKILL.md # This file -- orchestration logic├── references/│ ├── stack-signatures.md # File/config patterns mapped to stack identifiers│ ├── skill-stack-matrix.md # Which skills serve which stacks│ └── marketplace-registry.md # Known marketplaces and how to query them└── scripts/ ├── scan_repo.py # Repo scanner -- outputs stack profile JSON ├── resolve_skills.py # Maps stack profile to skill set └── wiki_sync.py # Syncs scan results into the wiki```
The skill router has two halves:1. **The Scanner** -- analyzes a repo and produces a stack profile2. **The Wiki** -- persistent catalog of all available skills/plugins/marketplaces, maintained via the Karpathy LLM Wiki pattern
## Session Startup (CRITICAL -- do this every time)
When this skill activates, follow this sequence:
### Step 1: Orient from the Wiki
```bashWIKI="${SKILL_ROUTER_WIKI:-$HOME/skill-wiki}"if [ -d "$WIKI" ]; then # Existing wiki -- orient first cat "$WIKI/SCHEMA.md" cat "$WIKI/index.md" tail -30 "$WIKI/log.md"else # No wiki yet -- will initialize after first scan echo "No skill wiki found. Will initialize on first scan."fi```
### Step 2: Scan the Active Repo
```bashpython /path/to/scripts/scan_repo.py --repo "$REPO_PATH" --output /tmp/stack-profile.json```
### Step 3: Resolve and Load
```bashpython /path/to/scripts/resolve_skills.py \ --profile /tmp/stack-profile.json \ --wiki "$WIKI" \ --available-skills /mnt/skills/ \ --output /tmp/skill-manifest.json```
### Step 4: Apply the Manifest
Load skills in the manifest. Unload everything else. Report what changed.
---
## The Scanner
### What It Detects
The scanner reads repo structure and files to produce a **stack profile** -- a JSONdocument describing everything the project uses. Detection is evidence-based: everyclaim maps to a file or pattern that proves it.
#### Detection Categories
**1. Languages**- Primary language(s) by file count and LOC- Evidence: file extensions, shebangs, `*.lock` files
**2. Frameworks & Libraries**- Web frameworks (React, Vue, Angular, Next.js, FastAPI, Django, Express, etc.)- ML/AI frameworks (PyTorch, TensorFlow, LangChain, LlamaIndex, CrewAI, etc.)- Mobile (React Native, Flutter, Swift, Kotlin)- Evidence: `package.json` deps, `requirements.txt`, `pyproject.toml`, `Cargo.toml`, `go.mod`, import statements in entry files
**3. Infrastructure & DevOps**- Containerization: Dockerfile, docker-compose.yml, .containerignore- CI/CD: `.github/workflows/`, `.gitlab-ci.yml`, `Jenkinsfile`, `.circleci/`- IaC: Terraform (`*.tf`), Pulumi, CDK, CloudFormation, Ansible- Cloud: AWS (SAM, CDK, `.aws/`), GCP, Azure config files- K8s: `k8s/`, `helm/`, `kustomization.yaml`- Evidence: config files, directory names
**4. Data & Storage**- Databases: migrations dir, ORM configs (Prisma, SQLAlchemy, TypeORM, Drizzle)- Message queues: Kafka, RabbitMQ, Redis configs- Data pipelines: Airflow DAGs, dbt, Spark configs- Evidence: connection strings (redacted), migration files, schema files
**5. Documentation & Content**- Docs generators: MkDocs, Docusaurus, Sphinx, VitePress- Content: markdown collections, MDX, RST- API specs: OpenAPI/Swagger YAML/JSON, GraphQL schemas- Evidence: config files, directory structure
**6. Testing & Quality**- Test frameworks: pytest, Jest, Vitest, Cypress, Playwright- Linting: ESLint, Prettier, Ruff, Black, Clippy- Type checking: TypeScript config, mypy, pyright- Evidence: config files, test directories
**7. AI/Agent Tooling**- MCP servers: `mcp.json`, `.mcp/`, server configs- Agent frameworks: LangGraph, CrewAI, AutoGen, Semantic Kernel- Prompt management: prompt files, template dirs- Model configs: `.env` with API keys (names only, never values), model references- Evidence: config files, import patterns
**8. Build & Package**- Build tools: Webpack, Vite, esbuild, Turbopack, Bazel- Package managers: npm, yarn, pnpm, pip, poetry, cargo, go modules- Monorepo tools: Nx, Turborepo, Lerna, workspace configs- Evidence: config files, lock files
### Stack Profile Schema
```json{ "repo_path": "/absolute/path", "scanned_at": "ISO-8601", "languages": [ { "name": "python", "confidence": 0.95, "evidence": ["pyproject.toml", "87 .py files", "poetry.lock"], "version_hint": ">=3.11 (pyproject.toml python_requires)" } ], "frameworks": [ { "name": "fastapi", "category": "web", "confidence": 0.99, "evidence": ["pyproject.toml dependency", "main.py imports FastAPI"] } ], "infrastructure": [ { "name": "docker", "confidence": 1.0, "evidence": ["Dockerfile", "docker-compose.yml"] } ], "data_stores": [], "testing": [], "ai_tooling": [], "build_system": [], "docs": [], "project_type": "api-service", "monorepo": false, "workspace_packages": [], "custom_signals": {}}```
### Scanning Rules
1. **Never read file contents unless necessary.** Start with directory listing and filenames. Only open files when you need to disambiguate (e.g., is this React or Preact? Check the import in the entry file).
2. **Confidence scoring:** - 1.0 = definitive (lock file, explicit config) - 0.8-0.99 = strong (dependency listed, config present) - 0.5-0.79 = probable (file patterns match, no explicit config) - <0.5 = speculative (mention in README, commented-out code) -- do not include
3. **Depth limits:** - Directory tree: 3 levels deep max for initial scan - `node_modules/`, `.git/`, `__pycache__/`, `venv/`, `.venv/`: skip entirely - For monorepos, scan each workspace package as a sub-profile
4. **Performance budget:** The scan should complete in under 10 seconds for repos up to 10K files. Use `find` with exclusions, not recursive `ls`.
5. **Version detection:** Extract version constraints from config files when available. This helps select skill variants (e.g., React 18 vs React 19 patterns differ).
---
## The Resolver
The resolver takes a stack profile and produces a **skill manifest** -- the exact setof skills, plugins, and MCP servers to load.
### Resolution Algorithm
```1. For each detected stack element (language, framework, infra, etc.): a. Look up in skill-stack-matrix.md which skills serve this element b. Check the wiki for any user-configured overrides or preferences c. Add to candidate set with priority score
2. Deduplicate: - If two skills cover the same capability, prefer the more specific one - Example: generic "python" skill vs "fastapi" skill -- keep fastapi, drop generic python
3. Check for required companions: - Some skills require others (e.g., "docker" skill needs "dockerfile-lint" if Dockerfile exists) - Read companion rules from skill-stack-matrix.md
4. Check for conflicts: - Some skills conflict (e.g., two different CSS-in-JS skills) - Resolve by: user preference (wiki) > specificity > recency
5. Apply user overrides: - Wiki pages in entities/ may have "always_load: true" or "never_load: true" flags - These override the algorithm
6. Produce the manifest```
### Skill Manifest Schema
```json{ "generated_at": "ISO-8601", "repo_path": "/absolute/path", "profile_hash": "sha256 of stack profile", "load": [ { "skill": "fastapi", "path": "/mnt/skills/public/fastapi/SKILL.md", "reason": "FastAPI detected in pyproject.toml dependencies", "priority": 1 } ], "unload": [ { "skill": "react", "reason": "No frontend framework detected in repo" } ], "mcp_servers": [ { "name": "github", "url": "https://github.mcp.example.com", "reason": ".github/ directory with workflows detected" } ], "plugins": [], "warnings": [ "Detected Terraform but no terraform skill is installed. Consider adding one." ], "suggestions": [ { "skill": "openapi-generator", "reason": "OpenAPI spec found at api/openapi.yaml but no API generation skill loaded", "install_from": "marketplace:anthropic/openapi-gen" } ]}```
### Priority Scoring
Skills are ordered by priority so the most relevant instructions appear first in context:
| Signal | Priority Boost ||---|---|| Framework detected with confidence >= 0.9 | +10 || User marked "always_load" in wiki | +20 || Skill used in last 3 sessions (from wiki log) | +5 || Skill covers primary language | +8 || Skill covers secondary tooling (linting, testing) | +3 || Skill is generic/fallback | +1 |
---
## The Wiki (Persistent Catalog)
The skill router maintains a wiki following the Karpathy LLM Wiki pattern. This isthe router's long-term memory -- it tracks what's available, what's been used, andwhat the user prefers.
### Wiki Location
Default: `~/skill-wiki` (configurable via `skills.config.wiki.path`)
### Wiki Structure
```skill-wiki/├── SCHEMA.md # Conventions for this wiki domain├── index.md # Catalog of all pages├── log.md # Action log (scans, loads, installs)├── raw/ # Layer 1: Immutable source data│ ├── scans/ # Historical stack profile JSONs│ └── marketplace-dumps/ # Cached marketplace listings├── entities/ # Layer 2: One page per skill/plugin/MCP server│ ├── skills/│ ├── plugins/│ └── mcp-servers/├── concepts/ # Layer 2: Stack patterns, best practices├── comparisons/ # Layer 2: Skill-vs-skill analyses└── queries/ # Layer 2: Resolved decision records```
### SCHEMA.md for the Skill Wiki
```markdown# Skill Wiki Schema
## DomainCatalog and management of all available skills, plugins, MCP servers, andmarketplace sources for the agent development environment. Tracks what exists,what's been used, what works well, and user preferences.
## Conventions- File names: lowercase, hyphens, no spaces- Every page starts with YAML frontmatter- Use [[wikilinks]] between pages (min 2 outbound per page)- Bump `updated` on every change- Every new page goes in index.md- Every action appends to log.md
## Frontmatter for Entity Pages (Skills/Plugins/MCP)
```yaml --- title: Skill Name created: YYYY-MM-DD updated: YYYY-MM-DD type: skill | plugin | mcp-server | marketplace status: installed | available | deprecated | broken tags: [from taxonomy] source: local | marketplace-name | github-url path: /mnt/skills/public/skill-name/SKILL.md stacks: [python, fastapi, docker] always_load: false never_load: false last_used: YYYY-MM-DD use_count: 0 avg_session_rating: null notes: "" --- ```
## Tag Taxonomy- Stack: python, javascript, typescript, rust, go, java, ruby, swift, kotlin- Framework: react, vue, angular, nextjs, fastapi, django, express, flask- Infra: docker, kubernetes, terraform, ci-cd, aws, gcp, azure- Data: sql, nosql, redis, kafka, spark, dbt, airflow- AI: llm, agents, mcp, langchain, embeddings, fine-tuning, rag- Quality: testing, linting, typing, security, performance- Docs: documentation, api-spec, markdown, diagrams- Meta: comparison, decision, pattern, troubleshooting- Management: marketplace, registry, versioning, compatibility
## Page Thresholds- Create a page when a skill/plugin/MCP server is discovered (installed or available)- Update usage/configuration metadata when the local user changes preferences- When a new version or replacement content is found, emit an update review first; do not replace the entity by default- Archive when deprecated or superseded with a note pointing to the replacement
## Update Policy- New version of a skill, agent, MCP server, or harness: compare the existing entity/local asset with the proposed replacement, list benefits and risks, and require the explicit update flag before replacing content- Skill conflict discovered: create a comparison page, update both entity pages- User preference expressed: update entity frontmatter (always_load/never_load)```
### Entity Page Template (Skill)
```markdown---title: FastAPI Skillcreated: 2026-04-08updated: 2026-04-08type: skillstatus: installedtags: [python, fastapi, web]source: localpath: /mnt/skills/public/fastapi/SKILL.mdstacks: [python, fastapi]always_load: falsenever_load: falselast_used: 2026-04-07use_count: 12avg_session_rating: 4.5notes: "Works well for API scaffolding. Occasionally suggests Pydantic v1 patterns."---
# FastAPI Skill
## OverviewGenerates FastAPI applications, routes, middleware, and deployment configs.
## Capabilities- Scaffold new FastAPI projects- Generate route handlers with Pydantic models- Add middleware (CORS, auth, rate limiting)- Generate OpenAPI spec customizations- Docker + uvicorn deployment configs
## Stack AffinityPrimary: [[python]], [[fastapi]]Secondary: [[docker]], [[openapi]]Companions: [[pydantic-skill]] (recommended), [[sqlalchemy-skill]] (if DB detected)Conflicts: [[flask-skill]] (overlapping web framework)
## Usage History| Date | Repo | Outcome ||------|------|---------|| 2026-04-07 | /home/user/api-project | Generated 12 routes, good || 2026-03-29 | /home/user/microservice | Scaffold + Docker, good |
## Known Issues- Suggests `from pydantic import BaseModel` without checking if v2 `model_validator` is needed- Does not handle GraphQL integration (use [[graphql-skill]] instead)
## Sources- [[raw/marketplace-dumps/anthropic-marketplace-2026-04.md]]```
### Marketplace Integration
The wiki tracks marketplace sources so the router can suggest skills the userdoesn't have yet.
#### Marketplace Entity Page
```markdown---title: Anthropic Marketplacecreated: 2026-04-08updated: 2026-04-08type: marketplacestatus: activetags: [marketplace, registry]url: https://marketplace.anthropic.com/skillsrefresh_interval_days: 7last_refreshed: 2026-04-08---
# Anthropic Marketplace
## OverviewOfficial skill marketplace maintained by Anthropic.
## How to Query- API: GET /api/v1/skills?stack=python&category=web- CLI: `hermes marketplace search --query "fastapi"`
## Cached ListingsSee [[raw/marketplace-dumps/anthropic-marketplace-2026-04.md]]
## Install Command`hermes skill install marketplace:anthropic/<skill-name>````
#### Marketplace Refresh
When the router detects a stack element with no matching installed skill:1. Check marketplace entity pages for `last_refreshed`2. If stale (> `refresh_interval_days`), re-query the marketplace3. Save new listing dump to `raw/marketplace-dumps/`4. Create entity pages for newly discovered skills; existing pages require an update review and explicit update flag before replacement5. Include in the manifest's `suggestions` array
---
## Core Operations
### 1. Full Scan (repo switch or first run)
Triggers: user opens a new project, says "scan my repo", switches working directory
```① Read wiki orientation (SCHEMA, index, recent log)② Run scan_repo.py on the target repo③ Save scan result to raw/scans/scan-YYYY-MM-DD-reponame.json④ Run resolve_skills.py with the profile + wiki⑤ Present the manifest to the user: - "Loading: [list with reasons]" - "Unloading: [list]" - "Suggestions: [skills you don't have but might want]" - "Warnings: [gaps detected]"⑥ On user confirmation, apply the manifest⑦ Update wiki: - Bump last_used and use_count on loaded skill entity pages - Create entity pages for any newly discovered skills - Append to log.md⑧ Update index.md if new pages were created```
### 2. Incremental Scan (file changes during session)
Triggers: user creates a new config file, adds a dependency, installs a package
The router watches for signals that the stack changed mid-session:- New `Dockerfile` created -> check if docker skill is loaded- `package.json` modified -> re-scan dependencies- New `.github/workflows/` file -> check CI/CD skills- New `*.tf` files -> check terraform skill
For incremental scans:```① Re-scan only the changed area (single file or directory)② Diff against the current manifest③ If new skills needed: "I noticed you added [X]. Want me to load the [Y] skill?"④ If skills can be unloaded: "You removed [X]. I can unload the [Y] skill to free context."⑤ Apply changes on confirmation⑥ Log the incremental update```
### 3. Manual Override
Users can force-load or force-unload skills:
- "Always load the docker skill" -> set `always_load: true` in wiki entity page- "Never load the react skill" -> set `never_load: true` in wiki entity page- "Load the terraform skill for this session" -> temporary load, no wiki change- "What skills am I running?" -> show current manifest with reasons
### 4. Skill Discovery
When the user asks "what skills exist for X" or "is there a skill for Y":
```① Search wiki entity pages for matching tags/stacks② If found: show the entity page summary, status, and rating③ If not found: query marketplace entity pages④ If marketplace has it: suggest installation with command⑤ If nowhere: note the gap, suggest creating a custom skill⑥ Log the query```
### 5. Wiki Maintenance (Lint)
Runs the standard LLM Wiki lint plus skill-specific checks:
- **Stale skills**: entity pages with `last_used` > 90 days- **Ghost skills**: entity pages with `status: installed` but path doesn't exist- **Orphan skills**: installed skills with no entity page in the wiki- **Marketplace staleness**: marketplaces not refreshed within their interval- **Conflict detection**: skills with overlapping `stacks` that are both `always_load`- **Usage cold spots**: skills with `use_count: 0` after 30+ days -- suggest removal- Standard wiki lint: orphan pages, broken links, index completeness, frontmatter validation
---
## Integration with Karpathy LLM Wiki
This skill extends the LLM Wiki pattern. If the user also has a general-purposeknowledge wiki (separate from the skill wiki), the two coexist:
- **Skill wiki** (`~/skill-wiki`): managed by skill-router, tracks tooling- **Knowledge wiki** (`~/wiki`): managed by llm-wiki skill, tracks domain knowledge
Cross-references between wikis use full paths: `[[~/wiki/concepts/rag.md|RAG]]`rather than bare wikilinks (which resolve within the same wiki).
The skill-router's wiki follows all LLM Wiki conventions:- Three-layer architecture (raw / entities-concepts / schema)- Frontmatter on every page- Tag taxonomy in SCHEMA.md- Append-only log with rotation- Lint for consistency- Obsidian-compatible wikilinks
The key extension is the **entity frontmatter** -- skill/plugin/MCP pages carryoperational metadata (status, path, stacks, always_load, use_count) that theresolver reads programmatically. This is what makes the wiki active rather thanpassive -- it doesn't just store knowledge, it drives loading decisions.
---
## Reporting
After every scan, the router produces a concise report:
```## Skill Router Report -- [repo-name]Scanned: YYYY-MM-DD HH:MM
### Stack Profile- Languages: Python 3.11, TypeScript 5.4- Frameworks: FastAPI, React 18- Infra: Docker, GitHub Actions- Data: PostgreSQL (SQLAlchemy), Redis- AI: LangChain, MCP (2 servers configured)
### Loaded (6 skills)1. fastapi (confidence: 0.99) -- pyproject.toml2. react (confidence: 0.95) -- package.json3. docker (confidence: 1.0) -- Dockerfile4. sqlalchemy (confidence: 0.9) -- alembic/5. langchain (confidence: 0.85) -- imports in agent.py6. github-actions (confidence: 1.0) -- .github/workflows/
### Unloaded (24 skills)[collapsed list]
### Suggestions- openapi-generator: OpenAPI spec found but no generation skill- redis-skill: Redis connection in docker-compose but no Redis skill
### Warnings- No testing skill loaded but pytest.ini exists -- add pytest skill?```
---
## Handling Edge Cases
**Monorepos**: Scan each workspace package separately. Produce a merged manifestthat includes skills for all packages, with per-package annotations.
**Empty repos**: Report "No stack detected. This looks like a new project."Ask what the user plans to build, then suggest a starter skill set.
**Conflicting signals**: If the repo has both `requirements.txt` AND `package.json`,it's a polyglot project. Load skills for both stacks. Note: confidence drops iffiles look abandoned (empty, very old timestamps).
**Skill not found**: If the resolver identifies a need but no skill exists for it,log a gap in the wiki and include in `warnings`. Suggest marketplace search orcustom skill creation.
**User disagrees with scan**: "No, I don't use React anymore, that's legacy code."Mark react skill as `never_load` in wiki, note the reason. The scan still sees thefiles but the override takes precedence.
---
## Configuration
In `~/.hermes/config.yaml` (or equivalent agent config):
```yamlskills: config: skill-router: wiki_path: ~/skill-wiki auto_scan: true # Scan on repo switch auto_load: false # Require confirmation before loading scan_depth: 3 # Directory depth for initial scan marketplace_refresh: 7 # Days between marketplace cache refresh max_loaded_skills: 15 # Hard cap on simultaneous skills incremental_watch: true # Monitor file changes mid-session report_verbosity: normal # minimal | normal | verbose```
---
## Pitfalls
- **Never skip wiki orientation.** Reading SCHEMA + index + log before acting prevents duplicates and missed context. This is the #1 cause of wiki degradation.- **Never load all skills "just in case."** The whole point is selective loading. If the user needs something unexpected, incremental scan catches it.- **Never modify raw/ files.** Scan results and marketplace dumps are immutable records.- **Always confirm before loading/unloading.** Unless `auto_load: true` is configured.- **Don't over-scan.** Reading every file in a 50K-file monorepo is wasteful. Use directory structure and config files first, open source files only to disambiguate.- **Keep entity pages current.** A stale wiki is worse than no wiki -- it makes wrong loading decisions. Run lint monthly.- **Respect `never_load`.** User overrides are sacrosanct. Don't re-suggest skills the user has explicitly rejected (unless they ask).- **Log everything.** The log is how the router learns patterns across sessions. "Last 3 times this repo was opened, the user also loaded X" is valuable signal.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224# Change-triggered backup — hook install
One page on wiring the `backup_on_change.py` PostToolUse hook into Claude
Code so a new snapshot fires automatically whenever you edit a tracked
config file (`~/.claude/settings.json`, agents, skills, top-level
manifests, etc.).
## What it does
On every `Edit` / `Write` / `MultiEdit` tool call, the hook:
1. Reads the tool payload from stdin.
2. Resolves `tool_input.file_path` and checks if it sits under
`~/.claude` in a file/tree/memory path tracked by `BackupConfig`.
3. If tracked, shells out to
`python <repo>/src/backup_mirror.py snapshot-if-changed --reason <tool>:<basename>`.
4. `snapshot-if-changed` hashes every tracked file, compares against the
most recent snapshot's `manifest.json`, and only creates a new folder
when at least one SHA differs.
No-op edits don't create folders. The hook always exits 0 so a bug in
the backup layer cannot stall a Claude session.
## Register the hook
Edit `~/.claude/settings.json` and add the following under `hooks` (keep
any existing entries alongside it). Replace `<REPO>` with the absolute
path to this checkout — on Windows this is a path like
`C:/Steves_Files/Work/Research_and_Papers/ctx`.
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write|MultiEdit",
"hooks": [
{
"type": "command",
"command": "python <REPO>/hooks/backup_on_change.py"
}
]
}
]
}
}
```
Notes:
- The `matcher` is a regex against the tool name — the three names above
are the only tools that touch files.
- Use forward slashes in the path even on Windows.
- If `python` on your PATH is not the interpreter you want, give the
absolute path instead (e.g.
`C:/Users/you/.pyenv/pyenv-win/versions/3.13.2/python.exe`).
## Verify it works
1. Reload Claude Code (the hook registration is read at session start).
2. Edit a tracked file, e.g. `~/.claude/CLAUDE.md`.
3. Watch `~/.claude/backups/` — a new folder named
`<timestamp>__edit-claude-md` should appear within a second.
4. Edit the same file again with identical content — no new folder
appears (SHA is unchanged).
If nothing shows up, run the verb manually to isolate the failure:
```bash
python -m backup_mirror snapshot-if-changed --reason smoke-test --json
```
The JSON output tells you which files the detector considered new,
changed, or removed.
## What gets backed up
See `src/backup_config.py` and the `backup` section of
`src/config.json` for the current defaults:
- **top_files** — `settings.json`, `skill-manifest.json`,
`pending-skills.json`, `CLAUDE.md`, `AGENTS.md`, `user-profile.json`,
`skill-system-config.json`, `skill-registry.json`.
- **trees** — `agents/`, `skills/`.
- **memory** — `projects/*/memory/**` when `memory_glob` is true.
- **always excluded** — `.credentials.json`, `claude.json`, token
caches; these are dropped even if a user config lists them.
To override per user, drop a partial config at
`~/.claude/backup-config.json`. Fields you omit fall back to the repo
default. Example:
```json
{
"retention": { "keep_latest": 100 },
"top_files": ["settings.json", "CLAUDE.md"]
}
```
## Manual CLI
The same verb is available as a one-shot command:
```bash
# snapshot only when something changed
python -m backup_mirror snapshot-if-changed --reason manual-check
# force an unconditional snapshot with a reason label
python -m backup_mirror create --reason pre-upgrade
```
Both land under `~/.claude/backups/<timestamp>__<reason>/` and write a
`manifest.json` that records the reason alongside every file's SHA-256.
## Watchdog — snapshot on changes outside a Claude session
The PostToolUse hook only fires on `Edit` / `Write` / `MultiEdit` tool
calls *inside* a Claude session. If you edit `~/.claude/settings.json`
in VS Code, or a `git pull` updates an agent file, the hook never
sees it.
For that gap, run the polling watchdog — a simple loop that calls
`snapshot-if-changed` every N seconds:
```bash
python -m backup_mirror watchdog --interval 60
```
Flags:
| Flag | Meaning |
| --- | --- |
| `--interval N` | Seconds between polls. Clamped to `[5, 3600]`. Default 60. |
| `--reason-prefix LBL` | Prefix used for each snapshot's `--reason` label. Default `watchdog`. |
| `--once` | Run exactly one tick and exit. Useful for cron / Task Scheduler. |
| `--json` | Emit run stats as JSON on exit. |
Because change detection is SHA-gated, polling is cheap — a tick with
no real changes does zero disk writes.
### Running it as a background service
Ready-to-use service manifests live under
[`docs/services/`](https://github.com/stevesolun/ctx/tree/main/docs/services).
Each one expects you to edit a handful of paths — there's no installer
that guesses where you keep the checkout.
- **Linux (systemd user unit)** —
[`docs/services/systemd/claude-backup-watchdog.service`](https://github.com/stevesolun/ctx/blob/main/docs/services/systemd/claude-backup-watchdog.service).
Copy to `~/.config/systemd/user/`, set `CTX_REPO`, then
`systemctl --user enable --now claude-backup-watchdog.service`.
- **macOS (launchd agent)** —
[`docs/services/macos/com.claude.backup.watchdog.plist`](https://github.com/stevesolun/ctx/blob/main/docs/services/macos/com.claude.backup.watchdog.plist).
Edit the `ProgramArguments` paths, drop into
`~/Library/LaunchAgents/`, then
`launchctl load -w ~/Library/LaunchAgents/com.claude.backup.watchdog.plist`.
- **Windows (Task Scheduler installer)** —
[`docs/services/windows/install-backup-watchdog.ps1`](https://github.com/stevesolun/ctx/blob/main/docs/services/windows/install-backup-watchdog.ps1).
Run `pwsh -File docs/services/windows/install-backup-watchdog.ps1`
from the repo root; it detects Python on PATH, registers a
`ClaudeBackupWatchdog` scheduled task that runs at logon, and kicks
off the first tick. `-Uninstall` removes it.
All three manifests assume the watchdog runs as an **unprivileged
user** — no admin/root — because it only reads `~/.claude/` and writes
`~/.claude/backups/`.
The watchdog stops cleanly on SIGINT/SIGTERM, flushes its stats line
to stderr, and exits 0. Pair it with the hook: the hook handles
in-session edits in real time; the watchdog catches everything else.
## Retention — how old snapshots get pruned
Auto-pruning runs after every successful `snapshot-if-changed`, so the
hook cannot fill the disk. The active policy comes from
`BackupRetention` in `src/backup_config.py` (or your user override):
| Field | Default | Meaning |
| --- | --- | --- |
| `keep_latest` | `50` | Always keep the N most-recent snapshots. |
| `keep_daily` | `14` | For the M most-recent UTC days that have snapshots, keep the newest snapshot from each. |
A snapshot survives the sweep iff it's in the **union** of those two
sets. Snapshots whose `manifest.json` has a missing or zero
`created_at` are always protected — we never silently delete something
we can't place in time.
To override per user, add a partial config at
`~/.claude/backup-config.json`:
```json
{
"retention": { "keep_latest": 100, "keep_daily": 30 }
}
```
### Manual prune
```bash
# Dry-run the configured policy — no deletions, JSON report.
python -m backup_mirror prune --policy --dry-run --json
# Apply the configured policy for real.
python -m backup_mirror prune --policy
# Legacy mode (still works): keep only the N newest.
python -m backup_mirror prune --keep 20
```
The policy output tells you which snapshots were kept by `keep_latest`
versus `keep_daily`, so a surprising retention decision is easy to
audit.
## Troubleshooting
| Symptom | Likely cause |
| --- | --- |
| Hook never fires | Settings not reloaded, or `matcher` typo. |
| Snapshot folder with no `reason` suffix | Called `create` without `--reason`. |
| Hook fires but no folder appears | Content hash matched — nothing actually changed. |
| Credentials appear in a snapshot | User put them in `top_files`; the `ALWAYS_EXCLUDE` filter would drop them — check you're on the current `backup_config.py`. |
| `ImportError: backup_config` from the hook | Repo moved; update the path in `settings.json`. |
| Snapshots pile up forever | `retention.keep_latest` / `keep_daily` too high. Run `prune --policy --dry-run --json` to see what the current policy would do, then lower the caps in `~/.claude/backup-config.json`. |
| Prune removed too much | Run `prune --policy --dry-run` *before* committing to a new policy. A snapshot with a missing/zero `created_at` is always protected, so if it's getting deleted the manifest is probably fine and the policy is genuinely too aggressive. |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262# Dashboard (`ctx-monitor`)
Local HTTP dashboard for ctx's currently supported live observables:
loaded skills, agents, and MCP servers; session timelines; the
knowledge graph; the LLM-wiki browser; quality grades + scores;
filterable audit logs; and a live event stream. Dashboard harness
exposure is not yet present.
```bash
ctx-monitor serve # http://127.0.0.1:8765
ctx-monitor serve --port 8888 # custom port
ctx-monitor serve --host 0.0.0.0 --port 8888 # LAN-visible (explicit opt-in)
```
Zero Python dependencies added by the dashboard. Everything runs on
stdlib `http.server`, using daemon request threads so a live
`/api/events.stream` client cannot block normal dashboard or JSON API
requests. Cytoscape.js is loaded from a CDN on the `/graph` route only.
## Usage
Every page in the dashboard has the same top nav, so getting around
is `Home → jump anywhere`. The three feature tabs new in v0.6.4 are
how you explore the dashboard-supported ctx corpus without ever touching
the CLI. The underlying ctx catalog can include harness pages and
recommendations, but `ctx-monitor` does not yet index, render, filter,
load, unload, or score harness entries.
### Browse the LLM wiki — `/wiki`
The wiki tab is a filterable card grid of **every dashboard-supported
entity page** under
`~/.claude/skill-wiki/entities/{skills,agents,mcp-servers}/`. MCP
server pages use the sharded layout
`entities/mcp-servers/<first-char-or-0-9>/<slug>.md`; the dashboard
routes `/wiki/<slug>` to the same shard convention. Harness pages may
exist under `entities/harnesses/`, but dashboard wiki exposure for
harnesses is not yet present. Each card shows:
- the slug (click to open `/wiki/<slug>`)
- the quality grade pill (A/B/C/D/F) when the entity has a sidecar,
otherwise a `skill`, `agent`, or `mcp-server` type badge
- the frontmatter `description`
- up to 6 tags
The **left sidebar** has a text search that matches across slug,
description, and tags, plus skill/agent/MCP type checkboxes. Pair them to
answer questions like "show me all grade-B agents related to
testing" — check `agent`, type `testing` in the search box.
Dashboard-supported entity pages (`/wiki/<slug>`) render the full
markdown body, the frontmatter table on the right, and a quality banner
with deep links to `/skill/<slug>` (sidecar detail) and
`/graph?slug=<slug>` (1-hop neighborhood).
### Explore the knowledge graph — `/graph`
The graph tab is a cytoscape-rendered view over the dashboard-supportedskill/agent/MCP graph. The shipped graph bundle also contains remote-catalogedSkills.sh `skill` nodes and the graph build/recommendation APIs can beharness-aware, but this dashboard view does not yet expose harness-specificfilters or install actions. When you arrive with noslug selected, the page shows:
- a stats line with the total node + edge counts
- a **Popular seed slugs** panel — the 18 highest-degree entities
rendered as clickable chips (skills in indigo, agents in amber).
Click a chip to explore that entity's 1-hop neighborhood
- a search box — type any valid skill, agent, or MCP slug and press
`explore` (or hit Enter)
- the cytoscape canvas itself, which activates as soon as you pick a
seed
Inside the cytoscape view, node colors mean:
- **emerald** — the focus node you searched for
- **indigo** — skills
- **amber** — agents
- **red diamond** — MCP servers
Edge width encodes the `weight` attribute (count of shared tags), so
thicker lines = stronger semantic relationships. **Tap any node** to
navigate to that entity's wiki page. The type checkboxes hide or show
skills, agents, and MCP servers without reloading the graph. There is no
harness filter or harness node styling yet.
### Read the quality KPIs — `/kpi`
The KPI tab is the browser equivalent of `python -m kpi_dashboard
render`. It aggregates the quality + lifecycle sidecars under
`~/.claude/skill-quality/` into a single page with six tables:
1. **Header banner** — total entity count, subject breakdown, grade
pill counts, link to the raw `/api/kpi.json` payload, link back to
`/skills`.
2. **Grade distribution** — A/B/C/D/F count and share.
3. **Lifecycle tiers** — counts for `active`, `watch`, `demote`,
`archive`.
4. **Hard floors active** — which override reasons are currently
pinning entities to F (`never_loaded_stale`, `intake_fail`, etc.)
and how many entities each one catches.
5. **By category** — per-category count, average score, and full
A/B/C/D/F mix. This is the row most useful for "where are my D/F
skills concentrated?"
6. **Top demotion candidates** — up to 25 active-or-watch entities
graded D/F, sorted by consecutive-D streak desc then raw score
asc. Click a slug to jump to its sidecar.
7. **Archived** — slugs currently in the archive tier, with their
last-known grade.
If the quality sidecar directory is empty (no scoring has happened
yet), the page shows a helpful empty-state pointing at
`ctx-skill-quality score --all`.
## Routes
### Top navigation
Every page shows the same nav bar. The nine tabs cover the
dashboard-supported observable surface of ctx:
```
Home · Loaded · Skills · Wiki · Graph · KPIs · Sessions · Logs · Live
```
### HTML views
Harness catalog entries are absent from these routes today; they remain
available through the CLI/API recommendation surfaces.
| Route | What it shows |
|---|---|
| `/` | Home: six stat cards (loaded, sidecars, wiki entities, graph nodes, audit events, sessions), grade distribution pills, recent sessions table, recent audit events |
| `/loaded` | **Currently-loaded skills, agents, and MCP servers** from `~/.claude/skill-manifest.json` with per-row **unload** buttons + a text-input to load a new skill slug |
| `/skills` | Every sidecar as a filterable **card grid**: left sidebar (search by slug, grade checkboxes, skill/agent toggle, hide-floored), card shows grade pill + raw score + links to sidecar/wiki/graph |
| `/skill/<slug>` | Full sidecar breakdown: four-signal score (telemetry · intake · graph · routing), hard-floor reason, computed_at timestamp, per-skill audit timeline |
| `/wiki` | **Wiki entity index** — card grid of every dashboard-supported page under `~/.claude/skill-wiki/entities/{skills,agents,mcp-servers}/`, including sharded MCP server pages. Left sidebar: text search (slug · description · tag), skill/agent/MCP checkboxes. Harness pages are not indexed yet. |
| `/wiki/<slug>` | Dashboard-supported wiki entity page rendered: markdown body + full frontmatter table + grade banner + deep links to sidecar and graph-neighborhood views |
| `/graph` | **Graph explorer landing page** — node/edge count header, a "Popular seed slugs" block (18 highest-degree skill/agent/MCP entities as clickable chips), search box for any skill/agent/MCP slug, and the cytoscape canvas. Clicking a seed chip navigates to `/graph?slug=<slug>` |
| `/graph?slug=<slug>` | **Cytoscape-rendered** 1-hop neighborhood around the target skill/agent/MCP slug. Node colors: emerald=focus, indigo=skill, amber=agent, red diamond=MCP server. Edge width maps to shared-tag count. Tap any node → navigate to that entity's wiki page. Type and tag filters run client-side; no harness filter or styling exists yet. |
| `/kpi` | **KPI dashboard** — total entity count with subject breakdown, grade distribution pills, two-column tables for grade counts and lifecycle tiers (active · watch · demote · archive), hard-floor reasons with counts, **By category** table (count · avg score · A/B/C/D/F mix per category), **Top demotion candidates** (active/watch entries graded D or F, sorted by consecutive-D streak desc then score asc), and the **Archived** list. Same shape as `python -m kpi_dashboard render` but HTML |
| `/sessions` | Index of every session (audit + skill-events), first/last seen, counts of skills loaded/unloaded/agents/lifecycle transitions |
| `/session/<id>` | Per-session audit timeline showing the load → score_updated → unload triad with timestamps |
| `/logs` | Last 500 audit events in a filterable table (client-side filter on event name, subject, session id) |
| `/events` | Live SSE stream of new audit events |
### JSON API
| Route | Returns |
|---|---|
| `GET /api/sessions.json` | All sessions with aggregated counts |
| `GET /api/manifest.json` | Raw `skill-manifest.json` passthrough |
| `GET /api/skill/<slug>.json` | Raw sidecar for one slug |
| `GET /api/graph/<slug>.json?hops=1&limit=40` | Dashboard-shaped skill/agent/MCP `{nodes, edges, center}`; `hops` ∈ [1, 3], `limit` ∈ [5, 150]. Harness graph exposure is not yet present here. |
| `GET /api/kpi.json` | `DashboardSummary` passthrough — `{total, by_subject, grade_counts, lifecycle_counts, category_breakdown, hard_floor_counts, low_quality_candidates, archived, generated_at}`. Returns `{total: 0, detail: "no sidecars yet"}` when the quality directory is empty |
| `GET /api/events.stream` | Server-sent events tail of `~/.claude/ctx-audit.jsonl` |
### Mutation endpoints
Both POST endpoints enforce same-origin (browser tab open on another
origin can't forge a request), require the per-process
`X-CTX-Monitor-Token` injected into the dashboard page, and reject any
slug failing the shared safe-name validator. That validator blocks path
separators, Windows drive-relative strings, malformed names, and Windows
reserved device names such as `con.txt` and `nul.`. There is no harness
load/unload mutation endpoint yet.
| Route | Body | Calls |
|---|---|---|
| `POST /api/load` | `{"slug": "..."}` | `skill_loader.load_skill(slug)` |
| `POST /api/unload` | `{"slug": "...", "entity_type": "skill"}` | `skill_unload.unload_from_session([slug])` |
| `POST /api/unload` | `{"slug": "...", "entity_type": "mcp-server"}` | `mcp_install.uninstall_mcp(slug, force=True)` |
Both emit a matching `skill.loaded` / `skill.unloaded` audit row
with `actor=user, meta.via="ctx-monitor"` so the dashboard-driven
action is visible in the session timeline.
## KPIs, measures, scores
The dashboard surfaces every quality signal ctx currently computes for
sidecar-backed skills, agents, and MCP servers. Harness scoring is not
yet exposed in the dashboard. Nothing is aggregated-only — you can
always drill from a headline number to the raw sidecar that produced it.
### On the home page
| Card | What it means |
|---|---|
| **Currently loaded** | Count of entries in `skill-manifest.json[load]`. Clicking the card drills to `/loaded` |
| **Sidecars** | Total sidecars in `~/.claude/skill-quality/` |
| **Wiki entities** | Count of dashboard-supported wiki pages (skills + agents + MCP servers; no harness pages yet) |
| **Knowledge graph** | Dashboard-supported skill/agent/MCP node count + edge count from `graphify-out/graph.json` |
| **Audit events** | Line count of `~/.claude/ctx-audit.jsonl` |
| **Sessions** | Unique session IDs seen across audit + events |
| **Grade pills** | A / B / C / D / F counts across all sidecars, colored |
### On `/skills`
Every card shows:
- **grade** — A / B / C / D / F pill (A=green, F=red)
- **raw score** — float in [0, 1] before the hard-floor override
- **subject_type** — skill vs agent
- **hard floor reason** — `never_loaded_stale`, `intake_fail`, etc.
when the floor is active
Cards sorted by `(grade, -raw_score)` so high-scoring A's come first.
### On `/skill/<slug>`
The full four-signal breakdown from the sidecar:
| Signal | Weight (default) | What it measures |
|---|---:|---|
| **Telemetry** | 0.40 | Load frequency + recency from `skill-events.jsonl`. Rewards skills that are actually used. |
| **Intake** | 0.20 | Structural health: frontmatter fields present, H1 present, minimum body length, description length. Zero if `intake_fail` floor is active. |
| **Graph** | 0.25 | Connectivity in the knowledge graph: degree, average edge weight, community size |
| **Routing** | 0.15 | Router hit rate from `~/.claude/router-trace.jsonl`: how often this skill was among the top-K recommendations when surfaced |
The final score is `sum(weight[i] * signal[i])`. A hard floor
(`never_loaded_stale`, `intake_fail`) can override the score to
force an F grade regardless of other signals.
The skill detail page also shows the audit timeline for this slug
specifically: every `skill.loaded`, `skill.unloaded`,
`skill.score_updated` row with its session_id, so you can trace
exactly why the score changed when it did.
### On `/session/<id>`
The per-session view lets you watch a skill's lifecycle inside one
session:
```
skill.loaded fastapi-pro session-abc @ 10:23:05
skill.score_updated fastapi-pro session-abc @ 10:31:47 grade C->B
skill.unloaded fastapi-pro session-abc @ 11:04:02
```
The `load → score_updated → unload` triad is the canonical
observability proof that ctx's telemetry pipeline is live.
## Security
- **Binds to 127.0.0.1 by default**. Use `--host 0.0.0.0` only if
you actually want LAN-visible. No authentication; the server is
intended for a local developer's own machine.
- **Same-origin gating on mutation**. Any POST with an `Origin`
header that doesn't match `Host` returns 403. Curl and direct
tool calls are allowed (no Origin header at all).
- **Slug allowlist on all paths**. Anywhere the dashboard resolves
a skill, agent, or MCP slug to a file path (`/wiki/<slug>`,
`/graph?slug=<slug>`, `/api/graph/<slug>.json`), the slug is
validated through the shared
safe-name helper — no path traversal, no absolute paths, no UNC
shares, no Windows reserved device names.
## Stopping
Ctrl+C in the terminal. Request handling is threaded for local dashboard
responsiveness, and shutdown signals any open SSE workers. The monitor is
still not suitable for shared/production serving.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273# Entity Onboarding
ctx treats skills, agents, MCP servers, and harnesses as wiki entities that can
be indexed, linked in the knowledge graph, and recommended from the same
surface. The important distinction is install behavior:
- Skills and agents are local Claude Code assets.
- MCP servers are cataloged first, then installed only when the user opts in.
- Harnesses are cataloged first. A harness describes the machinery around the
model: runtime, tools, access boundaries, memory, verification, and approval
policy. Adding one never executes upstream setup commands.
After adding any entity, rebuild the graph when you want it to participate in
recommendations:
```bash
ctx-wiki-graphifyctx-scan-repo --repo . --recommend```
## Updating the Graph and LLM Wiki
Use this sequence for every accepted skill, agent, MCP server, or harnesschange. The graph and LLM-wiki are shippable artifacts, not scratch output, sothe update is treated like a release step.
1. Add or update the entity through the matching command: `ctx-skill-add`, `ctx-agent-add`, `ctx-mcp-add`, or `ctx-harness-add`.2. If the entity already exists, read the update review. It lists changed fields, likely benefits, regressions, and security findings. Do not pass `--update-existing` until those findings are acceptable.3. Run the security/cyber check below.4. Rebuild the curated wiki graph with `ctx-wiki-graphify`.5. Repack `graph/wiki-graph.tar.gz` with the exclusions in `graph/README.md`; never commit local review reports or raw caches.6. Refresh the Skills.sh catalog overlay when shipping catalog coverage. This adds remote-cataloged first-class `skill` nodes under the `skills-sh-` prefix, skill pages under `entities/skills/`, install commands, duplicate hints, and metadata-only quality/security signals:
```bash python src/import_skills_sh_catalog.py --from-api-union <raw.json> \ --catalog-out graph/skills-sh-catalog.json.gz \ --wiki-tar graph/wiki-graph.tar.gz \ --update-wiki-tar ```7. Refresh published counts with `python src/update_repo_stats.py`.8. Verify the changed entity can be recommended through `ctx-scan-repo --repo . --recommend` or `ctx__recommend_bundle`.
## Security and Cyber Check
Run this before applying `--update-existing`, before installing a harness withapproved commands, and before shipping a refreshed graph tarball.
- Inspect changed entity markdown and frontmatter for shell commands, setup commands, install commands, URLs, requested permissions, and model/provider access.- Treat these as manual-review blockers: `curl | sh`, `wget | bash`, `Invoke-Expression`, broad `rm -rf`, `git reset --hard`, `chmod 777`, secret upload, disabled auth/TLS/sandboxing/audit/tests, or unpinned package sources.- For MCP and harness updates, check network access, filesystem scope, auth material, command transports, and whether setup or verify commands execute remote code.- Prefer dry-run first: `ctx-harness-install <slug> --dry-run` and `ctx-harness-install <slug> --update --dry-run`.- If a candidate is useful but risky, document the safer install path or keep it as catalog-only metadata instead of shipping it as an installed skill.
## Updating an Existing Entity
The add commands are non-destructive by default when the target skill, agent,MCP server, or harness already exists. The first add attempt prints an updatereview instead of replacing files. That review lists changed fields, expectedbenefits, possible regressions, security findings, and a recommendation.
Use this flow for every entity type:
1. Run the normal add command.2. If ctx prints `Existing <type> already exists`, read the benefits and risks.3. Keep the current entity by doing nothing, or re-run with `--skip-existing` in batch jobs where you do not want reviews.4. Apply the replacement only after review with `--update-existing`.5. Rebuild the graph with `ctx-wiki-graphify` when the update should affect recommendations.
Examples:
```bashctx-skill-add --skill-path ./SKILL.md --name fastapi-reviewctx-skill-add --skill-path ./SKILL.md --name fastapi-review --update-existing
ctx-agent-add --agent-path ./code-reviewer.md --name code-reviewerctx-agent-add --agent-path ./code-reviewer.md --name code-reviewer --update-existing
ctx-mcp-add --from-json ./github-mcp.jsonctx-mcp-add --from-json ./github-mcp.json --update-existing
ctx-harness-add --from-json ./text-to-cad-harness.jsonctx-harness-add --from-json ./text-to-cad-harness.json --update-existing```
`ctx-harness-install --update` is different: it refreshes an installed harnesscheckout under `~/.claude/harnesses/<slug>`. Catalog entity replacement uses`ctx-harness-add --update-existing`.
## Add a Skill
Use this when you have a local `SKILL.md` that should be installed under`~/.claude/skills/<name>/SKILL.md` and mirrored into the wiki.
```bash
ctx-skill-add \
--skill-path ./SKILL.md \
--name fastapi-review
```
What happens:
1. The name is validated.
2. Intake checks run against the markdown.
3. The skill is copied into `~/.claude/skills/`.
4. A wiki page is created under `entities/skills/`.
5. The wiki index and log are updated.
## Add an Agent
Use this when you have a local Claude Code agent markdown file.
```bashctx-agent-add \ --agent-path ./code-reviewer.md \ --name code-reviewer```
Batch-add every top-level `.md` file in a directory:
```bashctx-agent-add --scan-dir ./agents --skip-existing```
Agents are copied into `~/.claude/agents/` and mirrored into
`entities/agents/`. Re-run `ctx-wiki-graphify` after adding agents if you want
graph recommendations to include them.
## Add an MCP Server
Use this when you want the MCP server available as a recommendation before
installing it into a host.
Create `github-mcp.json`:
```json
{
"name": "GitHub MCP",
"slug": "github-mcp",
"description": "MCP server for GitHub repository and issue workflows.",
"github_url": "https://github.com/modelcontextprotocol/servers",
"sources": ["manual"],
"tags": ["github", "automation", "repository"],
"transports": ["stdio"]
}
```
Add it:
```bash
ctx-mcp-add --from-json ./github-mcp.json
```
MCP pages live under `entities/mcp-servers/<shard>/<slug>.md`. The add commanddetects existing pages by slug and, when possible, canonical GitHub URL. If amatch exists, ctx prints the update review and skips replacement unless`--update-existing` is passed.
## Add a Harness
Use this when a repo provides the runtime around a model rather than just a
tool. Harness examples include coding-agent loops, CAD-generation runtimes,
browser-automation runners, evaluation loops, and local-model workbenches.
Example: catalog `earthtojake/text-to-cad` as a harness recommendation.
```bash
ctx-harness-add \
--repo https://github.com/earthtojake/text-to-cad \
--name "Text to CAD" \
--description "Harness for turning text prompts into CAD artifacts." \
--tag cad --tag 3d --tag automation \
--model-provider openai \
--runtime python \
--capability "Generate CAD artifacts from natural language" \
--setup-command "pip install -e ." \
--verify-command "pytest"
```
Or load one JSON record:
```json
{
"repo_url": "https://github.com/earthtojake/text-to-cad",
"name": "Text to CAD",
"description": "Harness for turning text prompts into CAD artifacts.",
"tags": ["cad", "3d", "automation"],
"model_providers": ["openai"],
"runtimes": ["python"],
"capabilities": ["Generate CAD artifacts from natural language"],
"setup_commands": ["pip install -e ."],
"verify_commands": ["pytest"],
"sources": ["manual"]
}
```
```bash
ctx-harness-add --from-json ./text-to-cad-harness.json
```
Harness pages live under `entities/harnesses/<slug>.md`. Setup and verificationcommands are documentation only; ctx records them so the user can inspect anddecide before running anything.
To inspect and install a cataloged harness:
```bashctx-harness-install text-to-cad --dry-runctx-harness-install text-to-cadctx-harness-install text-to-cad --update --dry-runctx-harness-install text-to-cad --uninstall --dry-run```
The installer clones or copies the harness into `~/.claude/harnesses/<slug>` andwrites `~/.claude/harness-installs/<slug>.json`. It does not run setup commandsunless you pass `--approve-commands`, and it does not run verification commandsunless you also pass `--run-verify`.
```bashctx-harness-install text-to-cad --approve-commands --run-verifyctx-harness-install text-to-cad --update --approve-commands --run-verifyctx-harness-install text-to-cad --uninstallctx-harness-install text-to-cad --uninstall --keep-files```
## Initialize Model Choice
During setup, record whether you use Claude Code or your own model. Plain`ctx-init` starts a small wizard when it is attached to an interactiveterminal; use `ctx-init --wizard` to force the prompts, or pass explicit flagssuch as `--model-mode skip` for non-interactive automation.
```bashctx-initctx-init --wizardctx-init --model-mode skip```
For Claude Code:
```bashctx-init --model-mode claude-code --goal "maintain a FastAPI service"```
For a custom model:
```bash
ctx-init \
--model-mode custom \
--model openai/gpt-5.5 \
--goal "build CAD artifacts from text prompts"
```
Add `--validate-model` only when you want `ctx-init` to make one small provider
call. Without that flag, setup writes `~/.claude/ctx-model-profile.json` and
prints harness recommendations without calling the model.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259# Attaching ctx to any LLM host
`ctx` ships three integration surfaces. Pick based on what your host
already supports:
| Your host | Use |
|---|---|
| MCP-native (Claude Code, Claude Agent SDK, Cline, Goose, OpenHands, Continue) | **MCP server** — no Python, just spawn `ctx-mcp-server` |
| Anything that isn't MCP-native but runs Python | **Python library** — `from ctx import recommend_bundle, ...` |
| "I just want to run an agent and get recommendations" | **`ctx run` CLI** — our built-in harness |
All three paths consume the **same** knowledge graph, llm-wiki, and
quality scoring. Recommendations are identical; only the transport
differs.
---
## 1. MCP server path
Install ctx with the harness extras:
```bash
pip install "claude-ctx[harness]"
```
This puts `ctx-mcp-server` on your PATH. Then wire it into your host:
### Claude Code
```bash
claude mcp add ctx-wiki -- ctx-mcp-server
```
The tools `ctx__recommend_bundle`, `ctx__graph_query`, `ctx__wiki_search`,
`ctx__wiki_get` appear to Claude on the next turn. Ask
"What skills help with FastAPI auth?" and it will call them.
### Claude Agent SDK (Python)
```python
from anthropic import Anthropic
from claude_agent_sdk import ClaudeAgentOptions, McpServerConfig
options = ClaudeAgentOptions(
mcp_servers={
"ctx-wiki": McpServerConfig(
command="ctx-mcp-server",
),
},
)
```
### Cline / Continue.dev
Add to your MCP server config (`~/.config/cline/mcp.json` or the
Continue equivalent):
```json
{
"mcpServers": {
"ctx-wiki": {
"command": "ctx-mcp-server"
}
}
}
```
### Goose
`~/.config/goose/config.yaml`:
```yaml
extensions:
ctx-wiki:
type: stdio
cmd: ctx-mcp-server
```
### OpenHands
OpenHands' runtime config:
```json
{
"mcp_servers": {
"ctx-wiki": {
"command": "ctx-mcp-server"
}
}
}
```
### Any MCP-speaking harness
The server reads JSON-RPC 2.0 on stdin, writes on stdout, speaks
MCP protocol version `2024-11-05`. Any client that does the standard
`initialize` handshake + `tools/list` + `tools/call` flow works.
### Live MCP compatibility gate
The regular test suite never starts arbitrary third-party MCP servers.
Those commands run as local subprocesses and can read files, use the
network, and inherit whatever environment you explicitly allow.
To validate a trusted server, provide a local config and opt in:
```bash
python -m pytest src/tests/test_mcp_live_compat.py \
--run-live-mcp \
--live-mcp-config /path/to/trusted-mcp.json
```
Example config:
```json
{
"name": "trusted-filesystem",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "${tmp_path}"],
"startup_timeout": 30,
"request_timeout": 10,
"inherit_env": false,
"env": {},
"expected_tools": ["list_directory"],
"probe": {
"tool": "list_directory",
"arguments": {"path": "."},
"expect_text_contains": ""
},
"trust": {
"server_is_third_party_code": true,
"approved_by": "your-name"
}
}
```
`command` and `args` are passed as an argv list, not through a shell.
Parent secrets are not inherited unless you set `inherit_env: true`; prefer
explicit `env` keys for servers that need credentials. `${tmp_path}` expands
to a pytest temporary directory so filesystem probes can avoid real user data.
---
## 2. Python library path
For custom harnesses that aren't MCP-native but can import Python:
```python
from ctx import (
recommend_bundle, # free-text → ranked skill/agent/MCP bundle
graph_query, # walk from seed entities
wiki_search, # keyword search entity pages
wiki_get, # fetch one entity by slug
list_all_entities, # enumerate every slug
)
# Inside your agent loop:
def on_user_turn(query: str):
bundle = recommend_bundle(query, top_k=5)
for entry in bundle:
print(f" [{entry['type']:>11}] {entry['name']} (score {entry['score']:.1f})")
# User asks about a specific slug you saw in the bundle:
page = wiki_get("fastapi-pro")
if page:
inject_into_context(page["body"])
```
The first call to any of these lazy-loads the graph + wiki once;
subsequent calls are O(walk) cheap. Safe to call from inside your
own while-loop on every turn.
Advanced: build a `CtxCoreToolbox` directly if you need to point at
a non-default wiki/graph path:
```python
from pathlib import Path
from ctx import CtxCoreToolbox
toolbox = CtxCoreToolbox(
wiki_dir=Path("/path/to/custom/wiki"),
graph_path=Path("/path/to/custom/graph.json"),
)
for td in toolbox.tool_definitions():
print(td.name, td.description[:50])
```
---
## 3. `ctx run` CLI path
If you don't have your own loop yet:
```bash
pip install "claude-ctx[harness]"
export OPENROUTER_API_KEY=sk-or-v1-...
ctx run \
--model openrouter/anthropic/claude-opus-4.7 \
--task "find the failing tests in this repo and fix them" \
--mcp filesystem \
--budget-usd 2.00
```
Or offline with Ollama:
```bash
ctx run \
--model ollama/llama3.1:70b \
--task "summarize the architecture" \
--mcp filesystem
```
See `ctx run --help` for the full flag set (budgets, compaction,
system prompt overrides, session resume, JSON output, ...).
---
## Choosing the right path
| Situation | Path |
|---|---|
| Your host already speaks MCP | 1 (MCP server) — zero Python code on your side |
| You want the alive-skill system inside your existing Python loop | 2 (library) |
| You're comparing models and need a harness | 3 (CLI) |
| You're building an IDE extension | 1 if the IDE speaks MCP (most do), else 2 |
All three paths share `~/.claude/skill-wiki/` as the source-of-truth
corpus, so your recommendations are consistent regardless of the
integration you pick.
---
## Skill lifecycle
Recommendations go up and down based on use automatically. `ctx`
tracks:
- **How recently a skill was invoked** (`telemetry_signal`).
- **How broadly it's used across the graph** (`graph_signal`).
- **Whether new skills are being added** (`intake_signal`).
Skills that fall below a quality floor get demoted to `stale` status
and de-ranked from future recommendations. This logic lives in
`ctx.core.quality.quality_signals` and runs identically whether
you're on the MCP path, library path, or `ctx run` CLI.
To inspect lifecycle state for a specific skill:
```bash
ctx-skill-quality --slug fastapi-pro
```
Or from Python:
```python
from ctx.core.quality import quality_signals
# see ctx.core.quality for the scoring API
```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101# Clean Host Contract
The clean-host contract is a release-hardening check for ctx. It builds the
current source tree into a wheel, installs that wheel into a fresh virtualenv,
redirects user-state environment variables into a temporary directory, and then
drives real console scripts.
It is intentionally implemented as `scripts/clean_host_contract.py`, not as a
public `ctx-*` command. The runner is infrastructure for maintainers until the
contract stabilizes.
## What It Proves
- The source tree can build a wheel.
- The built wheel installs into a clean virtualenv.
- Console-script entrypoints execute from the installed wheel.
- `ctx-init --hooks` writes Claude settings only under an isolated temp home.
- A deterministic fake Claude host reads the generated settings and executes
the installed PostToolUse and Stop hook commands without calling Anthropic
APIs.
- With `--run-live-claude`, a real Claude Code host can be exercised behind an
explicit quota acknowledgement, non-spending preflights, and a hard budget
cap. Hook execution is verified through a JSONL sentinel written by injected
PostToolUse and Stop hooks under the temp root.
- `ctx-scan-repo --recommend` can scan a tiny FastAPI-like repo from the wheel.
- `ctx run` can start a session with a process-local fake LiteLLM provider.
- `ctx resume` can continue that session from the same isolated session store.
- `--deny-tool` blocks a model-requested ctx tool call before dispatch.
- Caller `PYTHONPATH` is stripped so the contract cannot accidentally import
source-tree modules instead of the installed wheel.
## What It Skips
- It does not run `ctx-init --graph`; graph builds are intentionally slow.
- It does not execute hooks inside a live Claude Code process by default. The
live host path is opt-in because it can consume Anthropic or provider quota.
- It does not connect to a real third-party MCP server.
- It does not browser-test the monitor dashboard.
- It does not simulate process kills or power loss during writes.
Those checks stay intentionally manual or opt-in until they are stable enoughfor the default CI path.
## Local Usage
Run from the repository root:
```bash
python scripts/clean_host_contract.py --fast
```
For debugging, keep the temp directory:
```bash
python scripts/clean_host_contract.py --fast --keep-temp
```
To force a specific temp root:
```bash
python scripts/clean_host_contract.py --fast --temp-root /tmp/ctx-clean-host-debug
```
To run the real Claude Code host gate, use a shell with explicit non-file auth
available, acknowledge quota, and keep the budget small:
```bash
CTX_LIVE_CLAUDE_ACK=uses_quota \
python scripts/clean_host_contract.py --fast --run-live-claude --live-claude-max-budget-usd 0.05
```
Use `--claude-bin /path/to/claude` if `claude` is not on `PATH`. The live gate
runs `claude --version` and `claude auth status` before the budgeted prompt,
then appends sentinel hooks to the isolated `settings.json` and requires both
PostToolUse and Stop records in `live-claude-hooks.jsonl`. It intentionally
does not read OAuth or keychain state from the real user home; use explicit
environment/provider auth for this check.
## CI Usage
The main `.github/workflows/test.yml` workflow runs this contract on pushes and
pull requests. The standalone `.github/workflows/clean-host-contract.yml`
workflow remains available for manual runs and weekly scheduled drift checks.
CI uses the default fake-host path and does not spend model quota.
## Failure Triage
- Wheel build failure: inspect package metadata and `pyproject.toml`.
- Install failure: inspect dependency constraints and `pip check` output.
- `ctx-init` failure: inspect packaged entrypoints and hook module paths.
- Fake Claude hook-smoke failure: inspect generated `settings.json`, packaged
hook module paths, and whether PostToolUse/Stop hook schemas changed.
- Live Claude gate failure: inspect explicit auth env/provider credentials,
`claude auth status`, the budget cap, the injected sentinel hook entries, and
`live-claude-hooks.jsonl` under the temp root.
- `ctx-scan-repo` failure: inspect installed flat-module entrypoints and
resolver imports.
- `ctx run` or `ctx resume` failure: inspect LiteLLM provider import behavior,
session store paths, and CLI metadata replay.
- Tool denial failure: inspect `--allow-tool`/`--deny-tool` policy handling in
`src/ctx/cli/run.py` and `src/ctx/adapters/generic/loop.py`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197---
hide:
- navigation
---
# ctx — Skill, Agent, MCP & Harness Recommendation and Management
Watches what you develop, walks a knowledge graph of **92,815 skills, 464agents, 10,786 MCP servers, and cataloged harnesses**, and recommends the
right ones on the fly — you decide what to load, install, or adopt. Powered
by a Karpathy LLM wiki with persistent memory that gets smarter every session.
!!! tip "Install"
```bash
pip install claude-ctx
```
Optional extras: `pip install "claude-ctx[embeddings]"` for the
semantic backend, `pip install "claude-ctx[dev]"` for the
pytest/mypy/ruff toolchain. After install the `ctx-scan-repo`,
`ctx-skill-quality`, `ctx-skill-health`, and `ctx-toolbox` console
scripts are on PATH.
Custom-model users can run
`ctx-init --model-mode custom --model <provider/model> --goal "<task>"`
to record the model profile and surface harness recommendations.
## Why this exists
Claude Code skills, agents, MCP servers, and model harness profiles are
powerful, but at scale they become unmanageable:
- **Discovery problem** — with 92K+ skills, 460+ agents, 10,000+ MCP servers, and an expanding harness catalog, how do you know which
ones exist and which are relevant to your current project?
- **Context budget** — loading every installable entity wastes tokens and
degrades quality. You need exactly the right skills, agents, MCP
servers, and harness recommendations per session.
- **Hidden connections** — a FastAPI skill is useful, but you also need
the Pydantic skill, the async Python patterns skill, and the Docker
skill, plus possibly a matching MCP server or model harness profile.
Nobody tells you that.
- **Entity rot** — skills, agents, MCP servers, and harness records you
added months ago and never used are cluttering your context. Stale ones
should be flagged and archived.
ctx solves all of these by treating your ctx catalog as a **knowledge
graph with persistent memory**, not a flat directory.
## What this is
ctx is not a collection of scripts. It is an agent with persistent memory
and a knowledge graph.
The core idea comes from Andrej Karpathy's LLM-wiki pattern: instead of
re-loading everything from scratch each session, an LLM maintains a wiki
it can read, write, and query. The wiki becomes the agent's long-term
memory.
ctx applies that pattern to catalog management — and extends it with
graph-based discovery:
- A Karpathy 3-layer wiki at `~/.claude/skill-wiki/` is the single source
of truth.
- **104,065 entity pages/nodes** for the shipped skill/agent/MCP inventory, including 90,846 remote-cataloged Skills.sh skill pages, plus harness pages under `entities/harnesses/` when you catalog them. Each page tracks tags, status, provenance, and usage where it applies.- A **knowledge graph** (104,065 nodes, 1,030,831 edges) built from a 13,219-node curated core plus 90,846 remote-cataloged Skills.sh `skill` nodes. The curated core has 22 Louvain communities and blends semantic cosine + tag overlap + slug-token overlap; the current Skills.sh pass adds sparse metadata edges and keeps metadata-only security status until full SKILL.md body hydration runs.- **22 Louvain communities** group related entities into named
communities (e.g., *AI + Devops + Frontend*, *Python + API*).
- PostToolUse and Stop hooks update the wiki automatically during each
Claude Code session.
- Skills over 180 lines are converted to a gated 5-stage micro-skill
pipeline so the router can load them incrementally.
- At session start, the skill-router scans your project and
**recommends** the best-matching skills, agents, MCP servers, and
harnesses.
- Mid-session, the context monitor watches every tool call, detects new
stack signals, walks the graph, and **recommends** relevant skills,
agents, MCP servers, and harnesses in real time — **nothing loads or
installs without your approval**.
The result: you always know what skills, agents, MCP servers, and harnesses are
available for your current task. The graph reveals hidden connections. The wiki
learns from your usage. Stale ones are flagged. New ones self-ingest.
## Explore the docs
<div class="grid cards" markdown>
- **Knowledge graph**
---
104,065 shipped graph nodes: 13,219 curated skill/agent/MCP nodes plus 90,846 remote-cataloged Skills.sh skill nodes. The graph has 1,030,831 weighted edges; Louvain communities are generated for the curated core. Ships pre-built in `graph/wiki-graph.tar.gz` and powers the
graph-aware recommendations + the pre-ship `ctx-dedup-check` gate.
[:octicons-arrow-right-24: Knowledge graph](knowledge-graph.md)
- **Entity onboarding**
---
Step-by-step commands for adding a skill, agent, MCP server, or
harness to the wiki and graph. Includes the `text-to-cad` harness
pattern for custom-model users.
[:octicons-arrow-right-24: Entity onboarding](entity-onboarding.md)
- **Dashboard**
---
`ctx-monitor serve` opens a local HTTP dashboard with live graph,
skill grades + four-signal scores, session timelines, and one-click
load/unload for skills, agents, and MCP servers. Dashboard harness
exposure is not yet present. Zero dependencies beyond stdlib.
[:octicons-arrow-right-24: Dashboard reference](dashboard.md)
- **Toolbox**
---
Curated councils of skills and agents that fire at session-start,
file-save, pre-commit, and session-end. Blocks `git commit` on
HIGH/CRITICAL findings. Five starter toolboxes ship out of the box.
[:octicons-arrow-right-24: Toolbox overview](toolbox/index.md) ·
[Starter toolboxes](toolbox/starters.md) ·
[Verdicts & guardrails](toolbox/verdicts.md)
- **Skill router**
---
Scans the active repo, detects the stack from file signatures, walks
the stack matrix, loads exactly the skills that apply, and can
recommend supporting agents, MCP servers, and harnesses.
[:octicons-arrow-right-24: Router overview](skill-router/index.md) ·
[Stack signatures](stack-signatures.md) ·
[Skill-stack matrix](skill-stack-matrix.md)
- **Health & quality**
---
Structural health checks (missing frontmatter, orphan manifest
entries, line-count drift) plus the four-signal quality score
(telemetry · intake · graph · routing) that grades every skill
A/B/C/D/F.
[:octicons-arrow-right-24: Skill health](skills-health.md) ·
[Memory anchoring](memory-anchor.md) ·
[Lifecycle dashboard](skill-lifecycle-and-dashboard.md)
- **Releases**
---
**v0.7.x** — MIT, CI-matrixed (Ubuntu + Windows × Python 3.11/3.12),
3,287+ tests passing. Ships console scripts including `ctx-init`,
`ctx-monitor` (local dashboard with graph + wiki + load/unload for
skills, agents, and MCP servers; harness exposure not yet present),
`ctx-dedup-check` (pre-ship near-duplicate gate), and
`ctx-tag-backfill` (catalog hygiene), plus the ~46 MB pre-built wiki tarball with **104,065 nodes / 1,030,831 edges / 22 curated-core Louvain communities**. Hardened across the Strix audit + a 12-finding codex review.
[:octicons-arrow-right-24: CHANGELOG](https://github.com/stevesolun/ctx/blob/main/CHANGELOG.md) ·
[Repository](https://github.com/stevesolun/ctx)
</div>
## Principles
- **Foundation first.** Data model, CLI, and starter bundles ship before
any hook integration. Each phase is independently usable.
- **User-configurable everything.** Dedup policy, suggestion loudness,
trigger set, council composition.
- **Evidence over opinion.** Suggestions cite real usage data plus
knowledge-graph edges. No black-box prompts.
- **Token discipline.** Every council run honors `max_tokens` /
`max_seconds` budgets.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210# Knowledge graph
A pre-built weighted graph of skills, agents, MCP servers, and cataloged
harnesses in the ctx ecosystem, shipped as `graph/wiki-graph.tar.gz`.
The on-disk JSON and `resolve_graph` Python API are harness-aware, includingplain-slug graph walks from `harness:<slug>` nodes;`ctx-monitor` currently exposes skill/agent/MCP graph and wiki viewsonly. Dashboard harness exposure is not yet present.
## What's in it
Authoritative numbers from the shipped tarball. The curated-core snapshotis **13,220 nodes** (1,969 curated skills + 464 agents + 10,786 MCP servers+ 1 harness). Harness pages under `entities/harnesses/` are ingested intolocal rebuilds and recommendation output when cataloged. The tarball also carries **90,846remote-cataloged Skills.sh `skill` nodes**, matching skill pages under`entities/skills/skills-sh-*.md`, and **67,519 sparse metadata edges** backto curated entities. These records are first-class skills by graph type,but remain metadata-only until their upstream SKILL.md bodies are hydratedand reviewed.
| | Count |
|---|---:|
| Total nodes | **104,066** || Curated core nodes | **13,220** (1,969 skills + 464 agents + 10,786 MCP servers + 1 harness) || Remote-cataloged Skills.sh skill nodes | **90,846** (`skill`, `status=remote-cataloged`) || Total edges | **1,031,011** || Curated core edges | **963,492** || Skills.sh metadata edges | **67,519** || Communities | **22** (Louvain over the curated core) || Edge sources (overlap-deduped) | semantic 210,248 - tag 597,017 - token 314,945 || Cross-type edges (skill <-> agent) | ~222K || Cross-type edges (skill <-> MCP) | ~62K || Cross-type edges (agent <-> MCP) | ~13K || Harness edges | **224** (`text-to-cad` -> 126 curated skills, 44 Skills.sh skills, 40 MCP servers, 14 agents) || Skills.sh catalog | **90,846** observed entries (`external-catalogs/skills-sh/catalog.json` + `entities/skills/skills-sh-*.md`) |
## Install
Extract the tarball into your `~/.claude/skill-wiki/` to get aready-to-query graph plus every shipped skill/agent/MCP entity page,cataloged harness pages when present, remote-cataloged Skills.sh skillpages, concept pages, and converted micro-skill pipelines. The extractedtree also includes the Skills.sh catalog JSON used by the sharedrecommender:
```bash
mkdir -p ~/.claude/skill-wiki
tar xzf graph/wiki-graph.tar.gz -C ~/.claude/skill-wiki/
```
The extracted tree also opens directly as an Obsidian vault — the
`.obsidian/` config ships inside the tarball — so you can use
Obsidian's native graph view if you prefer it to the web dashboard.
## How edges are built
Two sources of connectivity, combined at build time by the
`ctx-wiki-graphify` console script (`ctx.core.wiki.wiki_graphify`):
1. **Explicit frontmatter tags** — each entity page's YAML `tags:`
list contributes edges between every pair of entities that share
a tag. Popular tags capped at 500 nodes to avoid noise-floor
"everything connects to everything" mega-buckets like `typescript`
or `frontend`.
2. **Slug-token pseudo-tags** — each hyphenated slug contributes its
tokens as implicit tags. `fastapi-pro` contributes `fastapi`;
`python-patterns` contributes `python` and `patterns`. A stop-word
filter drops generic tokens like `skill`, `agent`, `pro`, `expert`,
`core` so they don't over-connect the graph.
Edge `weight` is the count of shared tags between two nodes. Edge
`shared_tags` is the list of the actual tags that produced the edge,
so any single edge is explainable (e.g. `cloud-architect ↔ terraform-
engineer` has `weight=6` with `shared_tags=[automation, azure,
security, _t:architect, ...]`).
## Communities
After edges are built, `wiki_graphify` runs NetworkX's Louvain
community detection (`resolution=1.2`, `seed=42` for determinism).
The result is **22 communities** ranging from single-member isolated
specialists to several thousand members in broad clusters like
`Community + Official + AI`. Each community also gets an auto-generated
`concepts/<community>.md` wiki page summarizing its members and top
shared tags.
The legacy CNM ("greedy modularity") algorithm is still available
behind `CTX_GRAPH_COMMUNITY=cnm` — it's deterministic but O(n²) on
dense graphs and hangs on the live 13K-node dataset (~50min run was
killed on 2026-04-27 inside the priority-queue siftup). Louvain is
the default because it finishes in seconds and produces equivalent
quality clusters for the recommendation use case.
## Querying the graph
### Via the dashboard
```bash
ctx-monitor serve # http://127.0.0.1:8765
```
Then open `/graph?slug=<skill-agent-or-mcp-slug>` for a cytoscape
neighborhood view, or `/api/graph/<slug>.json?hops=1&limit=40` for the
dashboard-shaped JSON. `ctx-monitor` does not yet offer harness filters,
styling, or wiki routes; use the Python/API recommendation surfaces for
harness-aware graph results. See the [dashboard reference](dashboard.md)
for the full route catalogue.
### Via Python
```python
import json
from pathlib import Path
from networkx.readwrite import node_link_graph
raw = json.loads(
Path("~/.claude/skill-wiki/graphify-out/graph.json").expanduser().read_text()
)
edges_key = "links" if "links" in raw else "edges"
G = node_link_graph(raw, edges=edges_key)
# 104,066 nodes, 1,031,011 edgesprint(G.number_of_nodes(), G.number_of_edges())
# Find entities related to 'fastapi-pro' by edge weight
seed = "skill:fastapi-pro"
neighbors = sorted(
G.neighbors(seed),
key=lambda n: G[seed][n]["weight"],
reverse=True,
)[:10]
for n in neighbors:
shared = G[seed][n].get("shared_tags", [])
print(f" w={G[seed][n]['weight']:>2} {G.nodes[n]['label']:<40} {shared[:3]}")
```
The node-link JSON schema's edges key is auto-detected (legacy
NetworkX 2.x used `"links"`; current versions default to `"edges"`).
The helper `resolve_graph.load_graph()` does this for you.
### Via recommendation paths
The graph backs two recommendation paths:
- Free-text recommendation surfaces (`ctx.recommend_bundle`, MCP
`ctx__recommend_bundle`, generic harness tools, and Claude Code hook
suggestions) share `ctx.core.resolve.recommendations.recommend_by_tags`.
That engine ranks skills, agents, MCP servers, and harnesses by slug-token matches, tag overlap, graph degree, and semantic-cache signals when available. Skills.sh results are `skill` nodes with `source_catalog=skills.sh`, `detail_url`, `install_command`, duplicate hints, and metadata-only quality/security signals. If an older extracted wiki has the Skills.sh catalog JSON but no graph nodes for those records, the same recommender falls back to the catalog file.- Repository scans still start from stack detections and installed-entity
availability. `resolve_skills.resolve()` maps detected languages,
frameworks, infrastructure, and tools through the shared stack matrix, then
uses the graph as an advisory augmentation source for additional installed
skills, agents, and MCP server suggestions, plus catalog-only harness
recommendations where the scan includes them.
This split is intentional: free-text query surfaces need identical ranking,
while scan resolution also has to respect local installation state and the
manifest cap.
## Rebuilding
After you add a skill, agent, MCP server, or harness entity page:
```bash
ctx-wiki-graphify # rebuild entity graph + communities
```
The pre-commit hook (`.githooks/pre-commit`) re-runs this
automatically when `skills/` or `agents/` are staged, and repacks
the tarball on disk so `README.md` numbers never drift. Run
`ctx-wiki-graphify` directly for MCP server or harness catalog changes
if your hook config does not include those paths.
## Edge-count history
| Version | Edges | Note |
|---|---|---|
| v0.5.x | 642K (stale) / 861 (live) | Bundle had stale 642K; live rebuild silently produced 861 because `DENSE_TAG_THRESHOLD=20` dropped every popular tag. |
| v0.6.0 | 454,719 | Threshold raised to 500, multi-line YAML lists parsed, slug-token pseudo-tags added. |
| v0.7.x | 847,207 | Pulsemcp ingest added 10,786 MCP server nodes; sentence-embedding semantic edges added. || 2026-04-27 (this release) | **963,068** | +21 mattpocock skills, +156 designdotmd designs (+106,702 edges); patch-path bug fixed (graphify now forces full rebuild when prior graph has 0 semantic edges but current run computed semantic pairs); community detection switched from CNM to Louvain. || 2026-04-29 Skills.sh remote-cataloged pass | **1,030,831** | +90,846 first-class `skill` nodes, +90,846 skill pages, and +67,519 sparse duplicate/tag metadata edges to the curated graph. Full-body semantic edges are intentionally deferred to the hydration pass. |
The full audit history lives in `CHANGELOG.md`. The current build is
fully reproducible from the wiki content.
## Pre-ship gates
Two advisory gates run before the tarball is repackaged. Both produce
review reports and never auto-modify the catalog.
- **`ctx-dedup-check`** — flags entity pairs (skill ↔ skill, skill ↔
agent, skill ↔ MCP, agent ↔ agent, agent ↔ MCP, MCP ↔ MCP) at or
above 0.85 cosine similarity. Incremental: keeps a `dedup-state.json`
next to the embedding cache, so follow-up runs only re-check pairs
involving entities whose content changed. Allowlist support via
`.dedup-allowlist.txt`. The current snapshot has 15,976 findings,
most of which are within-MCP near-duplicates (multiple wrappers
around the same upstream service).
- **`ctx-tag-backfill`** — finds skills/agents with empty `tags:`
frontmatter and proposes a backfill drawn from slug tokens, body
keywords, and the existing tag vocabulary. Report-only by default;
pass `--apply` to write. Backfills are additive only.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157# Marketplace Registry
> Known skill/plugin marketplaces and how to interact with them.> The router queries these when it detects a stack gap (needed skill not installed).
## Registered Marketplaces
### 1. Local Skills Directory
```yamlname: localtype: filesystempath: /mnt/skills/scan_method: directory listingrefresh: always currentpriority: 1 # check first```
List all installed skills:```bashfind /mnt/skills/ -name "SKILL.md" -maxdepth 3```
### 2. User Skills Directory
```yamlname: user-localtype: filesystempath: /mnt/skills/user/scan_method: directory listingrefresh: always currentpriority: 2```
User-uploaded or custom skills. Same scan as local but separate namespace.
### 3. Example Skills
```yamlname: examplestype: filesystempath: /mnt/skills/examples/scan_method: directory listingrefresh: always currentpriority: 3```
Bundled example skills that may not be active but can be copied to user skills.
### 4. GitHub Skill Repos
```yamlname: githubtype: gitbase_url: https://github.comsearch_method: topic search "claude-skill" OR "hermes-skill"install_method: git clone + copy SKILL.md to /mnt/skills/user/refresh: on-demandpriority: 5```
Search pattern:```bash# Via GitHub API (if available)curl -s "https://api.github.com/search/repositories?q=topic:claude-skill&sort=stars"
# Via web search fallbackweb_search "claude skill github site:github.com"```
### 5. npm Registry (for JS/TS skills packaged as npm)
```yamlname: npmtype: package-registrybase_url: https://registry.npmjs.orgsearch_method: keyword search "claude-skill"install_method: npm install -g <package>refresh: on-demandpriority: 6```
### 6. PyPI (for Python skills packaged as pip)
```yamlname: pypitype: package-registrybase_url: https://pypi.orgsearch_method: keyword search "claude-skill" OR "hermes-skill"install_method: pip install <package>refresh: on-demandpriority: 6```
---
## Marketplace Query Protocol
When the resolver identifies a gap (stack detected, no skill available):
```1. Check local -> user-local -> examples (instant, filesystem)2. If not found, check wiki for cached marketplace data3. If cache is stale or empty: a. Query GitHub topics b. Query npm/pypi if relevant language c. Cache results in raw/marketplace-dumps/ d. Create new entity pages for discovered skills, or emit an update review for existing pages4. Present findings to user with install commands```
## Caching
Marketplace results are cached in the wiki at:```raw/marketplace-dumps/<marketplace-name>-YYYY-MM.md```
Each dump is a markdown table:
```markdown# GitHub Marketplace Dump -- 2026-04
| Name | URL | Stars | Description | Stacks | Last Updated ||------|-----|-------|-------------|--------|--------------|| ... | ... | ... | ... | ... | ... |```
Refresh policy: controlled by `refresh_interval_days` on each marketplace'sentity page. Default 7 days. User can override per marketplace.
## Installing from Marketplace
The install flow:1. Router suggests: "The `terraform` skill is available on GitHub. Install it?"2. User confirms3. Router executes: ```bash # GitHub example git clone https://github.com/user/terraform-skill.git /tmp/terraform-skill cp -r /tmp/terraform-skill /mnt/skills/user/terraform/ rm -rf /tmp/terraform-skill ```4. Create the entity page in the wiki; if one already exists, show the benefits/risks update review and require `--update-existing` before replacing it5. Add to current manifest and load6. Log the install
## Security Notes
- Never auto-install without user confirmation- Always show the source URL before installing- For git repos: check for SKILL.md at root, reject if missing- Never execute arbitrary scripts from marketplace skills without user review- Warn if a skill requires network access or system-level permissions123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102# Memory anchoring
[`src/memory_anchor.py`](https://github.com/stevesolun/ctx/blob/main/src/memory_anchor.py)
walks the auto-memory store and flags references that no longer
resolve against the current repository.
## Why it exists
Claude's auto-memory accumulates notes that look like:
> Fixed the `add_skill()` bug in `src/skill_loader.py:42`. See also
> `docs/intent-interview.md`.
Those backtick references rot as the codebase moves. A renamed file, a
deleted module, a moved doc — and the memory silently points at
nothing. `memory_anchor` turns that silent rot into a loud dashboard.
## Where it looks
Memory files live under:
```text
~/.claude/projects/<slug>/memory/*.md
```
The module recursively scans that tree. You can override the root with
`--memory-root` (useful for tests or multi-project setups).
## What counts as a reference
Only tokens inside **backtick code spans** qualify. The heuristic is
deliberately conservative to keep false positives low:
- known extension (`.py`, `.md`, `.json`, `.yml`, `.ts`, `.rs`, …), or
- contains a `/` with a dotted final segment.
Tokens with whitespace, `()` suffixes, `http(s)://` prefixes, or leading
`-` are rejected up front. A trailing `:<digits>` is parsed as a line
suffix — `:` without digits is preserved (keeps Windows drive letters
intact).
## How resolution works
For each extracted reference, the module asks whether it resolves:
1. tilde-expand, if `~/…`
2. if absolute, does the path exist?
3. does `repo_root / path` exist?
4. does `repo_root / src / path` exist?
If any candidate hits, the ref is *live*; otherwise *dead*.
## CLI
```bash
# JSON report for downstream tooling
python -m memory_anchor scan
# Human dashboard
python -m memory_anchor dashboard
# CI gate: exit 2 if any dead references remain
python -m memory_anchor check --strict
# Override repo / memory roots
python -m memory_anchor check --strict \
--repo-root /path/to/repo \
--memory-root /path/to/project/memory
```
When `--repo-root` is omitted, the module walks upward from the current
directory to the nearest `.git/` ancestor.
## Data model
```python
@dataclass(frozen=True)
class AnchorRef:
raw: str # exactly the backtick contents
path: str # path sans trailing :<line>
line: int | None
exists: bool
@dataclass(frozen=True)
class MemoryAnchorFile:
memory_path: str
refs: tuple[AnchorRef, ...]
# derived: .live, .dead
@dataclass(frozen=True)
class AnchorReport:
generated_at: float
repo_root: str
memory_root: str
files: tuple[MemoryAnchorFile, ...]
# derived: .all_refs, .live_count, .dead_count, .has_dead
```
## Related
- [Skill health dashboard](skills-health.md) — structural and drift
checks for the skill + agent catalog.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467# Plan 001 — Model-Agnostic Harness & Repo Reorganization
**Status:** APPROVED (2026-04-24) — in execution**Author:** ctx**Date:** 2026-04-24**Reference:** [Anthropic — Harness design for long-running application development](https://www.anthropic.com/engineering/harness-design-long-running-apps)
## Decisions (locked 2026-04-24)
| # | Decision ||---|---|| 1 | **Option B — full harness**. ctx *becomes* the harness around any LLM. || 2 | **All reorg phases R0–R6**. || 3 | **Providers: Ollama (local) + OpenRouter (remote aggregator) as tier-1.** Any OpenRouter-listed model (GPT-5.5, MiniMax, Claude, Gemini, Llama, etc.) works without extra adapters. Direct provider SDKs added only if OpenRouter has a gap. || 4 | **Both `~/.ctx/` + `~/.claude/` shipped with configs out of the box.** First `ctx`/`ctx run` invocation works without the user filling in anything. || 5 | **B-full reached incrementally ("Anthropic style")** — solo agent → Planner → Evaluator → sprint contracts. Each step ships as its own phase and is only added after measuring the previous step's failure modes. Target end-state is the full three-agent harness; path there is evidence-driven. || 6 | **State = JSONL append-only** (Claude Agent SDK pattern). State behind a `StateStore` Protocol so SQLAlchemy/Redis implementations can drop in later. **No LangGraph** — adopting it means adopting its whole graph-based programming model. || 7 | **Publish as pip package** after R6 completes (package name TBD: `ctx-harness` candidate). |
---
## 0. TL;DR
`ctx` is currently built as a **plugin into Claude Code** — it assumes `~/.claude/`, shells out to `claude mcp add/remove`, emits CC's `PostToolUse`/`Stop` hook JSON. Goal: allow `ctx`'s alive-skill / knowledge-graph / recommendation system to run around **any** model (MiniMax, GPT-5.5, local Ollama, etc.).
**Three interpretations of "use ctx as a harness" — decision needed before we build:**
1. **(A) Plugin-for-any-harness** — ctx stays a skill/MCP recommendation *library*; ship adapters for Claude Code (today), Aider, Goose, Cline, and any custom host. No agent loop, no while-loop, no provider management. Smallest delta.2. **(B) Full harness** — ctx *becomes* the harness. We write the while-loop, provider adapter (via LiteLLM), tool dispatcher, context compactor, checkpointer. Claude Code integration becomes one of N hosts. Largest delta; overlaps with OpenAI Agents SDK / LangGraph / SWE-agent.3. **(C) Hybrid, minimal harness + plugin retained** — Build a *thin* harness (the while-loop + tool dispatch + LiteLLM provider shim) that uses ctx-core's recommendation system. Package the Claude-Code integration as one adapter, generic harness as another. ~80% of option A's simplicity + an actually usable "run against any model" path.
Recommendation: **(C)**. Rationale at §3.
Second question: **repo reorganization**. 60+ flat modules under `src/`, tests embedded, no namespace. Proposal: migrate to `src/ctx/{core,adapters,cli,utils}/` over 6 phases. Details at §6.
---
## 1. What Anthropic means by "harness"
Per the article, a harness is "an orchestration layer that structures how agents execute complex tasks over extended periods." It is scaffolding that compensates for what a model can't yet do alone — and should be systematically stripped away as model capabilities improve ("every component in a harness encodes an assumption about what the model can't do on its own").
Core responsibilities Anthropic enumerates:
| Concern | What it does | In ctx today? ||---|---|---|| **Context management** | Compaction, resets, avoiding "context anxiety" near token limits | ❌ (Claude Code handles it) || **Task decomposition** | Planner → Generator → Evaluator split | ❌ || **State persistence** | Artifacts survive context resets | ⚠️ (skill-manifest.json is persistent; no mid-session artifacts) || **QA feedback loops** | Separate evaluator from generator (avoids self-praise) | ❌ || **Tool/env integration** | Playwright MCP, git, runtime inspection | ⚠️ (MCP install works, but we don't *orchestrate* tool use) || **Interactive testing** | Live browser, code execution during the run | ❌ || **Observability** | Read each agent's logs, tune prompts | ⚠️ (telemetry exists, but for installs not for agent runs) || **Cost control** | Track $/run, remove scaffolding as models improve | ❌ || **Long-running coordination** | Sprint contracts, checkpoints, resumability | ❌ |
The article's **recommended pattern** is the three-agent architecture: **Planner** (expands vague prompts into detailed specs) → **Generator** (implements iteratively against spec) → **Evaluator** (interactive testing, explicit grading criteria, few-shot calibrated). They communicate via **file-based artifacts**, not inline conversation.
Anti-patterns called out: solo agent on complex tasks, self-evaluation, vague grading criteria, overspecifying implementation upfront, ignoring model-specific limitations.
---
## 2. Existing harnesses — design space survey
Full table: §Appendix A. Key findings:
- **The while-loop is universal.** Every harness implements the same loop: call model → check tool-use → execute → feed result back → repeat. Variations are in what wraps the loop.- **Tool dispatch splits into two camps:** native-schema (OpenAI/Claude tool-use JSON) vs protocol (MCP, XML-in-system-prompt, Agent-Computer Interface). **MCP has emerged as the cross-harness interoperability standard** (Cline, Goose, Claude Agent SDK, OpenHands all speak MCP).- **Multi-model support = LiteLLM substrate.** Aider, SWE-agent, OpenAI Agents SDK all delegate to LiteLLM for the N-provider problem. Reinventing that is industry anti-pattern. Strix (the pen-test tool we ran last session) already uses LiteLLM. **Decision: LiteLLM is a fixed dependency, never something to reimplement.**- **Checkpointing separates research from production harnesses.** LangGraph's per-step checkpointing is best-in-class; Claude Agent SDK does session-level resume via JSONL replay; Aider treats git commits as implicit checkpoints; Cline/Goose have none.- **Plugin surfaces = hooks | graph-nodes | MCP-servers.** MCP is the winner for cross-tool interop.
**Top 3 prior-art references:**1. **LiteLLM** — substrate, not prior art to copy. Fixed dependency.2. **SWE-agent** — cleanest "Agent-Computer Interface" abstraction. Separates agent / environment / models. Mini-SWE-agent is 100 lines and scores >74% SWE-bench. Directly instructive.3. **OpenAI Agents SDK** — best model for public API shape (Agents + Handoffs + Guardrails + Session). Study its `ModelProvider` protocol.
---
## 3. Strategic options — pick one
### Option A: Plugin-for-any-harness (LIBRARY-FIRST)
Users wire `ctx` into *their* harness (Claude Code today, Aider/Goose/Cline/their-custom-loop tomorrow).
**What ships:**- Stable Python API: `from ctx.core import bundle_for_query, resolve_skills, install_entity` etc.- Stable CLI surface unchanged (`ctx-skill-install`, `ctx-mcp-install`)- One MCP server (`ctx-mcp-server`) that exposes `ctx.recommend_bundle(query)` / `ctx.install(slug)` / `ctx.graph_query(seeds)` as MCP tools — any MCP-speaking harness can call it- Claude Code integration stays as today; it's just one more MCP consumer
**What does NOT ship:**- No agent loop- No provider adapter- No model calls from ctx code
**Pros:** Tiny delta. No competition with existing harnesses. Plays the MCP interop card. ctx stays a library, which is its actual differentiator.**Cons:** Users still need their own harness. Doesn't answer "run ctx around MiniMax" — it answers "run MiniMax inside a harness that happens to use ctx's MCP server."
### Option B: Full harness (HARNESS-FIRST)
We write a full harness — while-loop, provider abstraction, tool dispatch, context compaction, checkpointing, multi-agent (Planner/Generator/Evaluator).
**Pros:** User can `ctx run --provider=openai --model=gpt-5.5 "build me a todo app"` and actually get autonomous behavior.**Cons:** We'd be building a worse SWE-agent / worse OpenAI Agents SDK / worse LangGraph. Our differentiator (alive skills + graph + quality) gets buried under undifferentiated agent-loop code. Huge surface to maintain. We've never built a production harness.
### Option C: Hybrid — minimal harness + plugin retained (RECOMMENDED)
Thin harness layer: LiteLLM-backed provider shim + bare while-loop + MCP-based tool dispatch. Reuses **ctx-core** (graph/quality/resolve/wiki — already provider-agnostic) as its recommendation layer. Claude Code integration becomes one adapter among N.
**What ships (minimum viable harness):**```ctx run --provider openai --model gpt-5.5 \ --mcp ctx,filesystem,github \ --task "fix the failing tests in this repo"```
Internally:1. LiteLLM routes calls to the chosen provider.2. ctx-core resolves the task → suggests a skill/agent/MCP bundle → auto-attaches relevant MCPs.3. Thin while-loop: call model, check tool-use, dispatch via MCP, feed back.4. State: append-only JSONL session file (same pattern as Claude Agent SDK). Context compaction via OpenAI Agents SDK's pattern or direct `litellm.completion()` with summarization.5. Checkpointing is optional — start without, add LangGraph-style later if users need it.
**What does NOT ship in v1:**- Planner/Generator/Evaluator split (we defer Anthropic's pattern until there's demand — it's load-bearing in the Anthropic article specifically for *product-build* tasks, not general coding)- Interactive Playwright testing- Time-travel debugging
**Pros:** - Actually delivers "run around any model"- Leverages the existing ctx-core (which is already model-agnostic — per §4 inventory, 4 modules are ready today)- LiteLLM does 90% of the provider-adapter work- Minimum-surface harness — small enough to maintain while we focus on the skill/graph differentiator- Path to (A) if we decide we don't want the harness — just stop shipping `ctx run` and keep the MCP server
**Cons:**- More code than Option A- We own the loop, so bugs in context compaction / error recovery are ours- Per the Anthropic article, *our harness encodes our assumptions about model limits* — we have to revisit as models improve
### Recommendation: **C**
The decision fork is really "do we ship a runnable harness, or just a library." If the user's end-state is "wrap MiniMax / GPT-5.5 with ctx," option A requires the user to bring their own loop, which means they need another tool. Option C delivers the end-state with minimum new surface, and keeps A's escape hatch (the MCP server is still useful to other harnesses).
---
## 4. Current coupling inventory (what has to move)
From the CC-specific audit: **~46 references across 12 modules** need to change. Categorized:
### MUST refactor (coupled to Claude Code specifically)
| Module | What's coupled | Refactor ||---|---|---|| `ctx_config.py` | Path defaults → `~/.claude/*` | Config becomes per-adapter; adapter supplies its own paths || `bundle_orchestrator.py` | Emits CC `hookSpecificOutput` JSON | Output becomes adapter-provided (CC adapter keeps today's shape; generic adapter emits plain text / structured JSON for harness consumption) || `context_monitor.py` | Writes `~/.claude/pending-skills.json` | Same — adapter decides the sink path || `mcp_install.py` | `subprocess.run(["claude", "mcp", ...])` | Split: `mcp_install_core` (wiki state + manifest) vs `mcp_install_claude` (CC shell-out). Generic adapter writes MCP config to an adapter-owned `.mcp.json` or sends SIGHUP to the host harness. || `inject_hooks.py` | Writes CC `~/.claude/settings.json` | Adapter-specific — CC adapter only || `skill_loader.py`, `skill_health.py` | CC skill-auto-load assumption | Split loader body from CC-specific launch || `skill_suggest.py` (shim) | PostToolUse → bundle_orchestrator | Adapter-specific |
### Already provider-agnostic (**no refactor**)
| Module | Why it's portable ||---|---|| `resolve_graph.py`, `semantic_edges.py` | Pure NetworkX + numpy. No LLM dependency. || `resolve_skills.py` | Pure ranking. Uses tags/signals but those come from the query, not from CC. || `quality_signals.py`, `skill_quality.py`, `mcp_quality.py` | Pure heuristic scoring. || `wiki_utils.py`, `wiki_sync.py`, `wiki_graphify.py`, `wiki_query.py` | Generic YAML frontmatter + file layout. Wiki *root path* comes from config, not CC. || `catalog_builder.py` | Reads filesystem, writes markdown. No coupling. |
**Net: the model-agnostic core is ~60% of the codebase today.** The adapter work is the remaining ~40%.
---
## 5. Target architecture
```src/ctx/├── __init__.py # public API re-exports│├── core/ # provider-agnostic business logic│ ├── graph/ # resolve_graph + semantic_edges│ ├── quality/ # quality_signals + skill/mcp_quality│ ├── wiki/ # wiki_{sync,graphify,query,utils}│ ├── resolve/ # resolve_skills + stack_skill_map│ └── bundle/ # bundle_orchestrator (adapter-neutral part)│├── adapters/ # per-host integrations│ ├── claude_code/ # TODAY's integration│ │ ├── hooks/ # post_tool_use.py, stop.py, etc.│ │ ├── install/ # skill_install, agent_install, mcp_install (CC branch)│ │ ├── inject.py # inject_hooks equivalent│ │ └── adapter.py # declares how CC speaks to ctx-core│ ││ └── generic/ # NEW — model-agnostic harness│ ├── loop.py # the while-loop│ ├── providers/ # LiteLLM wrapper + per-provider quirks│ │ ├── litellm_provider.py│ │ └── direct_anthropic.py # optional bypass for tool-use fidelity│ ├── tools/│ │ ├── mcp_router.py # MCP-first tool dispatch│ │ └── registry.py│ ├── state.py # JSONL session, resume, no checkpoint yet│ ├── context.py # compaction (simple summary strategy v1)│ └── adapter.py # declares how the generic harness speaks to ctx-core│├── cli/ # all user-facing CLIs│ ├── skill_install.py # ctx-skill-install (wraps adapter)│ ├── agent_install.py # ctx-agent-install│ ├── mcp_install.py # ctx-mcp-install│ ├── run.py # NEW: ctx run --provider=... --model=...│ ├── graphify.py # ctx-wiki-graphify│ └── ...│├── mcp_server/ # NEW: expose ctx-core over MCP│ ��── server.py # ctx-mcp-server → tools: recommend_bundle, install, graph_query│└── utils/ # _safe_name, _fs_utils, _file_lock```
### Data flow — generic harness
``` user query │ ▼ ctx/cli/run.py ──────────────────────────── (resolve provider from --provider flag) │ ▼ ctx/adapters/generic/loop.py │ ├──► ctx/core/resolve (pick top-K skill/agent/MCP bundle) │ └──► ctx/core/graph + ctx/core/quality (provider-agnostic) │ ├──► ctx/adapters/generic/providers/litellm_provider (model call) │ └──► openai / minimax / gemini / anthropic / ollama / … │ ├──► ctx/adapters/generic/tools/mcp_router (tool dispatch) │ └──► attached MCP servers (including ctx's own mcp_server!) │ └──► ctx/adapters/generic/state (append session JSONL)```
### Data flow — Claude Code (unchanged UX)
``` CC hook fires │ ▼ ctx/adapters/claude_code/hooks/post_tool_use.py │ ├──► ctx/core/resolve (same code path) ├──► ctx/core/bundle (same) └──► emit CC hookSpecificOutput JSON (adapter-specific)```
Both flows share `core/`. The adapter folders own only the thin edges.
---
## 6. Repo reorganization — phased migration
Per CLAUDE.md phased-execution rule: **max 5 files per phase**, each phase ships green before the next starts.
### Phase R0 — scaffolding only (no code moves)- Create `src/ctx/__init__.py`, `src/ctx/core/`, `src/ctx/adapters/`, `src/ctx/cli/`, `src/ctx/utils/` (empty dirs + `__init__.py`)- Update `pyproject.toml` to declare `packages = ["ctx", "ctx.core", ...]` alongside existing flat `py-modules` (transitional — both work)- Add `docs/plans/001-model-agnostic-harness.md` (this file)- Files touched: ~8 (all new)- Verification: full suite still 2,654 passing
### Phase R1 — move utilities- Move `_safe_name.py`, `_fs_utils.py`, `_file_lock.py` → `src/ctx/utils/`- Update imports in every dependent module to `from ctx.utils import ...`- Keep legacy shim: `src/_safe_name.py` → `from ctx.utils._safe_name import *` (deprecation)- Files touched: 3 source + ~15 import updates across the codebase- Verification: suite green
### Phase R2 — move graph/quality/resolve core (already pure)- Move `resolve_graph.py`, `resolve_skills.py`, `semantic_edges.py`, `stack_skill_map.py`, `quality_signals.py` → `src/ctx/core/`- Files touched: 5- Verification: suite green
### Phase R3 — move wiki- Move `wiki_utils.py`, `wiki_sync.py`, `wiki_graphify.py`, `wiki_query.py`, `wiki_lint.py` → `src/ctx/core/wiki/`- Files touched: 5
### Phase R4 — move Claude Code adapter code- Move `mcp_install.py`, `skill_install.py`, `agent_install.py` → `src/ctx/adapters/claude_code/install/`- Move `bundle_orchestrator.py`, `skill_suggest.py`, `context_monitor.py` → `src/ctx/adapters/claude_code/hooks/`- Move `inject_hooks.py` → `src/ctx/adapters/claude_code/`- Files touched: ~8 — **exceeds 5-file phase rule, split across R4a + R4b**
### Phase R5 — CLI entrypoints- Thin wrappers under `src/ctx/cli/` — each is ~10 lines re-exporting from its adapter- Update `pyproject.toml` scripts section- Files touched: ~6
### Phase R6 — tests mirror the package tree- Move `src/tests/test_resolve_graph*.py` → `tests/core/test_resolve_graph*.py`- And so on- Largest phase but mechanical. Split if necessary.
After R6: drop legacy shims, drop flat `py-modules` from pyproject.toml, single `packages = ["ctx"]`.
### Git hygiene per phase- Each phase = one commit with test verification- Use `git mv` so history follows the files (not `delete+add`)- Conventional commit prefixes: `refactor(repo): phase R1 — move utilities to ctx.utils`- Don't mix R-phases with feature commits. Freeze feature work during the R-sequence or branch.
---
## 7. Harness work — phased after repo is reorganized
(All phases below assume repo is post-R6.)
### Phase H1 — provider adapter skeleton- `src/ctx/adapters/generic/providers/litellm_provider.py`: thin wrapper with `complete(messages, tools=None, **kwargs)` returning a provider-normalized response shape- Config: `~/.ctx/harness-config.json` with `{provider, model, api_key_env, base_url}` — NOT in `~/.claude/`- Test: mock LiteLLM, exercise the four main providers (openai, anthropic, gemini, ollama) with fake responses- Files touched: 3- Success criteria: `python -c "from ctx.adapters.generic.providers import complete; print(complete([{'role':'user','content':'hi'}]))"` returns a structured response
### Phase H2 — MCP router- `src/ctx/adapters/generic/tools/mcp_router.py`: given a list of MCP server configs, spawn them as subprocesses + maintain stdio streams + route tool calls- Reuses `claude mcp` schema (MCP is the protocol, not the host)- Test: spawn a mock MCP server (fs stub), confirm tool list + tool call + tool result round-trip- Files touched: 4- Success criteria: `mcp_router.list_tools(["filesystem"])` returns the server's tool schema
### Phase H3 — the while-loop- `src/ctx/adapters/generic/loop.py`: read query, call provider, check for tool_use, dispatch via mcp_router, append to messages, repeat until no tool_use- Stop conditions: model returns no tool_use | max_iterations | cost_budget_exceeded | user abort- Test: fake provider that returns 2 tool calls then a plain response; confirm loop runs 3 model calls + 2 tool dispatches- Files touched: 3- Success criteria: a minimal demo task works end-to-end against openai + anthropic + ollama
### Phase H4 — state & session- Append-only JSONL per session at `<ctx_dir>/sessions/<session_id>.jsonl`- Resume: `ctx run --resume <session_id>` replays the JSONL and continues- Files touched: 2
### Phase H5 — context compaction (v1: summarize-on-overflow)- When next call would exceed provider's context window, summarize all but last N messages via a separate call- Keep strategy simple; defer LangGraph-style per-step checkpointing- Files touched: 1
### Phase H6 — integrate ctx-core- Harness auto-attaches ctx's own MCP server (`ctx-mcp-server`) at startup- Every turn, expose `recommend_bundle(query)` / `graph_query(seeds)` / `install(slug)` to the model- The skill/graph/quality system is now usable FROM the harness- Files touched: 2
### Phase H7 — CLI UX- `ctx run --provider --model --task --mcp` (comma-list)- `ctx run --resume`- `ctx run --list-sessions`- Files touched: 1
### Phase H8 — ctx MCP server (ships independently too)- `src/ctx/mcp_server/server.py`: exposes ctx-core as an MCP server any MCP-speaking harness can attach- This is the Option A deliverable; option C ships it anyway because our own harness uses it- Files touched: 2
### Phase H9 — adapters for specific hosts (as demand arises)- Aider: shell-out or import adapter- Goose: MCP server is enough (Goose speaks MCP)- Cline: MCP server is enough- Custom: documented public API in `ctx/__init__.py`
### ── SHIP v1 ──
At this point `ctx run --provider openrouter --model minimax/minimax-m1 --task ...` works end-to-end with a solo agent. Measure failure modes on real tasks before adding P/G/E scaffolding.
### Phase H10 — Planner agent (evidence-driven)**Trigger:** solo-agent runs consistently fail on tasks that need multi-step decomposition (spec-to-implementation gap, scope drift, planner-less overruns).- Separate Planner agent that expands vague prompts into structured specs (Anthropic pattern §5: "Specification Artifact")- Planner → Generator handoff via file-based artifacts (not inline messages)- `ctx run --planner` flag opts in; default stays solo- Files touched: ~3
### Phase H11 — Evaluator agent (evidence-driven)**Trigger:** self-evaluation bias observed in H1-H10 runs — generator declares success on outputs a human would reject.- Separate Evaluator agent with explicit grading criteria + few-shot calibration- Feedback loop drives regeneration- `ctx run --evaluator` flag opts in (usually with `--planner` together)- Files touched: ~3
### Phase H12 — Sprint contracts**Trigger:** Evaluator and Generator disagree on "done" criteria in practice.- Contract artifact agreed before implementation- Hard pass/fail thresholds per criterion- Files touched: ~2
### ── SHIP v2 (full three-agent harness) ──
Match Anthropic's reference pattern. Expect 3-5x token cost vs solo. Worth it for high-stakes autonomous runs; overkill for simple edit-a-file tasks. `ctx run --mode=solo|triad` flag exposes both.
---
## 8. Risks & open questions
### Risks
| Risk | Mitigation ||---|---|| Repo reorg breaks downstream import paths | Phase R1-R6 with deprecation shims; 6-month shim deprecation window || LiteLLM has a bug for the user's target provider (e.g., MiniMax) | Factor providers behind a `ModelProvider` protocol so direct-SDK bypass is trivial; LiteLLM is the default but not a hard dep || Harness loop divergence — we own bugs CC used to hide | Keep loop minimal (H1-H3 ship as ~300 LOC). Study SWE-agent's loop as a known-good reference || Context compaction is hard and model-specific | Ship simple summarize-on-overflow in H5; swap for better strategy later. Don't block the release || "Alive skill" semantics may not map to harnesses that don't auto-load | Our MCP server exposes recommendation as a tool; model explicitly asks for skills. Harness-agnostic. || Self-evaluation anti-pattern (Anthropic §4) if users wire ctx's quality scorer as grader for its own output | Document that quality signals are for *discovery*, not for grading agent outputs || Strix-style scanning of the new harness surface | Every new adapter module ships with security tests (no-test-no-merge already enforces this) |
### Open questions — need user decision
1. **Which option?** A (library + MCP server only), B (full harness), or C (minimal harness + MCP server + CC adapter)? My recommendation: C.2. **Repo reorg scope** — all phases R0-R6 as proposed, or stop after R3 (core only)?3. **Which providers ship in H1?** LiteLLM gives us ~100 for free, but which 3-5 are the "tier-1 tested" set? MiniMax + GPT-5.5 + Anthropic + Ollama + (?)4. **Is `~/.ctx/` the right new config root**, or do we keep everything under the adapter-owned directory (`~/.claude/` for CC adapter, `~/.ctx/` for generic)?5. **Do we want the Planner/Generator/Evaluator split (Anthropic's recommended pattern) in v1**, or defer to a later phase? My recommendation: defer — it's load-bearing for *product builds* specifically, not for general agentic coding tasks.6. **Checkpointing — LangGraph-style per-step, or session-level JSONL replay only (Claude Agent SDK pattern)?** v1 = JSONL replay; revisit if users ask for time-travel.7. **License / distribution** — publish as a pip package (`pip install ctx-harness` or similar) after the reorg? Repo is already clean enough if we want to.
---
## 9. Non-goals
- We are **not** replacing Claude Code as a harness. The CC integration stays first-class.- We are **not** competing with SWE-agent / OpenAI Agents SDK / LangGraph on general-purpose agent features. Our differentiator is the **alive skill / knowledge graph / quality scoring** system, not the while-loop.- We are **not** going to reinvent LiteLLM. It's a fixed dependency for provider abstraction.- We are **not** reimplementing MCP. It's the protocol, not something we own.- We are **not** building Planner/Generator/Evaluator in v1 (defer; Anthropic's pattern is load-bearing for product-build tasks specifically).
---
## 10. Success criteria
**Minimum viable** (end of Phase H7):```bashctx run --provider openai --model gpt-5.5 --mcp ctx,filesystem \ --task "find the failing tests in this repo and fix them"```- Runs to completion or max-iterations without crashing- Cost tracked + shown- Session JSONL persisted; resumable via `--resume`- ctx's own skill-recommendation MCP server gets consulted at least once (evidence in the JSONL)- Same task against `--provider anthropic --model claude-opus-4-7` works identically (byte-diff on artefact level, not prose)
**Full delivery** (end of Phase H9):- 3 adapters ship: claude_code (existing), generic (new), aider (new)- `ctx-mcp-server` is published + a Cline/Goose recipe documents attaching it- Coverage floor on new code: 80%+ (current floor is 40%; ratchet up)- Full docs under `docs/harness/`
---
## Appendix A — harness comparison table
(See `docs/plans/001-research-appendix.md` for the full survey with citations. Summary inline §2.)
## Appendix B — detailed file-move map for each R-phase
(To be filled in as each R-phase ships. R0 scaffolding only — no files move.)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209# Skill Quality — Plan
Living plan for the **skill quality scoring + lifecycle** initiative.
Keep this file terse and current. Detailed work lives in GH issues linked per phase.
## Vision
Every skill and agent in `~/.claude/skills` and `~/.claude/agents` carries a
continuous **quality score** that updates automatically as signals change.
Low-scoring entries are proposed for demotion, archival, or deletion via a
propose-and-confirm CLI. High-scoring entries earn priority in the router.
The goal: keep the corpus from decaying as it grows past 1,700 skills,
without asking the user to curate by hand.
## Principles
- **Evidence-weighted, not opinion-driven.** Score = weighted sum of four
measurable signals. No manual grades.
- **Propose, don't mutate.** The lifecycle CLI prints proposed actions and
waits for confirmation. `--auto` unlocks the non-destructive tiers; the
**Delete** tier always requires human confirmation regardless of `--auto`.
- **Live on the knowledge graph.** The score is a node attribute on the
wiki graph that changes in real time, not a static frontmatter number.
Frontmatter + sidecar JSON + wiki page mirror it for auditability.
- **Asymmetric lifecycle.** Demotion is automatic; promotion back is
deliberate, through a dedicated `--review-archived` CLI.
- **Config-driven thresholds.** Weights, score cutoffs, lifecycle cadence
— all live under `config.json` so advanced users can tune without code
changes.
## Signals (Q1)
| Signal | Source | Range | Intent |
|---|---|---|---|
| **telemetry** | `~/.claude/intent-log.jsonl` + `skill-manifest.json` | 0–1 | Did the skill get loaded? Used after load? How recently? |
| **intake warnings** | `IntakeDecision.findings` captured at install | 0–1 | Was this flagged as near-dup / thin body / orphan at install? |
| **graph connectivity** | `graph/wiki-graph.tar.gz` edges | 0–1 | How many incoming + outgoing wiki-links? Isolated nodes score low. |
| **routing hit rate** | router trace logs | 0–1 | When the router considered this skill, did it pick it? |
## Score formula (Q2)
```
raw = w_t * telemetry + w_i * intake + w_g * graph + w_r * routing
score = clamp(raw, 0, 1) — then apply hard floors
grade = A if score >= 0.80
B if score >= 0.60
C if score >= 0.40
D otherwise
# Hard floors override the weighted score:
# intake_fail → F (blocked at install; should not exist in corpus)
# never_loaded AND age > stale_threshold_sessions → D regardless of graph/intake
```
Default weights: `w_t=0.40`, `w_i=0.20`, `w_g=0.25`, `w_r=0.15`.
All exposed under `config.json::quality`.
## Persistence (Q3)
Write score to **four sinks** on every compute:
1. **Knowledge-graph node attribute** — live, re-renders on wiki refresh.
This is the source of truth; everything else is a mirror.
2. **Frontmatter** — `quality_score`, `quality_grade`, `quality_updated_at`
on the converted wiki page.
3. **Sidecar JSON** — `~/.claude/skill-quality/<slug>.json` for machine
consumption without parsing frontmatter.
4. **Wiki page** — a `## Quality` section with the current grade + signal
breakdown for human auditability.
## Compute cadence (Q4)
All three triggers, each independently toggleable in `config.json::quality`:
- **Stop-hook piggyback** — on session end, recompute for skills touched
during the session. Cheap, incremental, keeps the score fresh.
- **CLI** - `ctx-skill-quality recompute [--all | --slug <name>]` for
on-demand recomputation.
- **Cron / scheduled** — optional daily full-corpus recompute for
telemetry drift. Off by default; opt-in via `quality.cron.enabled`.
## Action policy (Q5)
Every lifecycle action goes through **propose-and-confirm**:
```
$ ctx-lifecycle review
3 skills eligible for demotion (C → D):
- old-fastapi-patterns: score 0.42, stale 45 sessions
- ...
Proceed? [y/N]
```
- `--auto` flag promotes to auto-apply for Watch and Demote tiers only.
- Archive and Delete always require explicit confirmation.
- Delete additionally prints a **big warning + diff preview** and requires
typing the skill name to confirm. No `--auto` override.
## Four-tier lifecycle (Q6)
| Tier | Entry condition | Action | Reversible? |
|---|---|---|---|
| **Watch** | grade drops to C | tag in frontmatter, surface in next review | yes, automatic |
| **Demote** | grade drops to D for 2+ consecutive recomputes | move from `skills/` to `skills/_demoted/` (router excludes) | yes, via review |
| **Archive** | demoted > archive_threshold_days | move to `skills/_archive/`, remove from graph | yes, via `--review-archived` |
| **Delete** | archived > delete_threshold_days AND `ctx-lifecycle purge` invoked | permanent delete after typed confirmation | NO |
Transitions happen at review time, never silently. Cadence + thresholds
in `config.json::quality.lifecycle`.
## Promotion back (Q7)
Asymmetric by design — automatic demotion, deliberate promotion:
- `ctx-lifecycle --review-archived` — prints archived skills with their
last score and a preview of what changed since archival (git diff
against the archive point).
- Promotion restores to `skills/` and recomputes score immediately.
- No automatic promotion from Archive; the user must invoke the CLI.
## KPI categories (Q8)
Skills/agents carry both:
- **Tags** (free-form, existing): `python`, `testing`, `aws`, ...
- **Category** (new, closed set): one of `framework`, `language`, `tool`,
`pattern`, `workflow`, `meta`.
Dashboard shows:
- Score distribution by category (are `framework` skills healthier than
`pattern` skills?)
- Trend: percentage of corpus in each grade over time
- Top-10 demotion candidates
- Archived-but-restorable count (leading indicator of user regret)
## Phases
### Phase 3 — Post-install scoring module ← next
Files: `src/skill_quality.py`, `src/quality_signals.py`,
`src/tests/test_skill_quality.py`, `src/config.json` (new `quality`
section), `src/ctx_config.py` (extend for `quality_*` fields).
- [ ] `quality_signals.py` — four signal extractors, each returning a
normalized 0–1 float + raw evidence. Deterministic given inputs.
- [ ] `skill_quality.py` — score aggregation, hard floors, grade mapping,
four-sink persistence. Includes CLI `recompute` / `show` / `explain`.
- [ ] Stop-hook integration — recompute only for skills touched this
session (incremental path).
- [ ] Knowledge-graph node attribute writer — extends `graph/build_wiki_graph.py`
to emit `quality_score`, `quality_grade` on each skill node.
- [ ] `config.json::quality` section with weights, thresholds, cadence toggles.
- [ ] Tests: signal extractors are deterministic; hard floors fire correctly;
stop-hook incremental path matches full recompute on touched slugs.
### Phase 4 — Lifecycle CLI + KPI dashboard
Files: `src/ctx_lifecycle.py`, `src/kpi_dashboard.py`,
`src/tests/test_ctx_lifecycle.py`, `docs/quality/dashboard.md`.
- [ ] `ctx_lifecycle.py` — `review`, `demote`, `archive`, `purge`,
`--review-archived`, `--auto`. Propose-and-confirm on every action;
typed confirmation for purge.
- [ ] Tier transitions: Watch → Demote → Archive → Delete, reading
`config.json::quality.lifecycle` thresholds.
- [ ] `kpi_dashboard.py` — markdown report generator with distribution
tables and trend charts (sparkline per category).
- [ ] Add `category:` field to skill frontmatter schema + backfill script
that infers category from existing tags where unambiguous.
- [ ] Archive recovery preview: git-diff between archive point and HEAD
for the archived skill's source file.
### Phase 5 — Agent parity
Files: `src/skill_telemetry.py` (add subject_type discriminator),
`src/usage_tracker.py` (extend to agent pages), `src/agent_quality.py`.
- [ ] `skill_telemetry.py` — subject-type discriminator so the same
module tracks both skills and agents without collision.
- [ ] `usage_tracker.py` — extend to agent entity pages in the wiki.
- [ ] Short interview to confirm agent-specific signal weights (likely
different — agents are invoked less often but more deliberately).
- [ ] Reuse Phase 3 + 4 machinery for agents; single quality backbone.
## Open decisions (captured during interview)
- Signals: telemetry + intake warnings + graph connectivity + routing hit rate.
- Scoring: weighted sum + hard floors → A/B/C/D grade.
- Persistence: frontmatter + sidecar JSON + wiki page + **live KG node attribute**.
- Cadence: Stop-hook + CLI + cron, all config-toggleable.
- Policy: propose-and-confirm with `--auto` for Watch/Demote only; Delete always human-gated.
- Lifecycle: four tiers Watch → Demote → Archive → Delete.
- Promotion: asymmetric; dedicated `--review-archived` CLI.
- KPIs: both `tags:` (free-form) and `category:` (closed set).
- Order: M2.10 (done) → this plan doc (done) → Phase 3 → Phase 4 → agents.
## Out of scope (v1)
- Cross-machine score sync (local-only).
- ML-based scoring (start deterministic; revisit if signals prove noisy).
- Community quality leaderboard.
- Rewriting / auto-fixing low-scoring skills (we only demote/archive).
## Tracking
GH issues live under the `skill-quality-v1` milestone. One issue per phase.
This file is updated each time a phase completes.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141# Toolbox Feature — Plan
Living plan for the **pre/post dev toolbox + behavior-learning + docs** initiative.Keep this file terse and current. Detailed work lives in GH issues linked per phase.
## Vision
Let the user declare **named bundles of skills/agents** that load *before* (`pre`) orrun *after* (`post`) a development task. Learn from the user's invocation patternsover time and propose new bundles. Surface everything through slash commands, aCLI, and a version-controlled config.
## Principles
- **Foundation first.** Ship data model + CLI + 5 starter toolboxes before any hook integration or learning. Each phase is independently usable.- **User-configurable everything.** Dedup policy, suggestion loudness, trigger set, council composition — all settable per toolbox with sensible defaults.- **Evidence over opinion.** Suggestions cite real usage data + knowledge-graph edges. No black-box "trust me" prompts.- **Token discipline.** Every council run respects a declared `max_tokens` / `max_seconds` budget. No runaway cost.
## Data model (canonical)
```jsonc// ~/.claude/toolboxes.json (global) OR .toolbox.yaml (per-repo, overrides global){ "version": 1, "toolboxes": { "ship-it": { "description": "Professional council for end-of-feature review", "pre": [], "post": [ "code-reviewer", "security-reviewer", "architect-review", "test-automator", "performance-engineer", "accessibility-tester", "docs-lookup" ], "scope": { "projects": ["*"], "signals": ["python", "typescript", "rust", "go"], "analysis": "dynamic" // "diff" | "full" | "graph-blast" | "dynamic" }, "trigger": { "slash": true, "pre_commit": true, "session_end": true, "file_save": null // glob or null }, "budget": { "max_tokens": 150000, "max_seconds": 300 }, "dedup": { "window_seconds": 600, "policy": "fresh" }, // "fresh" | "cached" "guardrail": false // true => block commit on HIGH findings } }, "active": ["ship-it"]}```
## Phases
### Phase 1 — Foundation (data model, CLI, templates, tests)
Files: `src/toolbox.py`, `src/toolbox_config.py`, `src/tests/test_toolbox.py`,`skills/toolbox/SKILL.md`, `docs/toolbox/templates/*.yaml`.
- [ ] `toolbox_config.py` — JSON/YAML loader with global + per-repo merge.- [ ] `toolbox.py` — CLI: `list`, `show`, `activate`, `deactivate`, `init`, `export`, `import`, `validate`.- [ ] 5 starter templates: `ship-it`, `security-sweep`, `refactor-safety`, `docs-review`, `fresh-repo-init`.- [ ] Slash command wrappers under `skills/toolbox/` mapping to CLI.- [ ] Regression tests (data model round-trip, CLI happy paths, config merge precedence).
### Phase 2 — Hook integration + council runner
- [ ] Extend existing pre-commit hook with optional council stage.- [ ] `src/council_runner.py` — runs the post list with budget enforcement.- [ ] Session-start / session-end / file-save hook handlers.- [ ] Dedup cache at `~/.claude/toolbox-runs/<hash>.json`.- [ ] Graph-informed blast radius: read `graph/wiki-graph.tar.gz` edges to compute transitively affected files for `"analysis": "graph-blast"`.
### Phase 3 — Behavior miner + suggestion surface
- [ ] `src/behavior_miner.py` — mines `~/.claude/intent-log.jsonl` + `~/.claude/skill-manifest.json` + `git log` for four signals: agent co-invocation, skill load/unload cadence, file-type → agent correlations, commit-message-type correlations.- [ ] `~/.claude/user-profile.json` — acceptance rate, opted-out suggestions, cadence preferences.- [ ] Suggestion surface: real-time digest (batched, not interrupt-style) + session-end digest. Cadence user-configurable.
### Phase 4 — Intent interview + guardrails + retrospective + explainability
- [ ] `src/intent_interview.py` — structured interview for blank repos and existing repos. Auto-prompt on empty-repo detection with one-click skip.- [ ] Slash: `/toolbox init` and `/toolbox suggest`.- [ ] Guardrail mode: when enabled per-toolbox, blocks the commit on HIGH findings.- [ ] Session-end retrospective summarizing skills/agents used + council verdicts.- [ ] Explainability: every suggestion includes graph evidence + log citations.
### Phase 5 — Documentation site (MkDocs Material)
- [ ] `mkdocs.yml` + Material theme + GH Pages deploy action.- [ ] Pages: getting started, concepts, CLI reference, hook integration, starter toolboxes, behavior learning, FAQ.- [ ] Keep the existing README as landing; site = deep docs.
### Phase 6 — Curation & self-healing add-ons
- [ ] Skill health dashboard: stale skills, never-used-after-load, high-cost-low-value.- [ ] Self-healing catalog: nightly diff-scan backfills catalog + graph when skills/agents are added outside the wiki flow.- [ ] Diff-aware memory anchoring: project memories auto-expire when the referenced code is no longer present.- [ ] Community toolbox registry (read-only index repo).
## Open decisions (captured during interview)
- Council composition: **Full 7** = code-reviewer, security-reviewer, architect-review, test-automator, performance-engineer, accessibility-tester, docs-lookup. Overridable per toolbox.- Triggers: all four (slash, pre-commit, session-end, file-save), configurable per toolbox.- Dedup: fresh-by-default, toolbox-overridable.- Intent interview: auto-prompt on empty repo with skip, plus `/toolbox init`, plus CLI wizard.- Behavior signals: all four enabled.- Loudness: user-configurable; default = session-end digest + batched real-time.- Scope: global + per-repo, repo overrides global.- Docs: MkDocs Material on GH Pages.- Ship order: foundation first.
## Out of scope (v1)
- Hosted cloud-sync of user-profile (local-only).- Non-Claude-Code integrations (VS Code extension, Cursor, etc.).- Paid/premium toolbox tiers.
## Tracking
GH issues live under the `toolbox-v1` milestone. One issue per phase + oneper starter toolbox template. `plan.md` (this file) is updated each time aphase completes.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758<?xml version="1.0" encoding="UTF-8"?><!-- LaunchAgent for the ctx backup watchdog (macOS).
Install: 1. Edit the two path strings below so CTX_REPO matches your checkout and PYTHON matches your interpreter (e.g. the one from `which python3` or a venv). 2. cp docs/services/macos/com.claude.backup.watchdog.plist \ ~/Library/LaunchAgents/ 3. launchctl load -w ~/Library/LaunchAgents/com.claude.backup.watchdog.plist
Tail logs: tail -f ~/Library/Logs/claude-backup-watchdog.log
Unload: launchctl unload ~/Library/LaunchAgents/com.claude.backup.watchdog.plist
The agent runs in the user session (not at boot) and restarts on crash.--><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict> <key>Label</key> <string>com.claude.backup.watchdog</string>
<!-- EDIT THIS: python interpreter + repo path --> <key>ProgramArguments</key> <array> <string>/usr/bin/python3</string> <string>/Users/YOUR_USER/ctx/src/backup_mirror.py</string> <string>watchdog</string> <string>--interval</string> <string>60</string> </array>
<key>RunAtLoad</key> <true/>
<!-- Relaunch on crash with a short backoff so we don't busy-loop. --> <key>KeepAlive</key> <dict> <key>SuccessfulExit</key> <false/> </dict> <key>ThrottleInterval</key> <integer>30</integer>
<key>StandardOutPath</key> <string>/Users/YOUR_USER/Library/Logs/claude-backup-watchdog.log</string> <key>StandardErrorPath</key> <string>/Users/YOUR_USER/Library/Logs/claude-backup-watchdog.log</string>
<key>ProcessType</key> <string>Background</string></dict></plist>12345678910111213141516171819202122232425262728293031323334353637383940# Systemd user unit for the ctx backup watchdog.## Install:# mkdir -p ~/.config/systemd/user# cp docs/services/systemd/claude-backup-watchdog.service \# ~/.config/systemd/user/# # Edit the copy: set CTX_REPO to the absolute path of this checkout# # and confirm your python3 path (e.g. /usr/bin/python3).# systemctl --user daemon-reload# systemctl --user enable --now claude-backup-watchdog.service## Status / stop / tail:# systemctl --user status claude-backup-watchdog.service# systemctl --user stop claude-backup-watchdog.service# journalctl --user -u claude-backup-watchdog.service -f
[Unit]Description=Claude ~/.claude backup watchdog (ctx)After=default.target
[Service]Type=simple# Adjust CTX_REPO to your checkout, and Python if you use a venv.Environment=CTX_REPO=%h/ctxExecStart=/usr/bin/python3 ${CTX_REPO}/src/backup_mirror.py watchdog --interval 60# Crash-recover: back off 5s between restarts, give up after 3 fast crashes.Restart=on-failureRestartSec=5StartLimitIntervalSec=60StartLimitBurst=3# Least-privilege: the watchdog only needs to read ~/.claude and write# ~/.claude/backups. No network. No privilege escalation.NoNewPrivileges=yesPrivateTmp=yesProtectSystem=strictProtectHome=read-onlyReadWritePaths=%h/.claude/backups
[Install]WantedBy=default.target123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120# install-backup-watchdog.ps1## Registers the ctx backup watchdog as a Windows Scheduled Task.# The task runs under the current user, starts at logon, and restarts# on failure. Nothing elevated — a standard user can install, run, and# remove the task without administrator rights.## Usage:# # From a PowerShell prompt inside this repo:# pwsh -File docs/services/windows/install-backup-watchdog.ps1## Flags:# -RepoPath Absolute path to this ctx checkout. Defaults to the# repo the script lives in.# -Python Absolute path to the Python interpreter. Auto-detected# via `where python` when omitted.# -Interval Seconds between polls. Default 60.# -Uninstall Remove the task and exit.## Inspect afterwards:# Get-ScheduledTask -TaskName 'ClaudeBackupWatchdog'# Get-ScheduledTaskInfo -TaskName 'ClaudeBackupWatchdog'## Remove:# pwsh -File docs/services/windows/install-backup-watchdog.ps1 -Uninstall
[CmdletBinding()]param( [string]$RepoPath = (Resolve-Path "$PSScriptRoot\..\..\..").Path, [string]$Python = $null, [int]$Interval = 60, [switch]$Uninstall)
$ErrorActionPreference = 'Stop'$TaskName = 'ClaudeBackupWatchdog'
if ($Uninstall) { if (Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue) { Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false Write-Host "[uninstall] removed scheduled task $TaskName" } else { Write-Host "[uninstall] task $TaskName is not registered; nothing to do" } return}
# --- Validate inputs ----------------------------------------------------------
$MirrorScript = Join-Path $RepoPath 'src\backup_mirror.py'if (-not (Test-Path $MirrorScript)) { throw "backup_mirror.py not found under $RepoPath. Pass -RepoPath correctly."}
if (-not $Python) { $Python = (Get-Command python -ErrorAction SilentlyContinue).Source if (-not $Python) { throw "Python interpreter not found on PATH. Pass -Python <path>." }}if (-not (Test-Path $Python)) { throw "Python path does not exist: $Python"}
if ($Interval -lt 5 -or $Interval -gt 3600) { throw "Interval must be between 5 and 3600 seconds (got $Interval)."}
# --- Build the task ----------------------------------------------------------
$Arguments = "`"$MirrorScript`" watchdog --interval $Interval"
$Action = New-ScheduledTaskAction ` -Execute $Python ` -Argument $Arguments ` -WorkingDirectory $RepoPath
# Run at user logon. The watchdog itself sleeps between polls, so we# don't need a repetition trigger on top.$Trigger = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME
# Settings: allow on battery, restart on failure, no time limit.$Settings = New-ScheduledTaskSettingsSet ` -AllowStartIfOnBatteries ` -DontStopIfGoingOnBatteries ` -RestartCount 3 ` -RestartInterval (New-TimeSpan -Minutes 1) ` -ExecutionTimeLimit (New-TimeSpan -Days 0) ` -StartWhenAvailable
$Principal = New-ScheduledTaskPrincipal ` -UserId $env:USERNAME ` -LogonType Interactive ` -RunLevel Limited
$Description = "Snapshots ~/.claude/ on change. Source: $RepoPath"
$Task = New-ScheduledTask ` -Action $Action ` -Trigger $Trigger ` -Settings $Settings ` -Principal $Principal ` -Description $Description
# Replace any previous registration.if (Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue) { Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false}Register-ScheduledTask -TaskName $TaskName -InputObject $Task | Out-Null
# Kick it off now so the user sees a snapshot folder appear.Start-ScheduledTask -TaskName $TaskName
Write-Host "[install] registered scheduled task $TaskName"Write-Host " python: $Python"Write-Host " script: $MirrorScript"Write-Host " interval: ${Interval}s"Write-Host ""Write-Host "Inspect: Get-ScheduledTaskInfo -TaskName '$TaskName'"Write-Host "Remove: pwsh -File '$PSCommandPath' -Uninstall"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171# Skill lifecycle & KPI dashboard — install & operations
One page on running the Phase 4 lifecycle CLI, the category backfill,
and the KPI dashboard. Prerequisite: Phase 3 scorer is installed and
has written at least one sidecar. See
[skill-quality-install.md](./skill-quality-install.md).
## What it does
After the scorer has labeled everything, these three tools turn the
labels into action:
| Tool | CLI | Purpose |
| ---- | --- | ------- |
| `ctx_lifecycle.py` | `review`, `demote`, `archive`, `purge`, `review-archived` | Move D/F-grade skills through `active → watch → demote → archive → deleted`. |
| `skill_category.py` | `backfill`, `infer` | Write the closed-set `category:` field into skill/agent frontmatter. |
| `kpi_dashboard.py` | `render`, `summary` | Emit a single Markdown dashboard joined across all quality sinks. |
Asymmetric gates: downward transitions are automatic from a D-streak;
upward transitions are deliberate. Archive needs aging (`active` for
14 days in `_demoted`); delete needs a typed-slug confirmation even
under `--auto`.
## Category taxonomy
Closed set: `framework`, `language`, `tool`, `pattern`, `workflow`,
`meta`. The dashboard groups scores by category so you can see, e.g.,
that your `framework`-tagged skills average a B but your
`workflow`-tagged skills are mostly D — which tells you where to focus
curation.
Inference is precedence-ordered: `python + django` → `language`
(language wins over framework). The backfill **never overwrites** an
existing non-empty value — human edits win.
Run once after the scorer has seeded the sidecars:
```bash
python -m skill_category backfill --dry-run
python -m skill_category backfill # apply
```
Unresolved slugs (no tag matched the taxonomy) are listed for manual
curation.
## Lifecycle CLI
Four verbs. All are propose-and-confirm by default; `--auto` unlocks
only the safe tiers (Watch + Demote).
```bash
# List every pending transition; no writes.
python -m ctx_lifecycle review --dry-run
# Apply all Watch/Demote transitions without prompting.
python -m ctx_lifecycle review --auto
# Archive a specific slug. Requires the demoted aging threshold to have passed.
python -m ctx_lifecycle archive <slug>
# Delete archived slugs that exceeded the delete threshold.
# Requires typed-slug confirmation per entry even with --auto.
python -m ctx_lifecycle purge
# List archived slugs with optional diffs, or restore one.
python -m ctx_lifecycle review-archived --show-diff
python -m ctx_lifecycle review-archived --restore <slug>
```
Filesystem moves: demote → `<skills_dir>/_demoted/<slug>/`, archive →
`<skills_dir>/_archive/<slug>/`. The scanner skips directories starting
with `_`, so demoted/archived skills no longer show up to the router.
Lifecycle state is persisted in a sibling sidecar at
`~/.claude/skill-quality/<slug>.lifecycle.json`. Each transition is
folded into the `history` array (capped at `history_max`) so you can
audit how a slug ended up where it did.
### The D-streak
A skill needs `consecutive_d_to_demote` consecutive D-or-F grades to
trigger a demote proposal. Any A/B/C grade resets the streak to 0. The
default is 2 — one bad session is a blip, two in a row is a trend.
## KPI dashboard
Pure read-only. Walks both quality sidecars and lifecycle sidecars,
joins them against `category:` in frontmatter (with inference
fallback), and emits Markdown or JSON.
```bash
# Dump Markdown to stdout.
python -m kpi_dashboard render
# Persist to a file — good target for the cron / pre-push hook.
python -m kpi_dashboard render --out ~/.claude/skill-quality/kpi.md
# Machine-readable.
python -m kpi_dashboard render --json --out kpi.json
# Terse one-screen summary.
python -m kpi_dashboard summary
```
### What's in the report
- **Grade distribution** — A/B/C/D/F counts + percentages. Blank grade
(no score yet) rolls up to F so it surfaces in the "needs
attention" bucket.
- **Lifecycle tiers** — counts across active/watch/demote/archive.
- **Hard floors active** — how many slugs are failing intake or
never-loaded-stale.
- **By category** — per-category count, average score of
scored entries, and a mini A/B/C/D/F mix table.
- **Top demotion candidates** — up to `--limit N` (default 10) active
or watch-tier entries sorted by (D-streak desc, score asc). These
are the first slugs `ctx_lifecycle review --auto` will act on.
- **Archived (restorable)** — every slug currently in the archive
tier; still recoverable via `review-archived --restore <slug>` until
`purge` deletes them.
## Configuration
All knobs live under `quality` in `src/config.json`:
```json
{
"quality": {
"lifecycle": {
"archive_threshold_days": 14.0,
"delete_threshold_days": 60.0,
"consecutive_d_to_demote": 2,
"demoted_subdir": "_demoted",
"archive_subdir": "_archive",
"history_max": 20
},
"dashboard": {
"default_top_n": 10,
"report_path": "~/.claude/skill-quality/kpi.md"
}
}
}
```
Tighten `consecutive_d_to_demote` to 1 for aggressive pruning, or
loosen `archive_threshold_days` if you want a longer grace window
before a demoted skill gets archived.
## Operational cadence
A reasonable default rhythm, given the defaults above:
- **Every session** — scorer hook runs automatically on session end.
- **Weekly** — `ctx_lifecycle review --auto` to sweep Watch/Demote.
- **Weekly** — `kpi_dashboard render --out …/kpi.md` for the digest.
- **Monthly** — `ctx_lifecycle review` (no `--auto`) to surface
archive-ready demoted skills for manual approval.
- **Quarterly** — `ctx_lifecycle purge` with typed-slug confirmation
to actually remove archived skills past the delete threshold.
## Troubleshooting
- **"unresolved" in backfill output** — the skill's tags don't match
the taxonomy. Either add a matching tag (e.g. `python`) or set
`category:` manually in frontmatter.
- **Dashboard shows skills as F with no score** — they have a
lifecycle sidecar but no quality sidecar. That's intentional:
archived slugs whose quality sidecar was cleaned up still appear
in the tier and archive sections so you can restore them.
- **`review --auto` refuses to archive or delete** — by design. Those
tiers require human approval.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171# Skill quality — install & operations
One page on running the Phase 3 quality scorer: install the Stop hook,
seed the sidecars, and verify the data flows into the wiki and the
knowledge graph.
## What it does
Every installed skill and agent gets a continuous quality score in
`[0.0, 1.0]` plus an A/B/C/D/F letter grade, derived from four signals:
| Signal | Weight | What it measures |
| --------- | -----: | ----------------------------------------------------- |
| telemetry | 0.40 | Load count, recency, freshness in `skill-events.jsonl`|
| intake | 0.20 | Live re-run of the six install-time structural checks |
| graph | 0.25 | Degree + average edge weight in the wiki graph |
| routing | 0.15 | Router hit-rate (neutral prior below 3 observations) |
Two hard floors override the weighted sum:
- **`intake_fail`** — any structural check is currently failing → grade **F**.
Grade F is **only** produced by this hard floor; it is never returned by
the score-to-grade mapping function alone. A score of 0.0 maps to **D**.
- **`never_loaded_stale`** — no load events ever → grade capped at **D**.
The score is mirrored to three on-disk sinks so every consumer sees the
same number:
1. `~/.claude/skill-quality/<slug>.json` — canonical machine-readable form.
2. Wiki entity frontmatter — `quality_score`, `quality_grade`, `quality_updated_at`.
3. Wiki body — a `## Quality` block between `<!-- quality:begin -->` markers.
The knowledge-graph node attribute is a **separate consumer path**, not a
write path from `persist_quality`: `wiki_graphify` reads the sidecar JSON
produced by sink 1 and attaches `quality_score` / `quality_grade` to each
node on its next build.
## Register the Stop hook
The hook runs once per session-end. It reads `skill-events.jsonl` since
its last run, collects every slug that appeared, and calls
`skill_quality.py recompute --slugs <comma-list>` — so scoring is
incremental (touched skills only), not a full 2,000-page sweep.
Edit `~/.claude/settings.json` and add, replacing `<REPO>` with the
absolute path to this checkout (use forward slashes on Windows):
```json
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "python <REPO>/hooks/quality_on_session_end.py"
}
]
}
]
}
}
```
The hook always exits 0: a scoring error will not block session
shutdown.
## Seed the sidecars (first run only)
Run once after install so every installed skill has a baseline score:
```bash
ctx-skill-quality recompute --all
```
This walks `~/.claude/skills/*/SKILL.md` and `~/.claude/agents/*.md`,
scores each, and writes the three on-disk sinks. Expect ~15–30s depending on
corpus size and disk.
## CLI reference
```bash
# Full recompute (use sparingly; the Stop hook handles incrementals).
ctx-skill-quality recompute --all
# One slug.
ctx-skill-quality recompute --slug python-testing
# Show the most recent score.
ctx-skill-quality show python-testing
# Signal-by-signal breakdown with evidence.
ctx-skill-quality explain python-testing
# List every slug with its grade, filtered.
ctx-skill-quality list --grade D
```
All verbs accept `--json` for piping into other tools.
## Graph integration
`wiki_graphify.py` reads the sidecar directory automatically and
attaches `quality_score` and `quality_grade` to every matching node. The
Obsidian graph view can then color nodes by grade — configure the
`quality_grade` property in Obsidian's graph settings.
Nodes without a sidecar get `quality_score: null` and `quality_grade:
null` so downstream consumers can always read the attribute safely.
## Configuration
All knobs live in `src/config.json` under the top-level `quality` key:
```json
{
"quality": {
"weights": {
"telemetry": 0.40, "intake": 0.20, "graph": 0.25, "routing": 0.15
},
"agent_weights": {
"telemetry": 0.15, "intake": 0.30, "graph": 0.35, "routing": 0.20
},
"grade_thresholds": {"A": 0.80, "B": 0.60, "C": 0.40},
"stale_threshold_days": 30.0,
"recent_window_days": 14.0,
"min_body_chars": 120,
"paths": {
"sidecar_dir": "~/.claude/skill-quality",
"router_trace": "~/.claude/router-trace.jsonl"
}
}
}
```
`ctx_config.Config` exposes this through `cfg.get("quality", {})`. User
overrides in `~/.claude/skill-system-config.json` deep-merge over the
repo defaults, so you can pin only the keys you want to change.
Both weight vectors must sum to 1.0 (±0.01) and grade thresholds must
satisfy `0 ≤ C ≤ B ≤ A ≤ 1` — `QualityConfig.__post_init__` will raise
on bad values, catching typos before they pollute sidecars.
### Why two weight vectors
Skills and agents differ in how they're invoked. Skills are loaded
automatically by the router, so **telemetry** (load counts, recency) is
the strongest post-install quality signal — hence 0.40 weight.
Agents are invoked via the Agent tool, deliberately and rarely. A
seldom-used agent isn't stale, it's specialized. The agent weights
shift mass onto **graph connectedness** (0.35) and **intake structure**
(0.30) so agents aren't penalized for having an empty telemetry stream.
The `never_loaded_stale` hard floor, which caps skills at D when they
have zero load events, does **not** apply to agents for the same
reason.
## Troubleshooting
- **Every skill grades D.** Telemetry hasn't accumulated enough load
events yet. This is expected on a fresh install; the stop-hook will
pick up real usage over the next few sessions.
- **A recently-edited skill now grades F.** Open the sidecar and look
at `signals.intake.evidence.checks` — one of the six structural
checks is failing. Fix the file and rerun `recompute --slug <name>`.
- **Wiki page has two `## Quality` sections.** Shouldn't happen —
`persist_quality` is idempotent via the HTML-comment markers. If it
does, delete both blocks and rerun `recompute`; the first pass will
re-emit exactly one.
- **Graph view shows no color.** Run `ctx-wiki-graphify
--graph-only` to rebuild; it reads sidecars fresh on every build.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849# Skill router
The skill router decides which skills, plugins, and MCP servers load intoa session based on the active repository. The full router spec lives in[`docs/SKILL.md`](https://github.com/stevesolun/ctx/blob/main/docs/SKILL.md);this page summarizes the parts most relevant to the docs site.
## Problem
Every skill, plugin, and MCP server loaded into context costs tokens andattention. Most projects need 3–8 skills out of 30+. Loading all of them:
- wastes the context window on irrelevant instructions,- causes skill misfires (wrong skill triggers for a task),- slows response time, and- creates conflicting instructions between skills.
## Architecture
```skill-router/├── SKILL.md # Orchestration logic├── references/│ ├── stack-signatures.md # File/config → stack id│ ├── skill-stack-matrix.md # Which skills serve which stacks│ └── marketplace-registry.md # Known marketplaces└── scripts/ ├── scan_repo.py # Scanner → stack profile JSON ├── resolve_skills.py # Stack → skill set └── skill_loader.py # Load/unload skills into session```
## Flow
1. Repo opens (or Claude detects a `cd`).2. `scan_repo.py` produces a stack profile.3. `resolve_skills.py` maps the profile to a skill set using the [skill-stack matrix](../skill-stack-matrix.md).4. `skill_loader.py` loads selected skills, unloads anything not in the set, and records the choice in the LLM Wiki catalog.
## Reference pages
- [Stack signatures](../stack-signatures.md) — the file/config patterns the scanner uses to identify stacks.- [Skill-stack matrix](../skill-stack-matrix.md) — the mapping from stack identifiers to skill sets.- [Marketplace registry](../marketplace-registry.md) — known skill marketplaces and query patterns.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165# Skill-Stack Matrix
> Maps stack identifiers to the skills that serve them.> Used by resolve_skills.py to determine what to load.
## Table of Contents1. [Matrix Format](#matrix-format)2. [The Matrix](#the-matrix)3. [Companion Rules](#companion-rules)4. [Conflict Rules](#conflict-rules)
---
## Matrix Format
Each entry:- **Stack IDs**: which detected stacks trigger this skill- **Skill**: skill name (matches directory name in /mnt/skills/)- **Priority Base**: starting priority before signal boosts- **Required**: must-load if stack detected, vs nice-to-have- **Companions**: skills that should co-load- **Conflicts**: skills that should not co-load
## The Matrix
### Document Creation Skills
| Skill | Stack IDs | Priority | Required | Path Pattern ||-------|-----------|----------|----------|--------------|| docx | (any -- triggered by user request) | 2 | no | /mnt/skills/public/docx/ || pdf | (any -- triggered by user request) | 2 | no | /mnt/skills/public/pdf/ || pptx | (any -- triggered by user request) | 2 | no | /mnt/skills/public/pptx/ || xlsx | (any -- triggered by user request) | 2 | no | /mnt/skills/public/xlsx/ |
> Note: document skills are demand-loaded, not stack-loaded. They activate on user> request ("make a presentation") not on repo content. The router keeps them in a> "standby" pool -- not loaded into context, but available for instant load.
### Frontend Skills
| Skill | Stack IDs | Priority | Required ||-------|-----------|----------|----------|| frontend-design | react, vue, angular, svelte, nextjs, nuxt, html, css | 8 | yes || react | react, nextjs | 7 | yes || vue | vue, nuxt | 7 | yes || angular | angular | 7 | yes || svelte | svelte | 7 | yes || tailwind | tailwindcss | 5 | no || css-modules | css-modules | 4 | no |
### Backend Skills
| Skill | Stack IDs | Priority | Required ||-------|-----------|----------|----------|| fastapi | fastapi | 8 | yes || django | django | 8 | yes || flask | flask | 7 | yes || express | express | 8 | yes || nestjs | nestjs | 8 | yes || rails | rails | 8 | yes || gin | gin | 7 | yes || actix | actix | 7 | yes |
### Data Skills
| Skill | Stack IDs | Priority | Required ||-------|-----------|----------|----------|| sqlalchemy | sqlalchemy, alembic | 6 | yes || prisma | prisma | 6 | yes || typeorm | typeorm | 6 | yes || drizzle | drizzle | 6 | yes || redis | redis | 4 | no || kafka | kafka | 5 | no || dbt | dbt | 6 | yes |
### Infrastructure Skills
| Skill | Stack IDs | Priority | Required ||-------|-----------|----------|----------|| docker | docker, docker-compose | 6 | yes || kubernetes | kubernetes, helm, kustomize | 6 | yes || terraform | terraform | 7 | yes || github-actions | github-actions | 5 | yes || gitlab-ci | gitlab-ci | 5 | yes || aws | aws-cdk, aws-sam | 7 | yes || vercel | vercel | 4 | no |
### AI/Agent Skills
| Skill | Stack IDs | Priority | Required ||-------|-----------|----------|----------|| langchain | langchain | 7 | yes || llamaindex | llamaindex | 7 | yes || mcp-dev | mcp | 7 | yes || pytorch | pytorch | 6 | yes || huggingface | huggingface | 6 | yes || openai-sdk | openai-sdk | 5 | no || anthropic-sdk | anthropic-sdk | 5 | no |
### Quality Skills
| Skill | Stack IDs | Priority | Required ||-------|-----------|----------|----------|| pytest | pytest | 5 | yes || jest | jest, vitest | 5 | yes || cypress | cypress | 4 | no || playwright | playwright | 4 | no || eslint | eslint | 3 | no || ruff | ruff | 3 | no |
### Documentation Skills
| Skill | Stack IDs | Priority | Required ||-------|-----------|----------|----------|| openapi | openapi | 5 | yes || graphql | graphql | 5 | yes || mkdocs | mkdocs | 4 | no || docusaurus | docusaurus | 4 | no |
### Meta Skills (always available, never unloaded)
| Skill | Stack IDs | Priority | Required | Notes ||-------|-----------|----------|----------|-------|| skill-router | * | 99 | yes | This skill -- always loaded || file-reading | * | 50 | yes | Core capability || skill-creator | * | 10 | no | Standby pool || product-self-knowledge | * | 10 | no | Standby pool |
---
## Companion Rules
When skill A is loaded, also load skill B if its stack is detected:
| Primary Skill | Companion | Condition ||---------------|-----------|-----------|| fastapi | sqlalchemy | DB migrations detected || fastapi | openapi | OpenAPI spec file exists || django | django-orm | (always with django) || react | tailwind | tailwind.config.* exists || docker | docker-compose | docker-compose.yml exists || kubernetes | helm | Chart.yaml exists || terraform | aws | provider "aws" in *.tf || langchain | openai-sdk | openai in deps || pytest | coverage | .coveragerc or coverage config exists |
## Conflict Rules
These skills should not be co-loaded (pick the one with higher confidence/priority):
| Skill A | Skill B | Resolution ||---------|---------|------------|| flask | fastapi | Higher confidence wins || flask | django | Higher confidence wins || jest | vitest | Higher confidence wins || webpack | vite | Higher confidence wins || npm | yarn | Check lock file || npm | pnpm | Check lock file || yarn | pnpm | Check lock file || react | vue | Both can coexist in monorepo || sqlalchemy | prisma | Both can coexist if different services |
> Conflict resolution: check if the repo is a monorepo. In monorepos, "conflicting"> skills may serve different packages and should both load. In single-package repos,> pick the one with higher confidence.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108# Skill health dashboard
[`src/skill_health.py`](https://github.com/stevesolun/ctx/blob/main/src/skill_health.py)
scans `~/.claude/skills/` and `~/.claude/agents/` for structural and
catalog issues, then produces a JSON or human-readable dashboard. It
also self-heals catalog drift — without ever modifying a SKILL.md.
## What it checks
For each skill (`~/.claude/skills/<name>/SKILL.md`) and each agent
(`~/.claude/agents/<name>.md`):
| Code | Severity | Condition |
|---|---|---|
| `missing-file` | error | Skill directory has no SKILL.md |
| `unreadable` | error | File exists but can't be decoded as UTF-8 |
| `no-frontmatter` | error | Missing or malformed `---` YAML fence |
| `frontmatter-missing-name` | error | Frontmatter has no `name:` field |
| `frontmatter-missing-description` | warning | Missing `description:` (router relevance suffers) |
| `empty-body` | error | Fewer than `min_body_lines` non-blank lines |
| `over-threshold` | warning | Line count exceeds `line_threshold` (default 180) |
## Drift detection
`DriftReport` cross-references three sources:
- on-disk entities (skills + agents),
- `~/.claude/skill-manifest.json` → `load[].skill` entries,
- `~/.claude/pending-skills.json` → `graph_suggestions[].name` and
`unmatched_signals[]`.
Anything in the manifest or pending file that doesn't exist on disk
becomes an *orphan*. Orphans are the only thing `heal` is allowed to
touch.
## Self-healing
```bash
ctx-skill-health heal
```
- drops orphaned entries from `skill-manifest.json`
- drops orphaned entries from `pending-skills.json`
- writes atomically (`tempfile.mkstemp` + `os.replace`)
- never modifies SKILL.md files or agent .md files
If nothing needs healing, prints `[heal] nothing to do.` and exits 0.
## CLI
```bash
# Emit a full JSON report
ctx-skill-health scan
# Pretty dashboard
ctx-skill-health dashboard
# CI gate: exit 2 if any error-severity issue or drift is present
ctx-skill-health check --strict
# Apply safe autofixes to manifest + pending
ctx-skill-health heal
```
## Data model
```python
@dataclass(frozen=True)
class Issue:
code: str
severity: str # "warning" | "error"
message: str
@dataclass(frozen=True)
class EntityHealth:
name: str
kind: str # "skill" | "agent"
path: str
lines: int
has_frontmatter: bool
issues: tuple[Issue, ...] = ()
@dataclass(frozen=True)
class DriftReport:
orphaned_manifest: tuple[str, ...] = ()
orphaned_pending: tuple[str, ...] = ()
@dataclass(frozen=True)
class HealthReport:
generated_at: float
entities: tuple[EntityHealth, ...]
drift: DriftReport
totals: dict[str, int]
```
`HealthReport.has_errors` is true when any entity has severity `error`
*or* drift is non-empty — that's the single predicate behind
`check --strict`'s exit code.
## Related
- [Memory anchoring](memory-anchor.md) — dead-reference detection for
auto-memory notes.
- `src/skill_quality.py` (v0.5.0+) — the four-signal quality scorer
(telemetry 0.40, intake 0.20, graph 0.25, routing 0.15) that writes
per-entity sidecars and surfaces A/B/C/D/F grades. The `skill_health`
CLI above focuses on *structural* correctness; `skill_quality`
focuses on *behavioral* quality over time.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164# Stack Signatures Reference
> Maps file patterns and config markers to stack identifiers.> The scanner uses this to classify what a repo contains.> Organized by detection category. Each entry: pattern -> stack identifier + confidence.
## Table of Contents1. [Languages](#languages)2. [Web Frameworks](#web-frameworks)3. [AI/ML Frameworks](#aiml-frameworks)4. [Infrastructure](#infrastructure)5. [Data & Storage](#data-storage)6. [Testing](#testing)7. [Build & Package](#build-package)8. [Documentation](#documentation)9. [AI/Agent Tooling](#aiagent-tooling)
---
## Languages
| Pattern | Stack ID | Confidence | Notes ||---------|----------|------------|-------|| `*.py` + `pyproject.toml` | python | 1.0 | Check `python_requires` for version || `*.py` + `requirements.txt` | python | 0.95 | Older pattern, still common || `*.py` + `Pipfile` | python | 0.95 | || `*.py` + `poetry.lock` | python | 1.0 | || `*.ts` + `tsconfig.json` | typescript | 1.0 | || `*.js` + `package.json` | javascript | 0.9 | Could be TS compiled || `*.rs` + `Cargo.toml` | rust | 1.0 | || `*.go` + `go.mod` | go | 1.0 | || `*.java` + `pom.xml` | java | 1.0 | Maven || `*.java` + `build.gradle` | java | 1.0 | Gradle || `*.kt` + `build.gradle.kts` | kotlin | 1.0 | || `*.rb` + `Gemfile` | ruby | 1.0 | || `*.swift` + `Package.swift` | swift | 1.0 | || `*.cs` + `*.csproj` | csharp | 1.0 | || `*.php` + `composer.json` | php | 1.0 | |
## Web Frameworks
| Pattern | Stack ID | Confidence | Notes ||---------|----------|------------|-------|| `next.config.*` | nextjs | 1.0 | Check for app/ vs pages/ || `nuxt.config.*` | nuxt | 1.0 | || `angular.json` | angular | 1.0 | || `svelte.config.*` | svelte | 1.0 | || `vite.config.*` + react in deps | react | 0.95 | Confirm via package.json || `package.json` has `"react"` | react | 0.9 | Check version for 18 vs 19 || `package.json` has `"vue"` | vue | 0.9 | || `package.json` has `"express"` | express | 0.95 | || `package.json` has `"fastify"` | fastify | 0.95 | || pyproject/req has `fastapi` | fastapi | 0.99 | || pyproject/req has `django` | django | 0.99 | Check for DRF too || pyproject/req has `flask` | flask | 0.95 | || `Gemfile` has `rails` | rails | 1.0 | || `go.mod` has `gin-gonic` | gin | 0.95 | || `Cargo.toml` has `actix-web` | actix | 0.95 | || `Cargo.toml` has `axum` | axum | 0.95 | |
## AI/ML Frameworks
| Pattern | Stack ID | Confidence | Notes ||---------|----------|------------|-------|| deps has `torch` or `pytorch` | pytorch | 0.95 | || deps has `tensorflow` | tensorflow | 0.95 | || deps has `transformers` | huggingface | 0.9 | || deps has `langchain` | langchain | 0.95 | Check core vs community || deps has `llama-index` | llamaindex | 0.95 | || deps has `crewai` | crewai | 0.95 | || deps has `autogen` | autogen | 0.95 | || deps has `semantic-kernel` | semantic-kernel | 0.95 | || deps has `openai` | openai-sdk | 0.8 | Could be indirect || deps has `anthropic` | anthropic-sdk | 0.8 | || deps has `dspy` | dspy | 0.95 | || `*.ipynb` files present | jupyter | 0.85 | |
## Infrastructure
| Pattern | Stack ID | Confidence | Notes ||---------|----------|------------|-------|| `Dockerfile` | docker | 1.0 | || `docker-compose.yml` | docker-compose | 1.0 | || `.github/workflows/*.yml` | github-actions | 1.0 | || `.gitlab-ci.yml` | gitlab-ci | 1.0 | || `Jenkinsfile` | jenkins | 1.0 | || `.circleci/config.yml` | circleci | 1.0 | || `*.tf` files | terraform | 1.0 | || `pulumi.*` or `Pulumi.yaml` | pulumi | 1.0 | || `cdk.json` | aws-cdk | 1.0 | || `template.yaml` (SAM) | aws-sam | 0.9 | Disambiguate from other templates || `serverless.yml` | serverless | 1.0 | || `k8s/` or `kubernetes/` dir | kubernetes | 0.95 | || `helm/` or `Chart.yaml` | helm | 1.0 | || `kustomization.yaml` | kustomize | 1.0 | || `ansible/` or `playbook.yml` | ansible | 0.9 | || `fly.toml` | fly-io | 1.0 | || `vercel.json` | vercel | 1.0 | || `netlify.toml` | netlify | 1.0 | || `render.yaml` | render | 1.0 | || `railway.json` | railway | 1.0 | |
## Data & Storage
| Pattern | Stack ID | Confidence | Notes ||---------|----------|------------|-------|| `alembic/` or `alembic.ini` | sqlalchemy | 0.95 | || `prisma/schema.prisma` | prisma | 1.0 | || deps has `typeorm` | typeorm | 0.95 | || deps has `drizzle-orm` | drizzle | 0.95 | || deps has `sequelize` | sequelize | 0.95 | || `migrations/` + Django | django-orm | 0.9 | || deps has `redis` or `ioredis` | redis | 0.85 | || deps has `kafka` or `confluent-kafka` | kafka | 0.9 | || deps has `celery` | celery | 0.95 | || `dags/` directory | airflow | 0.9 | || `dbt_project.yml` | dbt | 1.0 | || `*.sql` migration files | sql | 0.7 | Generic |
## Testing
| Pattern | Stack ID | Confidence | Notes ||---------|----------|------------|-------|| `pytest.ini` or `conftest.py` | pytest | 1.0 | || `jest.config.*` | jest | 1.0 | || `vitest.config.*` | vitest | 1.0 | || `cypress.config.*` or `cypress/` | cypress | 1.0 | || `playwright.config.*` | playwright | 1.0 | || `.mocharc.*` | mocha | 1.0 | |
## Build & Package
| Pattern | Stack ID | Confidence | Notes ||---------|----------|------------|-------|| `webpack.config.*` | webpack | 1.0 | || `vite.config.*` | vite | 1.0 | || `esbuild.*` in scripts | esbuild | 0.8 | || `turbo.json` | turborepo | 1.0 | || `nx.json` | nx | 1.0 | || `lerna.json` | lerna | 1.0 | || `pnpm-workspace.yaml` | pnpm-workspace | 1.0 | || `yarn.lock` + `workspaces` in pkg.json | yarn-workspace | 0.95 | |
## Documentation
| Pattern | Stack ID | Confidence | Notes ||---------|----------|------------|-------|| `mkdocs.yml` | mkdocs | 1.0 | || `docusaurus.config.*` | docusaurus | 1.0 | || `conf.py` + `index.rst` | sphinx | 0.95 | || `.vitepress/` | vitepress | 1.0 | || `openapi.yaml` or `swagger.yaml` | openapi | 0.95 | || `*.graphql` or `schema.graphql` | graphql | 0.9 | |
## AI/Agent Tooling
| Pattern | Stack ID | Confidence | Notes ||---------|----------|------------|-------|| `mcp.json` or `.mcp/` | mcp | 1.0 | || `CLAUDE.md` | claude-code | 0.95 | || `.cursorrules` | cursor | 0.9 | || `.windsurfrules` | windsurf | 0.9 | || `prompts/` directory | prompt-management | 0.7 | || `.env` with `*_API_KEY` | api-keys | 0.6 | Names only, never values |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990# Behavior miner
[`src/behavior_miner.py`](https://github.com/stevesolun/ctx/blob/main/src/behavior_miner.py)
watches your invocation patterns and proposes toolbox tweaks grounded in
real evidence.
## What it collects
Four signal families, each with `MIN_EVIDENCE = 3` before a suggestion
can surface:
| Signal | Source | Example suggestion |
|---|---|---|
| **Co-invocation** | Pairs of agents invoked in the same session | "You ran `code-reviewer` + `security-reviewer` together 4 times — consider a bundle." |
| **Skill cadence** | Skill load frequency over time | "`python-patterns` loaded every session — promote to `pre`." |
| **File-type** | File extensions of work-in-progress | "60% of your diffs touch `.tf` files — consider a Terraform toolbox." |
| **Commit-type** | Conventional Commit parsing | "8 of your last 10 commits are `fix:` — consider a pre-commit test toolbox." |
## User profile
Signals aggregate into `~/.claude/user-profile.json`:
```jsonc
{
"version": 1,
"updated_at": 1713456789,
"signals": {
"co_invocation": {
"code-reviewer|security-reviewer": 4,
"architect-review|test-automator": 3
},
"skill_cadence": {
"python-patterns": {"loads": 12, "sessions": 12}
},
"file_types": {"py": 87, "md": 31, "tf": 0},
"commit_types": {"fix": 8, "feat": 2}
},
"suggestions": [
{
"id": "bundle:reviewers-pair",
"rationale": "4 co-invocations of code-reviewer + security-reviewer",
"evidence_count": 4
}
]
}
```
## Digest
On `session-end`, the hook calls `format_digest(profile)` and prints
anything new. Example output:
```
[behavior-miner] 2 suggestions:
- bundle:reviewers-pair (4 co-invocations)
→ add to 'review' toolbox:
ctx-toolbox add review --post code-reviewer,security-reviewer
- promote:python-patterns (loaded in 12/12 sessions)
→ promote to 'pre' in your default toolbox
```
Suggestions are never applied automatically. The user runs the command,
or accepts the suggestion via `toolbox init --accept <id>`.
## CLI
```bash
# Rebuild the profile from scratch (scans ~/.claude/history/)
python -m behavior_miner build
# Show current suggestions
python -m behavior_miner show
# Print digest (same output as session-end hook)
python -m behavior_miner digest
# Drop a suggestion (noise reduction)
python -m behavior_miner dismiss bundle:reviewers-pair
```
## Privacy
All signal data stays in `~/.claude/`. Nothing is sent over the network.
The miner never reads file contents — only names, extensions, and commit
message prefixes.
## Related
- [Intent interview](intent-interview.md) — surfaces miner suggestions
during the `toolbox init` flow.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143# Configuration
Toolbox config lives in two files:
| Layer | Path | Format | Scope |
|---|---|---|---|
| **Global** | `~/.claude/toolboxes.json` | JSON | Every repo on this machine |
| **Per-repo** | `.toolbox.yaml` (project root) | YAML | This repo only, overrides global |
Per-repo entries shadow global entries with the same name. Fields absent
from the per-repo file fall back to the global value.
## Schema
```jsonc
{
"version": 1,
"toolboxes": {
"<name>": {
"description": "human-readable purpose",
// Skills to load before the trigger fires
"pre": ["python-patterns", "docs-lookup"],
// Agents to run after
"post": [
"code-reviewer",
"security-reviewer",
"architect-review"
],
"scope": {
// "diff" | "dynamic" | "full"
"analysis": "dynamic",
// Optional: restrict to these glob projects
"projects": ["*"],
// Optional: restrict to these file globs
"files": ["src/**/*.py"]
},
"budget": {
"max_tokens": 60000,
"max_seconds": 180
},
"dedup": {
// "fresh" = always re-run, "user-configurable" = skip
// if same files already reviewed this session
"policy": "user-configurable",
"window_seconds": 3600
},
"trigger": {
"slash": true,
"session_start": false,
"file_save": false,
"pre_commit": true,
"session_end": false
},
// If true, HIGH/CRITICAL verdicts block pre-commit
"guardrail": true
}
}
}
```
## Field reference
### `pre` and `post`
- `pre` — skills to load before work starts. Loaded into the session's
skill manifest, unloaded when the session ends.
- `post` — agents to invoke after the trigger. Each runs in its own
sub-agent context window.
Either list can be empty. A toolbox with only `pre` is a skill preloader;
one with only `post` is a review council.
### `scope.analysis`
Controls what files the council sees:
| Value | Behavior |
|---|---|
| `diff` | Only files with uncommitted changes. Cheapest, fastest. |
| `dynamic` | Diff + import graph blast radius. Catches downstream regressions. |
| `full` | Every tracked file. Most thorough; expensive — reserve for security sweeps. |
### `budget`
Enforced by `council_runner`. When the plan would exceed `max_tokens`, the
runner truncates the file list; when time exceeds `max_seconds`, the
trigger exits 0 without running remaining agents.
### `dedup`
`fresh` always re-runs. `user-configurable` skips a council run when the
same file set was reviewed within `window_seconds`. Dedup state lives at
`~/.claude/toolbox-runs/<plan_hash>.json`.
### `trigger`
At least one trigger must be true. Multiple triggers are allowed — a
`ship-it` toolbox typically enables `slash`, `pre_commit`, and
`session_end`.
### `guardrail`
When `true` and the trigger is `pre_commit`, the hook reads
`<plan_hash>.verdict.json` after the council runs and exits `2` (blocks
the commit) if level is `HIGH` or `CRITICAL`. See
[Verdicts & guardrails](verdicts.md).
## Editing tools
```bash
# List all toolboxes, both layers merged
ctx-toolbox list
# Show resolved config for one toolbox
ctx-toolbox show ship-it
# Activate a starter preset
ctx-toolbox activate ship-it
# Export merged config
ctx-toolbox export > my-toolboxes.yaml
# Import from file
ctx-toolbox import my-toolboxes.yaml
```
## Validation
`toolbox_config.load()` validates on read:
- `version` must equal `1`.
- Every toolbox needs at least one trigger.
- `scope.analysis` must be one of `diff`, `dynamic`, `full`.
- `budget.max_tokens` and `budget.max_seconds` must be positive ints.
Invalid entries raise `ValueError` with the offending key.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081# Council runner
[`src/council_runner.py`](https://github.com/stevesolun/ctx/blob/main/src/council_runner.py)
is the planner that turns a toolbox declaration into a concrete `RunPlan`
the hook system can execute.
## Responsibilities
1. **Resolve the toolbox** — merge global + per-repo config.
2. **Compute scope** — walk the current diff or full repo, honoring
`scope.analysis` and optional `scope.files` globs.
3. **Graph-blast expansion** — for `dynamic` scope, add every file that
imports a changed module (via the knowledge graph edge map).
4. **Enforce budget** — drop files until the plan fits within
`budget.max_tokens` (estimated by line count × heuristic).
5. **Honor dedup** — skip if the same file set was run within
`dedup.window_seconds` and policy is `user-configurable`.
6. **Persist** — write the plan to
`~/.claude/toolbox-runs/<plan_hash>.json` for downstream reads.
## RunPlan
```python
@dataclass(frozen=True)
class RunPlan:
plan_hash: str
toolbox: str
agents: tuple[str, ...]
files: tuple[str, ...]
source: str # "slash" | "pre-commit" | ...
guardrail: bool
budget: Budget
created_at: float
```
The `plan_hash` is deterministic (sha256 of `toolbox|sorted(files)|agents`),
which lets dedup work across triggers without any additional state.
## CLI
```bash
# Build and persist a plan for the named toolbox
python -m council_runner build ship-it
# Build without persisting (useful for inspection)
python -m council_runner build ship-it --dry-run
# Show a previously persisted plan
python -m council_runner show <plan_hash>
# List recent plans
python -m council_runner list --limit 10
```
## Budget estimation
Token estimates are intentionally rough. The runner assumes ~4 tokens per
line of source, then sorts files by recency (newest first) and greedily
takes until `max_tokens` is reached. If a single file exceeds the budget,
the plan is truncated rather than dropped — the council still runs on a
partial view.
This cheap estimate is fine because the council itself enforces its own
budgets; `council_runner`'s job is just to stay in the right ballpark.
## Dedup window
Dedup compares the sorted file list, not the plan hash — that way a
toolbox and its re-run with a newer budget still dedup correctly.
## Graph-blast expansion
For `dynamic` scope, `council_runner` reads the graph edge map produced
by `scan_repo.py` and walks imports one hop out from each changed file.
It stops at one hop to keep scope bounded; deep graph walks are reserved
for explicit `full` mode.
## Related
- [Hooks & triggers](hooks.md) — how a plan gets executed.
- [Verdicts & guardrails](verdicts.md) — what the council leaves behind.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980# Hooks & triggers
[`src/toolbox_hooks.py`](https://github.com/stevesolun/ctx/blob/main/src/toolbox_hooks.py)is the bridge between Claude Code's hook system and the toolbox runner.It listens for four events plus one explicit slash command.
## Event model
| Event | Fires on | Typical toolbox ||---|---|---|| `session-start` | New Claude Code session | Skill preloaders, intent suggestions || `file-save` | File written to disk | Linters, quick reviewers || `pre-commit` | `git commit` before write | Guardrail councils (`ship-it`, `security-sweep`) || `session-end` | Session closes | Digest, behavior miner, retro || `slash:/toolbox run <name>` | User-initiated | Anything |
Each trigger in a toolbox's `trigger` map enables that toolbox on thatevent. Events with no matching toolbox emit nothing.
## Emission format
One JSON line per matching toolbox, on stdout:
```jsonc{ "trigger": "pre-commit", "toolbox": "ship-it", "plan_file": "/Users/steve/.claude/toolbox-runs/abc123.json", "agents": ["code-reviewer", "security-reviewer", "architect-review"], "files": ["src/toolbox_verdict.py", "src/tests/test_toolbox_verdict.py"], "source": "pre-commit", "guardrail": true}```
Claude Code's hook handler reads these lines and dispatches each agentagainst the listed files.
## Exit codes
| Code | Meaning ||---|---|| `0` | Success; zero or more toolboxes emitted || `1` | Unknown trigger or config error || `2` | `pre-commit` + `guardrail=true` + verdict level is HIGH/CRITICAL |
The `2` exit from `pre-commit` is what actually blocks `git commit`.
## Installation
`pip install claude-ctx` exposes `ctx-toolbox` on PATH; wire it into`.githooks/pre-commit` directly:
```bash# .githooks/pre-commit#!/bin/shctx-toolbox run --event pre-commit```
Then point git at the directory once: `git config core.hooksPath .githooks`.
Then `git config core.hooksPath .githooks`.
## file-save path matching
`file-save` triggers honor `scope.files` globs. Without a `--path` argthe event matches nothing (there's no file to test). This is intentional:file-save toolboxes must be path-scoped.
## session-end digest
On `session-end`, the hook also calls[`behavior_miner.build_profile`](behavior-miner.md), saves the updatedprofile, and prints any new suggestions. This is informational only —the digest never blocks and never changes the return code.
## Reference
- [Council runner](council-runner.md) — how plans are built.- [Verdicts & guardrails](verdicts.md) — how blocking is decided.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475# Toolbox overview
A **toolbox** is a named bundle of skills and agents that runs at a defined
moment in your workflow: at session start, on file save, before a commit, at
session end, or when you invoke its slash command.
Toolboxes let you declare the *council* you want reviewing your work
without hand-loading skills each session.
## Lifecycle
```mermaid
flowchart LR
A[Declare toolbox] --> B[Trigger fires]
B --> C[Council runner<br/>builds plan]
C --> D[Agents run<br/>scoped to plan.files]
D --> E[Findings recorded<br/>as Verdict]
E -->|HIGH / CRITICAL| F[Guardrail blocks<br/>pre-commit]
E -->|LOW / MEDIUM| G[Logged,<br/>session continues]
```
Each arrow is a concrete module:
- **Declare**: [`toolbox_config.py`](https://github.com/stevesolun/ctx/blob/main/src/toolbox_config.py)
loads `~/.claude/toolboxes.json` and merges per-repo `.toolbox.yaml` on top.
- **Trigger**: [`toolbox_hooks.py`](https://github.com/stevesolun/ctx/blob/main/src/toolbox_hooks.py)
listens for `session-start`, `file-save`, `pre-commit`, `session-end`, and
the `/toolbox run` slash command.
- **Plan**: [`council_runner.py`](https://github.com/stevesolun/ctx/blob/main/src/council_runner.py)
assembles a `RunPlan` honoring scope, dedup, and graph-blast expansion.
- **Verdict**: [`toolbox_verdict.py`](https://github.com/stevesolun/ctx/blob/main/src/toolbox_verdict.py)
merges findings by id and escalates level to max(findings).
## Minimal declaration
```yaml
# .toolbox.yaml (per-repo)
version: 1
toolboxes:
review:
description: "Post-feature code review"
post:
- code-reviewer
- security-reviewer
scope:
analysis: diff
trigger:
slash: true
pre_commit: true
guardrail: true
```
Run it manually:
```bash
ctx-toolbox run review
```
Or let the `pre-commit` hook fire it automatically — see
[Hooks & triggers](hooks.md).
## Scope modes
| Mode | What gets reviewed | Best for |
|---|---|---|
| `diff` | Files in the current uncommitted diff | Pre-commit, real-time review |
| `dynamic` | Diff + graph blast radius (imports of modified files) | Refactor safety |
| `full` | Entire repo | Security sweeps, docs audits |
## Related
- [Configuration schema](configuration.md) — full field reference.
- [Starter toolboxes](starters.md) — 5 shipping presets.
- [Intent interview](intent-interview.md) — `toolbox init` walkthrough.
- [Verdicts & guardrails](verdicts.md) — how blocking works.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# Intent interview
[`src/intent_interview.py`](https://github.com/stevesolun/ctx/blob/main/src/intent_interview.py)
bootstraps your toolbox set via a short, skippable interview.
The slash command `/toolbox init` is a thin wrapper; see
[`.claude/commands/toolbox-init.md`](https://github.com/stevesolun/ctx/blob/main/.claude/commands/toolbox-init.md).
## Flow
1. **Detect repo state** — is this a git repo? Any commits? What languages?
2. **Load behavior profile** — read `~/.claude/user-profile.json` for any
mined suggestions.
3. **Ask up to three questions**:
- Which starter toolboxes to activate.
- Which miner suggestions to accept (if any).
- Default analysis mode for new toolboxes.
4. **Persist** — write chosen toolboxes to `~/.claude/toolboxes.json`
(only when `--apply` is passed).
Any prompt can be skipped with the word `skip`.
## Repo state detection
```python
@dataclass(frozen=True)
class RepoState:
is_git: bool
commit_count: int
languages: dict[str, int] # extension → file count
markers: dict[str, str] # marker file → language
has_toolbox_config: bool
@property
def is_blank(self) -> bool:
# True when the repo has effectively nothing to analyze yet.
return not self.is_git or self.commit_count == 0 or (
not self.languages and not self.markers
)
```
Language scoring uses both extensions (`.py`, `.ts`, …) and marker files
(`pyproject.toml`, `Cargo.toml`, `Dockerfile`, …). Marker files bump the
score by 5 to reflect that they declare intent more strongly than a
stray extension match.
## Usage
```bash
# Default: interactive, dry-run (no write)
python -m intent_interview init
# Detect state only
python -m intent_interview detect
# Preset flows (no prompts)
python -m intent_interview init --preset blank --apply
python -m intent_interview init --preset existing --apply
python -m intent_interview init --preset docs-heavy --apply
python -m intent_interview init --preset security-first --apply
# Fully structured (CI / scripted setup)
python -m intent_interview init \
--non-interactive \
--starters ship-it,security-sweep \
--suggestions 1,2 \
--analysis dynamic \
--apply
```
## Presets
| Preset | Starters | Default scope |
|---|---|---|
| `blank` | ship-it, security-sweep, fresh-repo-init | dynamic |
| `existing` | ship-it, refactor-safety | dynamic |
| `docs-heavy` | docs-review | diff |
| `security-first` | security-sweep | full |
## Skip semantics
- Typing `skip` at any prompt short-circuits the whole interview: no
starters activated, no suggestions accepted, analysis mode unchanged.
- `--skip` on the CLI is the non-interactive equivalent.
## Exit codes
- `0` — success; JSON payload printed on stdout.
- non-zero — unrecoverable error (unknown preset, malformed args).
## Related
- [Starter toolboxes](starters.md) — the five bundles the interview can activate.
- [Behavior miner](behavior-miner.md) — source of the suggestions the interview offers.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596# Starter toolboxes
Five presets ship in `docs/toolbox/templates/`. `toolbox init` activates
them into `~/.claude/toolboxes.json`; you can then override any field per-repo
in `.toolbox.yaml`.
## ship-it
> **Professional council of 7 experts for end-of-feature review.**
Runs `code-reviewer`, `security-reviewer`, `architect-review`,
`test-automator`, `performance-engineer`, `accessibility-tester`, and
`docs-lookup` against the diff + graph blast radius.
- **Triggers**: slash, pre-commit, session-end.
- **Scope**: `dynamic` — diff plus imports of changed modules.
- **Budget**: 200 k tokens / 420 seconds.
- **Guardrail**: on (HIGH/CRITICAL blocks pre-commit).
Best for: shipping a feature branch. The council covers correctness,
security, architecture, testing, performance, accessibility, and docs in
one pass.
## security-sweep
> **Full-repo security audit with blocking guardrail on HIGH findings.**
Runs `security-reviewer`, `backend-security-coder`, `frontend-security-coder`,
and `compliance-auditor` against the entire repo.
- **Triggers**: slash, pre-commit.
- **Scope**: `full` — every tracked file.
- **Budget**: 300 k tokens / 600 seconds.
- **Guardrail**: on.
Best for: periodic audits, pre-release sweeps, compliance checkpoints.
Expensive; not a per-commit hook.
## refactor-safety
> **Graph-informed refactor review with regression and dead-code checks.**
Runs `architect-review`, `refactor-cleaner`, `test-automator`, and
`code-reviewer` against diff + graph blast.
- **Triggers**: slash, pre-commit.
- **Scope**: `dynamic`.
- **Budget**: 120 k tokens / 300 seconds.
- **Guardrail**: off — flags issues without blocking.
Best for: mid-refactor checkpoints. Catches orphaned code, downstream
breakage, missing test updates.
## docs-review
> **Documentation pass: accuracy, completeness, clarity, and API parity.**
Runs `docs-lookup`, `technical-writer`, and `code-reviewer` against docs
diffs.
- **Triggers**: slash, pre-commit.
- **Scope**: `diff`.
- **Budget**: 60 k tokens / 180 seconds.
- **Guardrail**: off.
Best for: docs-heavy branches and README updates.
## fresh-repo-init
> **New-repo bootstrap: run the intent interview, scaffold plan, pick initial toolbox.**
Invokes `intent_interview` in interactive mode, then activates whichever
starters the user selects.
- **Triggers**: slash only.
- **Scope**: `full` (fresh scan of a new repo).
- **Budget**: small — this bundle is just an orchestrator.
Best for: `git init` followed by `toolbox init`.
## Activation
```bash
# Pick starters interactively
python -m intent_interview init
# Non-interactive preset
python -m intent_interview init --preset existing --apply
python -m intent_interview init --preset docs-heavy --apply
python -m intent_interview init --preset security-first --apply
# Activate a specific starter directly
ctx-toolbox activate ship-it
```
See [Intent interview](intent-interview.md) for the full flow.123456789101112131415161718192021222324252627282930{ "description": "Documentation pass: accuracy, completeness, clarity, and API parity", "pre": ["docs-lookup"], "post": [ "technical-writer", "docs-architect", "api-documenter", "tutorial-engineer" ], "scope": { "projects": ["*"], "signals": ["documentation"], "analysis": "diff" }, "trigger": { "slash": true, "pre_commit": false, "session_end": false, "file_save": "**/*.md" }, "budget": { "max_tokens": 120000, "max_seconds": 240 }, "dedup": { "window_seconds": 300, "policy": "cached" }, "guardrail": false}1234567891011121314151617181920212223242526272829{ "description": "New-repo bootstrap: run the intent interview, scaffold plan, pick initial toolbox", "pre": [], "post": [ "planner", "architect", "tdd-guide" ], "scope": { "projects": ["*"], "signals": [], "analysis": "diff" }, "trigger": { "slash": true, "pre_commit": false, "session_end": false, "file_save": null }, "budget": { "max_tokens": 100000, "max_seconds": 300 }, "dedup": { "window_seconds": 0, "policy": "fresh" }, "guardrail": false}12345678910111213141516171819202122232425262728293031{ "description": "Graph-informed refactor review with regression and dead-code checks", "pre": ["architect-review", "refactor-cleaner"], "post": [ "architect-review", "refactor-cleaner", "code-reviewer", "test-automator", "dependency-manager" ], "scope": { "projects": ["*"], "signals": [], "analysis": "graph-blast" }, "trigger": { "slash": true, "pre_commit": false, "session_end": true, "file_save": null }, "budget": { "max_tokens": 180000, "max_seconds": 360 }, "dedup": { "window_seconds": 900, "policy": "cached" }, "guardrail": false}12345678910111213141516171819202122232425262728293031{ "description": "Full-repo security audit with blocking guardrail on HIGH findings", "pre": [], "post": [ "security-reviewer", "security-auditor", "penetration-tester", "compliance-auditor", "threat-detection-engineer" ], "scope": { "projects": ["*"], "signals": ["security", "auth", "crypto"], "analysis": "full" }, "trigger": { "slash": true, "pre_commit": true, "session_end": false, "file_save": "**/auth/**" }, "budget": { "max_tokens": 300000, "max_seconds": 600 }, "dedup": { "window_seconds": 0, "policy": "fresh" }, "guardrail": true}123456789101112131415161718192021222324252627282930313233{ "description": "Professional council of 7 experts for end-of-feature review", "pre": [], "post": [ "code-reviewer", "security-reviewer", "architect-review", "test-automator", "performance-engineer", "accessibility-tester", "docs-lookup" ], "scope": { "projects": ["*"], "signals": ["python", "typescript", "rust", "go", "java"], "analysis": "dynamic" }, "trigger": { "slash": true, "pre_commit": true, "session_end": true, "file_save": null }, "budget": { "max_tokens": 200000, "max_seconds": 420 }, "dedup": { "window_seconds": 600, "policy": "fresh" }, "guardrail": false}.claude/commands/toolbox-init.mdAdded+54
.dedup-allowlist.txtAdded+18
.githooks/pre-commitAdded+168
.github/ISSUE_TEMPLATE/bug_report.mdAdded+36
.github/ISSUE_TEMPLATE/feature_request.mdAdded+23
.github/pull_request_template.mdAdded+15
.github/workflows/clean-host-contract.ymlAdded+29
.github/workflows/docs.ymlAdded+69
.github/workflows/publish.ymlAdded+138
.github/workflows/test.ymlAdded+241
.gitignoreAdded+87
AGENTS.mdAdded+70
CHANGELOG.mdAdded+1235
CONTRIBUTING.mdAdded+77
LICENSEAdded+21
README.mdAdded+85
docs/SKILL.mdAdded+690
docs/backup-hook-install.mdAdded+224
docs/dashboard.mdAdded+262
docs/entity-onboarding.mdAdded+273
docs/harness/attaching-to-hosts.mdAdded+259
docs/harness/clean-host-contract.mdAdded+101
docs/index.mdAdded+197
docs/knowledge-graph.mdAdded+210
docs/marketplace-registry.mdAdded+157
docs/memory-anchor.mdAdded+102
docs/plans/001-model-agnostic-harness.mdAdded+467
docs/roadmap/skill-quality.mdAdded+209
docs/roadmap/toolbox.mdAdded+141
docs/services/macos/com.claude.backup.watchdog.plistAdded+58
docs/services/systemd/claude-backup-watchdog.serviceAdded+40
docs/services/windows/install-backup-watchdog.ps1Added+120
docs/skill-lifecycle-and-dashboard.mdAdded+171
docs/skill-quality-install.mdAdded+171
docs/skill-router/index.mdAdded+49
docs/skill-stack-matrix.mdAdded+165
docs/skills-health.mdAdded+108
docs/stack-signatures.mdAdded+164
docs/toolbox/behavior-miner.mdAdded+90
docs/toolbox/configuration.mdAdded+143
docs/toolbox/council-runner.mdAdded+81
docs/toolbox/hooks.mdAdded+80
docs/toolbox/index.mdAdded+75
docs/toolbox/intent-interview.mdAdded+94
docs/toolbox/starters.mdAdded+96
docs/toolbox/templates/docs-review.jsonAdded+30
docs/toolbox/templates/fresh-repo-init.jsonAdded+29
docs/toolbox/templates/refactor-safety.jsonAdded+31
docs/toolbox/templates/security-sweep.jsonAdded+31
docs/toolbox/templates/ship-it.jsonAdded+33