diff --git a/.dedup-allowlist.txt b/.dedup-allowlist.txt
index a418c3c6319ac94c3a567fedc9481a21e0d2e5ee..ac692bf8ed2f133a946a9bffa6f42d5e1b807bc3 100644
--- a/.dedup-allowlist.txt
+++ b/.dedup-allowlist.txt
@@ -1,18 +1,18 @@
-# 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:
-#
-# # 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 overlap
+# 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:
+#
+# # 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 overlap
diff --git a/.gitattributes b/.gitattributes
index 3fffd4e600fa5075b183eb8ff6cef6c654887d10..0b34f89f3b1d50a5ae4db57bed2b6140a9a27324 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,4 +1,4 @@
-graph/wiki-graph.tar.gz filter=lfs diff=lfs merge=lfs -text
+graph/wiki-graph.tar.gz filter=lfs diff=lfs merge=lfs -text
graph/skills-sh-catalog.json.gz filter=lfs diff=lfs merge=lfs -text
graph/viz-overview.png filter=lfs diff=lfs merge=lfs -text
graph/viz-security.png filter=lfs diff=lfs merge=lfs -text
diff --git a/.githooks/post-checkout b/.githooks/post-checkout
index 4de8e2874437b8b6042b8879f6e467b34ccb1667..ca7fcb4008854b4113235ad5b78563e27a525ae1 100644
--- a/.githooks/post-checkout
+++ b/.githooks/post-checkout
@@ -1,3 +1,3 @@
-#!/bin/sh
-command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-checkout' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks').\n"; exit 2; }
-git lfs post-checkout "$@"
+#!/bin/sh
+command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-checkout' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks').\n"; exit 2; }
+git lfs post-checkout "$@"
diff --git a/.githooks/post-commit b/.githooks/post-commit
index 51d31f6a9c22a68dbb06de561149ee7d60ad8876..52b339cb3f496610a69a3bd6cc0cd8b4dbca93a3 100644
--- a/.githooks/post-commit
+++ b/.githooks/post-commit
@@ -1,3 +1,3 @@
-#!/bin/sh
-command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-commit' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks').\n"; exit 2; }
-git lfs post-commit "$@"
+#!/bin/sh
+command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-commit' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks').\n"; exit 2; }
+git lfs post-commit "$@"
diff --git a/.githooks/post-merge b/.githooks/post-merge
index 81c57e7d4144e20fcb1abeb6df25f5ea60689274..a912e667aa3353b079f92508f844d9ef35267c5f 100644
--- a/.githooks/post-merge
+++ b/.githooks/post-merge
@@ -1,3 +1,3 @@
-#!/bin/sh
-command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-merge' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks').\n"; exit 2; }
-git lfs post-merge "$@"
+#!/bin/sh
+command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-merge' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks').\n"; exit 2; }
+git lfs post-merge "$@"
diff --git a/.githooks/pre-commit b/.githooks/pre-commit
index db5391eff2eb2d222ff37a006969f1b72f0ff1c4..15d7b7942d1fe7c278c3a36208f2f6d2013354e7 100644
--- a/.githooks/pre-commit
+++ b/.githooks/pre-commit
@@ -1,43 +1,43 @@
-#!/usr/bin/env bash
-# pre-commit -- refresh cheap repo stats without leaking local wiki state.
-#
-# Enable with: git config core.hooksPath .githooks
-# Disable with: git config --unset core.hooksPath
-#
-# This hook intentionally does not rebuild graph/wiki artifacts from
-# ~/.claude/skill-wiki. That directory can contain private local entities.
-# Release graph artifacts must be created by explicit, reproducible commands
-# and staged by the user or CI.
-
-set -u
-
-REPO_ROOT="$(git rev-parse --show-toplevel)"
-UPDATER="$REPO_ROOT/src/update_repo_stats.py"
-
-PYTHON="${PYTHON:-python3}"
-command -v "$PYTHON" >/dev/null 2>&1 || PYTHON="python"
-
-STAGED_CHANGES=$(git diff --cached --name-only)
-log() { echo "[pre-commit] $*" >&2; }
-
-if echo "$STAGED_CHANGES" | grep -qE '^(README\.md|graph/(wiki-graph\.tar\.gz|communities\.json)|src/update_repo_stats\.py)$' ; then
- if [[ -f "$UPDATER" ]]; then
- STATS_CMD=("$PYTHON" "$UPDATER")
- if command -v timeout >/dev/null 2>&1; then
- STATS_CMD=(timeout 45s "${STATS_CMD[@]}")
- fi
- if ! "${STATS_CMD[@]}" 2> >(sed 's/^/[pre-commit stats] /' >&2); then
- log "stats updater failed or timed out; continuing without README refresh"
- elif ! git diff --quiet -- README.md; then
- git add README.md
- log "README.md refreshed and re-staged"
- fi
- fi
-fi
-
-if echo "$STAGED_CHANGES" | grep -qE '^(skills|agents|harnesses|imported-skills|graph/skills-sh-catalog\.json\.gz)' ; then
- log "entity source changed; graph/wiki tarball not rebuilt by pre-commit"
- log "run the explicit graph release command and stage graph/wiki-graph.tar.gz if needed"
-fi
-
-exit 0
+#!/usr/bin/env bash
+# pre-commit -- refresh cheap repo stats without leaking local wiki state.
+#
+# Enable with: git config core.hooksPath .githooks
+# Disable with: git config --unset core.hooksPath
+#
+# This hook intentionally does not rebuild graph/wiki artifacts from
+# ~/.claude/skill-wiki. That directory can contain private local entities.
+# Release graph artifacts must be created by explicit, reproducible commands
+# and staged by the user or CI.
+
+set -u
+
+REPO_ROOT="$(git rev-parse --show-toplevel)"
+UPDATER="$REPO_ROOT/src/update_repo_stats.py"
+
+PYTHON="${PYTHON:-python3}"
+command -v "$PYTHON" >/dev/null 2>&1 || PYTHON="python"
+
+STAGED_CHANGES=$(git diff --cached --name-only)
+log() { echo "[pre-commit] $*" >&2; }
+
+if echo "$STAGED_CHANGES" | grep -qE '^(README\.md|graph/(wiki-graph\.tar\.gz|communities\.json)|src/update_repo_stats\.py)$' ; then
+ if [[ -f "$UPDATER" ]]; then
+ STATS_CMD=("$PYTHON" "$UPDATER")
+ if command -v timeout >/dev/null 2>&1; then
+ STATS_CMD=(timeout 45s "${STATS_CMD[@]}")
+ fi
+ if ! "${STATS_CMD[@]}" 2> >(sed 's/^/[pre-commit stats] /' >&2); then
+ log "stats updater failed or timed out; continuing without README refresh"
+ elif ! git diff --quiet -- README.md; then
+ git add README.md
+ log "README.md refreshed and re-staged"
+ fi
+ fi
+fi
+
+if echo "$STAGED_CHANGES" | grep -qE '^(skills|agents|harnesses|imported-skills|graph/skills-sh-catalog\.json\.gz)' ; then
+ log "entity source changed; graph/wiki tarball not rebuilt by pre-commit"
+ log "run the explicit graph release command and stage graph/wiki-graph.tar.gz if needed"
+fi
+
+exit 0
diff --git a/.githooks/pre-push b/.githooks/pre-push
index c36202b0dc05d266717d4d42c325b1153333180c..0f0089bc25dc188e65375cc983f3325dd9f4480c 100644
--- a/.githooks/pre-push
+++ b/.githooks/pre-push
@@ -1,3 +1,3 @@
-#!/bin/sh
-command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'pre-push' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks').\n"; exit 2; }
-git lfs pre-push "$@"
+#!/bin/sh
+command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'pre-push' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks').\n"; exit 2; }
+git lfs pre-push "$@"
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
index b2c56fba11d432b9913432c966598eeced3a68ed..09141fd2d4251d0111049ced1880167f5749b014 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.md
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -1,36 +1,36 @@
----
-name: Bug report
-about: Something is broken
-title: "[bug] "
-labels: bug
-assignees: ""
----
-
-## 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.).
+---
+name: Bug report
+about: Something is broken
+title: "[bug] "
+labels: bug
+assignees: ""
+---
+
+## 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.).
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
index e07ccd6be4c6f5d6a642567df35f62d90b2d97df..6d494be7a23ec98878bc899b3b455219d7c26c87 100644
--- a/.github/ISSUE_TEMPLATE/feature_request.md
+++ b/.github/ISSUE_TEMPLATE/feature_request.md
@@ -1,23 +1,23 @@
----
-name: Feature request
-about: Suggest an improvement or new capability
-title: "[feat] "
-labels: enhancement
-assignees: ""
----
-
-## 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.
+---
+name: Feature request
+about: Suggest an improvement or new capability
+title: "[feat] "
+labels: enhancement
+assignees: ""
+---
+
+## 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.
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 87e2af238b84a54759c843dc90cdb63849eba0d5..1d5062dbe3dd46ca7a3f7335edc2b97061d92da6 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -1,15 +1,15 @@
-## Summary
-
-
-
-## Related issue
-
-
-
-## 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`)
+## Summary
+
+
+
+## Related issue
+
+
+
+## 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`)
diff --git a/.github/workflows/clean-host-contract.yml b/.github/workflows/clean-host-contract.yml
index ae4704773dbdc93f92ee46d5b2a283c5a5b91845..843ef5733222bdca0ea51d0da058a10330cc7d9d 100644
--- a/.github/workflows/clean-host-contract.yml
+++ b/.github/workflows/clean-host-contract.yml
@@ -8,6 +8,9 @@ on:
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
+permissions:
+ contents: read
+
jobs:
clean-host-contract:
name: Clean wheel install and A-Z contract
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
index e296d5877f2c03f853678cb40a2981029fbd28b7..45abe7db8033dab26ae89a89aff77134f8f26f31 100644
--- a/.github/workflows/docs.yml
+++ b/.github/workflows/docs.yml
@@ -1,72 +1,72 @@
-name: 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:
-
-env:
- FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
-
-# 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@v5
- with:
- fetch-depth: 0 # Required by mkdocs git-revision plugins if added.
-
- - name: Set up Python
- uses: actions/setup-python@v6
- 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@v5
- 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@v5
+name: 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:
+
+env:
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
+
+# 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@v5
+ with:
+ fetch-depth: 0 # Required by mkdocs git-revision plugins if added.
+
+ - name: Set up Python
+ uses: actions/setup-python@v6
+ 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@v5
+ 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@v5
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 4d80bf249fa1e4c8861fe2c6e3e84576f26580b3..29f8d13c061835a80e921ceb9a552ee8720f94cf 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -28,13 +28,14 @@ env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
permissions:
- id-token: write # required for Trusted Publishing
contents: read
jobs:
build:
name: Build sdist + wheel
runs-on: ubuntu-latest
+ permissions:
+ contents: read
steps:
- name: Checkout
uses: actions/checkout@v5
@@ -90,6 +91,40 @@ jobs:
env:
INPUT_REPOSITORY: ${{ github.event.inputs.repository || 'pypi' }}
+ - name: Reject already published PyPI version
+ run: |
+ python - <<'PY'
+ import os
+ import tomllib
+ import urllib.error
+ import urllib.request
+
+ target_repository = os.environ.get("INPUT_REPOSITORY", "pypi")
+ if target_repository != "pypi":
+ print(f"skipping PyPI reuse check for {target_repository}")
+ raise SystemExit(0)
+
+ with open("pyproject.toml", "rb") as fh:
+ project = tomllib.load(fh)["project"]
+
+ name = project["name"]
+ package_version = project["version"]
+ url = f"https://pypi.org/pypi/{name}/{package_version}/json"
+ try:
+ with urllib.request.urlopen(url, timeout=15):
+ raise SystemExit(
+ f"{name} {package_version} already exists on PyPI; "
+ "bump the version before publishing"
+ )
+ except urllib.error.HTTPError as exc:
+ if exc.code == 404:
+ print(f"{name} {package_version} is not present on PyPI")
+ raise SystemExit(0)
+ raise
+ PY
+ env:
+ INPUT_REPOSITORY: ${{ github.event.inputs.repository || 'pypi' }}
+
- name: Static gates
run: |
python -m ruff check src hooks scripts
@@ -175,6 +210,9 @@ jobs:
name: Publish to PyPI
needs: build
runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ id-token: write # required for Trusted Publishing
environment:
name: pypi
url: https://pypi.org/project/claude-ctx/
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 87e44ca3a4d2a8fb2c3dbb70f1d307c94b4d1abd..fc827f33e5074f8947aa0c8fa472b2caabbbdacb 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -9,6 +9,9 @@ on:
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
+permissions:
+ contents: read
+
concurrency:
group: tests-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
@@ -24,6 +27,7 @@ jobs:
graph_changed: ${{ steps.classify.outputs.graph_changed }}
graph_only: ${{ steps.classify.outputs.graph_only }}
package_changed: ${{ steps.classify.outputs.package_changed }}
+ similarity_changed: ${{ steps.classify.outputs.similarity_changed }}
source_changed: ${{ steps.classify.outputs.source_changed }}
steps:
- name: Checkout with full history
@@ -120,6 +124,32 @@ jobs:
include-hidden-files: true
retention-days: 7
+ similarity-integration:
+ name: "Similarity precision/recall"
+ needs: classify
+ if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true' && needs.classify.outputs.similarity_changed == 'true') }}
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v5
+ with:
+ lfs: false
+
+ - name: Set up Python 3.11
+ uses: actions/setup-python@v6
+ with:
+ python-version: "3.11"
+ cache: pip
+ cache-dependency-path: pyproject.toml
+
+ - name: Install embedding dependencies
+ run: |
+ python -m pip install --upgrade pip
+ python -m pip install ".[dev,embeddings]"
+
+ - name: Run similarity precision/recall gate
+ run: pytest -q --no-cov -m integration src/tests/test_similarity_precision_recall.py
+
test:
name: pytest (${{ matrix.os }} / py${{ matrix.python-version }})
if: ${{ github.event_name != 'pull_request' }}
@@ -160,6 +190,37 @@ jobs:
- name: Run tests without coverage
run: pytest -q -m "not browser" --no-cov
+ contract-compat:
+ name: "Contract compatibility (${{ matrix.os }})"
+ needs: classify
+ if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true') }}
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [windows-latest, macos-latest]
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v5
+ with:
+ lfs: false
+
+ - name: Set up Python 3.12
+ uses: actions/setup-python@v6
+ with:
+ python-version: "3.12"
+ cache: pip
+ cache-dependency-path: pyproject.toml
+
+ - name: Install dependencies
+ run: |
+ python -m pip install --upgrade pip
+ python -m pip install ".[dev]"
+
+ - name: Run cross-OS contract tests
+ run: python -m pytest -q --no-cov src/tests/test_clean_host_contract.py src/tests/test_package_scaffold.py
+
e2e-canary:
name: "A-Z alive-loop E2E canary"
needs: classify
@@ -241,6 +302,17 @@ jobs:
--min-edges 2000000 \
--min-skills-sh-nodes 89000 \
--min-semantic-edges 1000000 \
+ --expected-nodes 102696 \
+ --expected-edges 2900834 \
+ --expected-semantic-edges 1682825 \
+ --expected-harness-nodes 13 \
+ --expected-skills-sh-nodes 89463 \
+ --expected-skills-sh-catalog-entries 89463 \
+ --expected-skills-sh-converted 89463 \
+ --expected-skill-pages 91432 \
+ --expected-agent-pages 464 \
+ --expected-mcp-pages 10787 \
+ --expected-harness-pages 13 \
--line-threshold 180 \
--max-stage-lines 40
@@ -379,34 +451,59 @@ jobs:
python -m pip install dist/*.whl
python -m pip check
python - <<'PY'
+ import tomllib
from importlib.metadata import entry_points, version
import ctx
+ with open("pyproject.toml", "rb") as fh:
+ expected_scripts = set(tomllib.load(fh)["project"]["scripts"])
+
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")
+ script_eps = {
+ ep.name: ep
+ for ep in entry_points(group="console_scripts")
if ep.name == "ctx" or ep.name.startswith("ctx-")
- ]
+ }
+ missing = sorted(expected_scripts - set(script_eps))
+ extra = sorted(set(script_eps) - expected_scripts)
+ if missing or extra:
+ raise SystemExit(
+ "wheel console-script surface mismatch\n"
+ f"missing: {missing}\n"
+ f"extra: {extra}"
+ )
failures = []
- for ep in scripts:
+ for ep in script_eps.values():
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}")
+
+ unsafe_help = {"ctx-mcp-server"}
+ safe_help = sorted(expected_scripts - unsafe_help)
+ with open(
+ "ctx-console-help.txt", "w", encoding="utf-8", newline="\n"
+ ) as fh:
+ fh.write("\n".join(safe_help) + "\n")
+ print(
+ f"loaded {len(script_eps)} ctx console scripts from wheel "
+ f"{dist_version}; help-smoke={len(safe_help)}"
+ )
PY
- ctx-init --help >/dev/null
- ctx-scan-repo --help >/dev/null
- ctx-wiki-graphify --help >/dev/null
- ctx --help >/dev/null
+ while IFS= read -r cmd; do
+ cmd="${cmd%$'\r'}"
+ [[ -z "$cmd" ]] && continue
+ echo "help smoke: $cmd"
+ "$cmd" --help >/dev/null
+ done < ctx-console-help.txt
clean-host-contract:
name: "Clean host contract"
@@ -434,7 +531,7 @@ jobs:
run: python scripts/clean_host_contract.py --fast
no-test-no-merge:
- name: "Every src/*.py change must touch a src/tests/*.py"
+ name: "Contract changes must touch tests"
needs: classify
runs-on: ubuntu-latest
if: ${{ github.event_name == 'pull_request' && needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true' }}
@@ -446,7 +543,7 @@ jobs:
lfs: false
- name: Enforce test-coverage-per-PR policy
- # Policy: any source change under src/ that isn't itself a test
+ # Policy: any product or CI/package contract change
# must be accompanied by at least one test file change in the
# same PR. Exemptions:
# - Pure docs / comment changes (matched by a trivial heuristic)
@@ -458,35 +555,10 @@ jobs:
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"
+ python scripts/ci_no_test_policy.py \
+ --base "$BASE" \
+ --head "$HEAD" \
+ --labels-json "$LABELS"
ci-required:
name: "CI required"
@@ -495,7 +567,9 @@ jobs:
- classify
- static
- unit-linux
+ - similarity-integration
- test
+ - contract-compat
- e2e-canary
- docs-check
- graph-check
diff --git a/.github/workflows/xdist-experiment.yml b/.github/workflows/xdist-experiment.yml
index 2dbdf42450315f2db979c26cf2ed38582725697c..e405c94d36f710bddd6339f4b6912ed57cee0349 100644
--- a/.github/workflows/xdist-experiment.yml
+++ b/.github/workflows/xdist-experiment.yml
@@ -87,4 +87,4 @@ jobs:
if [ "$status" -ne 0 ]; then
echo "::warning::xdist experiment failed on $RUNNER_OS with exit code $status"
fi
- exit 0
+ exit "$status"
diff --git a/AGENTS.md b/AGENTS.md
index 396fc55b46c00fc8a3e4b2c8bfec2828ef81ec88..5f2483b03431a12b987507711e7a776cb301fac5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,70 +1,70 @@
-# 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.
+# 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.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 60026d8a95d976915ecf36fd793fceb1008e43c2..cf040bd66c57bbd6cb21645118d877e4fedf568b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,38 @@ Format loosely follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- No unreleased changes yet.
+## [0.7.5] - 2026-05-05
+
+### Fixed
+
+- Hardened Hugging Face sync so published snapshots use hydrated graph
+ artifacts instead of Git LFS pointers and refuse unsafe graph artifact
+ states before upload.
+- Added PyPI version reuse preflight and tighter workflow token
+ permissions so release jobs fail early and only the publish job gets
+ Trusted Publishing OIDC.
+- Made the similarity precision/recall CI job path-aware while keeping it
+ required for recommendation, graph scoring, embedding, and workflow
+ changes.
+- Updated Hugging Face publish instructions to use the tested sync script
+ and avoid inline token assignment in shell history.
+
+## [0.7.4] - 2026-05-05
+
+### Fixed
+
+- Kept semantic query ranking opt-in so default recommendations do not
+ download embedding models or call Hugging Face during ordinary CLI use.
+- Made scan profile defaults OS-portable and dashboard artifact status
+ report the shipped graph/wiki archives truthfully.
+- Hardened package-smoke and xdist CI against Windows CRLF command lists,
+ nondeterministic test collection, macOS system temp symlinks, and
+ Windows xdist benchmark variance.
+- Moved the no-test merge policy into a tested Python helper and added a
+ narrow exemption for release metadata-only version bumps.
+- Pinned the wheel console-script surface and clean-host environment
+ isolation so packaged installs stay aligned with `pyproject.toml`.
+
## [0.7.3] - 2026-05-04
### Fixed
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0ebac9953e0f074e3dea3fd3caa4341f817d720f..bfce33b6c959fc5572e88045f0883480a9e8215f 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,77 +1,77 @@
-# Contributing to ctx
-
-Thank you for your interest in contributing.
-
-## Dev environment setup
-
-```bash
-git clone https://github.com/stevesolun/ctx && cd ctx
-python -m venv .venv
-source .venv/bin/activate # Windows: .venv\Scripts\activate
-pip install -e ".[dev]"
-```
-
-To also run the similarity/embedding tests (requires ~100 MB model download):
-
-```bash
-pip install -e ".[dev,embeddings]"
-```
-
-## Running tests
-
-```bash
-pytest -q # fast suite (skips integration)
-pytest -q -m 'not integration' # same, explicit
-pytest -q -m integration # embedding precision/recall tests
-pytest --cov=src -q # with coverage report
-```
-
-## Code style
-
-Both **ruff** and **mypy** must pass before a PR is merged.
-
-```bash
-ruff check src/ # linting
-ruff format --check src/ # formatting check
-mypy src/ # type checking
-```
-
-Fix formatting in one shot:
-
-```bash
-ruff format src/
-ruff check --fix src/
-```
-
-## Commit conventions
-
-This repo uses [Conventional Commits](https://www.conventionalcommits.org/):
-
-```
-feat: new feature
-fix: bug fix
-refactor: code restructuring without behaviour change
-docs: documentation only
-test: test additions or corrections
-chore: maintenance (deps, CI, tooling)
-perf: performance improvement
-ci: CI/CD changes
-```
-
-Scope is optional but encouraged, e.g. `feat(intake): add fuzzy-match gate`.
-
-## Reporting bugs
-
-Open an issue at . 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.
+# Contributing to ctx
+
+Thank you for your interest in contributing.
+
+## Dev environment setup
+
+```bash
+git clone https://github.com/stevesolun/ctx && cd ctx
+python -m venv .venv
+source .venv/bin/activate # Windows: .venv\Scripts\activate
+pip install -e ".[dev]"
+```
+
+To also run the similarity/embedding tests (requires ~100 MB model download):
+
+```bash
+pip install -e ".[dev,embeddings]"
+```
+
+## Running tests
+
+```bash
+pytest -q # fast suite (skips integration)
+pytest -q -m 'not integration' # same, explicit
+pytest -q -m integration # embedding precision/recall tests
+pytest --cov=src -q # with coverage report
+```
+
+## Code style
+
+Both **ruff** and **mypy** must pass before a PR is merged.
+
+```bash
+ruff check src/ # linting
+ruff format --check src/ # formatting check
+mypy src/ # type checking
+```
+
+Fix formatting in one shot:
+
+```bash
+ruff format src/
+ruff check --fix src/
+```
+
+## Commit conventions
+
+This repo uses [Conventional Commits](https://www.conventionalcommits.org/):
+
+```
+feat: new feature
+fix: bug fix
+refactor: code restructuring without behaviour change
+docs: documentation only
+test: test additions or corrections
+chore: maintenance (deps, CI, tooling)
+perf: performance improvement
+ci: CI/CD changes
+```
+
+Scope is optional but encouraged, e.g. `feat(intake): add fuzzy-match gate`.
+
+## Reporting bugs
+
+Open an issue at . 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.
diff --git a/LICENSE b/LICENSE
index f77323d7651d6419fcf2fe51a52abab2f3d52313..dae9762b8ad16b2de18b667c836081d1b073e15c 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,21 +1,21 @@
-MIT License
-
-Copyright (c) 2026 Steve Solun
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, 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 THE
-SOFTWARE.
+MIT License
+
+Copyright (c) 2026 Steve Solun
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, 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 THE
+SOFTWARE.
diff --git a/MANIFEST.in b/MANIFEST.in
index df9d868d6cd332982d01d07f9e4eade87a7a35bc..3ee49e612d4ee22f91fefd32a20eecd874ef7b70 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,4 +1,4 @@
-prune src/tests
-prune .a5c
-prune .claude
-global-exclude __pycache__ *.py[cod]
+prune src/tests
+prune .a5c
+prune .claude
+global-exclude __pycache__ *.py[cod]
diff --git a/README.md b/README.md
index f7eb99887e4bbb1656c3a03bd1a9f26e47e2a171..2387ddb1fd3387b1a865338881896c7e0c130988 100644
--- a/README.md
+++ b/README.md
@@ -2,100 +2,101 @@
license: mit
pretty_name: ctx
tags:
-- agents
-- mcp
-- skills
-- knowledge-graph
-- llm-wiki
-- recommendation-system
-- harness
-- codex
-- claude-code
+ - agents
+ - mcp
+ - skills
+ - knowledge-graph
+ - llm-wiki
+ - recommendation-system
+ - harness
+ - codex
+ - claude-code
---
-# ctx — Skill, Agent, MCP & Harness Recommendations
-
-[](LICENSE)
-[](https://python.org)
-[](https://pypi.org/project/claude-ctx/)
-[](#)
-[](graph/)
-[](https://stevesolun.github.io/ctx/)
-
-ctx watches what you are building, walks a **102,696-node** graph, and
-recommends a small, top-scored bundle of skills, agents, and MCP servers for
-the current task. If you use your own local/API model instead of Claude Code,
-ctx has a separate harness catalog flow: tell it the model and goal, review the
-recommended harness, then install with dry-run/update/uninstall controls.
-
-Current shipped snapshot:
-
-- **91,432 skills**: 1,969 curated/imported skills plus **89,463 body-backed Skills.sh skills**.
-- **464 agents**, **10,787 MCP servers**, and **13 cataloged harnesses**.
-- **2.9M graph edges** across semantic similarity, tags, slug tokens, source overlap, direct links, quality, usage, type affinity, and graph structure.
-- **89,463 hydrated `SKILL.md` bodies** in the shipped LLM-wiki; long entries are converted through the micro-skill gate instead of loading raw long prompts.
-- Entity updates for skills, agents, MCPs, and harnesses print benefits/risks and skip replacement unless you explicitly approve the update.
-
-## Why it exists
-
-- **Discovery** — with 91K+ skill nodes, 460+ agents, 10K+ MCP servers, and 13 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 102,696 nodes and 2.9M edges ships as a tarball. The same tarball includes `external-catalogs/skills-sh/catalog.json`, 89,463 body-backed Skills.sh skill pages under `entities/skills/skills-sh-*.md`, 89,463 hydrated installable Skills.sh `SKILL.md` files under `converted/skills-sh-*/`, and 13 cataloged harness pages 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 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, MCP servers, and installed harness records. It provides load/unload buttons where ctx owns the live action, a cytoscape graph view (`/graph?slug=…`), the LLM-wiki entity browser (`/wiki/`), a filterable skills grid, a session timeline, an audit log viewer, and a live SSE event stream. Harnesses are visible in the dashboard loaded/wiki/graph views; harness install/update/uninstall actions stay in `ctx-harness-install`.
-
-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:
-****
-
-Full docs, architecture, and every module: ****
-
-## License
-
-MIT — see [LICENSE](LICENSE).
+
+# ctx — Skill, Agent, MCP & Harness Recommendations
+
+[](LICENSE)
+[](https://python.org)
+[](https://pypi.org/project/claude-ctx/)
+[](#)
+[](graph/)
+[](https://stevesolun.github.io/ctx/)
+
+ctx watches what you are building, walks a **102,696-node** graph, and
+recommends a small, top-scored bundle of skills, agents, and MCP servers for
+the current task. If you use your own local/API model instead of Claude Code,
+ctx has a separate harness catalog flow: tell it the model and goal, review the
+recommended harness, then install with dry-run/update/uninstall controls.
+
+Current shipped snapshot:
+
+- **91,432 skills**: 1,969 curated/imported skills plus **89,463 body-backed Skills.sh skills**.
+- **464 agents**, **10,787 MCP servers**, and **13 cataloged harnesses**.
+- **2.9M graph edges** across semantic similarity, tags, slug tokens, source overlap, direct links, quality, usage, type affinity, and graph structure.
+- **89,463 hydrated `SKILL.md` bodies** in the shipped LLM-wiki; long entries are converted through the micro-skill gate instead of loading raw long prompts.
+- Entity updates for skills, agents, MCPs, and harnesses print benefits/risks and skip replacement unless you explicitly approve the update.
+
+## Why it exists
+
+- **Discovery** — with 91K+ skill nodes, 460+ agents, 10K+ MCP servers, and 13 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 102,696 nodes and 2.9M edges ships as a tarball. The same tarball includes `external-catalogs/skills-sh/catalog.json`, 89,463 body-backed Skills.sh skill pages under `entities/skills/skills-sh-*.md`, 89,463 hydrated installable Skills.sh `SKILL.md` files under `converted/skills-sh-*/`, and 13 cataloged harness pages 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 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, MCP servers, and installed harness records. It provides load/unload buttons where ctx owns the live action, a cytoscape graph view (`/graph?slug=…`), the LLM-wiki entity browser (`/wiki/`), a filterable skills grid, a session timeline, an audit log viewer, and a live SSE event stream. Installed harness records appear in `/loaded`; cataloged harnesses appear in `/wiki` and `/graph`. Harness install/update/uninstall actions stay in `ctx-harness-install`.
+
+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:
+****
+
+Full docs, architecture, and every module: ****
+
+## License
+
+MIT — see [LICENSE](LICENSE).
diff --git a/docs/SKILL.md b/docs/SKILL.md
index e1eb50b87a7a68ff835d33e4b7c90b89b6154130..2bb4187595f896c1db634e31010274154124bb8c 100644
--- a/docs/SKILL.md
+++ b/docs/SKILL.md
@@ -58,17 +58,17 @@ fi
### Step 2: Scan the Active Repo
```bash
-python /path/to/scripts/scan_repo.py --repo "$REPO_PATH" --output /tmp/stack-profile.json
+python -m scan_repo --repo "$REPO_PATH" --output .ctx/stack-profile.json
```
### Step 3: Resolve and Load
```bash
-python /path/to/scripts/resolve_skills.py \
- --profile /tmp/stack-profile.json \
+python -m ctx.core.resolve.resolve_skills \
+ --profile .ctx/stack-profile.json \
--wiki "$WIKI" \
- --available-skills /mnt/skills/ \
- --output /tmp/skill-manifest.json
+ --available-skills "$HOME/.claude/skills" \
+ --output .ctx/skill-manifest.json
```
### Step 4: Apply the Manifest
diff --git a/docs/dashboard.md b/docs/dashboard.md
index fb98186040be38209e2f1f813f338de192d89142..2e53f75190dfe2737107b8b69ea11fdf92e37eab 100644
--- a/docs/dashboard.md
+++ b/docs/dashboard.md
@@ -1,7 +1,7 @@
# Dashboard (`ctx-monitor`)
Local HTTP dashboard for ctx's currently supported live observables:
-loaded skills, agents, and MCP servers; session timelines; the
+loaded skills, agents, MCP servers, and installed harness records; session timelines; the
knowledge graph; the LLM-wiki browser; quality grades + scores;
durable queue state; graph/wiki artifact versions; filterable audit
logs; a live event stream; and cataloged harness wiki/graph browsing.
@@ -20,11 +20,11 @@ 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 dashboard indexes skills, agents, MCP servers, and harness
-pages in wiki/graph views. Harness install, update, load/unload, and
-quality scoring remain CLI/API workflows.
+is `Home -> jump anywhere`. The dashboard indexes skills, agents, MCP
+servers, and harness pages in wiki/graph views. Harness installation,
+update, and uninstall run through `ctx-harness-install`; dashboard
+load/unload POSTs reject harnesses with the exact dry-run command to use.
+Quality scoring is shown for sidecar-backed skills, agents, and MCP servers.
### Check queue and artifact state - `/status`
@@ -35,15 +35,18 @@ generated graph/wiki artifacts that ctx can ship or consume. It reports:
`succeeded`, `failed`)
- the 20 most recent queue jobs with kind, attempts, source, worker, and
last error
-- artifact presence and byte size for `graph.json`, `graph-delta.json`,
- `communities.json`, `wiki-graph.tar.gz`, and `skills-sh-catalog.json.gz`
+- artifact presence and byte size for generated
+ `~/.claude/skill-wiki/graphify-out/{graph.json,graph-delta.json,communities.json}`
+ plus `wiki-graph.tar.gz` and `skills-sh-catalog.json.gz` from
+ `~/.claude/graph/` when installed there, falling back to the repo `graph/`
+ directory during source checkouts
- artifact promotion metadata, including the latest promoted hash when
the crash-safe promotion path has recorded it
### Browse the LLM wiki — `/wiki`
-The wiki tab is a filterable card grid of **every dashboard-supported
-entity page** under
+The wiki tab is a filterable card grid over a bounded dashboard sample:
+up to 500 pages per dashboard-supported entity type under
`~/.claude/skill-wiki/entities/{skills,agents,mcp-servers,harnesses}/`.
MCP server pages use the sharded layout
`entities/mcp-servers//.md`; the dashboard
@@ -56,8 +59,9 @@ the flat `entities/harnesses/.md` layout. Each card shows:
- 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/harness type checkboxes. Pair them to
+The **left sidebar** has a text search over the visible sample that
+matches slug, description, and tags, plus skill/agent/MCP/harness 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.
@@ -139,22 +143,27 @@ Home · Loaded · Skills · Wiki · Graph · Status · KPIs · Sessions · Logs
### HTML views
-Harness catalog entries are visible in loaded, wiki, and graph routes. Harness
-installation, update, uninstall, and quality scoring remain CLI/API workflows.
+Harness catalog entries are visible in wiki and graph routes. `/loaded` shows
+installed harness records from `~/.claude/harness-installs/*.json`, not the
+full catalog. Harness installation, update, and uninstall remain
+`ctx-harness-install` workflows, while harness scoring is not exposed in the
+dashboard yet.
+Dashboard POST actions are available only from loopback clients and require the
+per-process monitor token injected into the rendered page.
| 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, MCP servers, and installed harness records** from `~/.claude/skill-manifest.json` plus `~/.claude/harness-installs/*.json`; skill/MCP rows expose supported live actions |
+| `/loaded` | **Currently-loaded skills, agents, MCP servers, and installed harness records** from `~/.claude/skill-manifest.json` plus `~/.claude/harness-installs/*.json`; skill/agent/MCP rows expose supported live actions |
| `/skills` | Every sidecar as a filterable **card grid**: left sidebar (search by slug, grade checkboxes, skill/agent/MCP toggle, hide-floored), card shows grade pill + raw score + links to sidecar/wiki/graph |
| `/skill/` | 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,harnesses}/`, including sharded MCP server pages and flat harness pages. Left sidebar: text search (slug, description, tag), skill/agent/MCP/harness checkboxes. |
+| `/wiki` | **Wiki entity index** - bounded card-grid sample of up to 500 pages per dashboard-supported entity type under `~/.claude/skill-wiki/entities/{skills,agents,mcp-servers,harnesses}/`, including sharded MCP server pages and flat harness pages. Left sidebar: text search over the visible sample (slug, description, tag), skill/agent/MCP/harness checkboxes. |
| `/wiki/?type=` | Dashboard-supported wiki entity page rendered: markdown body + full frontmatter table + grade banner + deep links to sidecar and graph-neighborhood views. The optional `type` query disambiguates duplicate slugs such as `langgraph`. |
| `/graph` | **Graph explorer landing page** - node/edge count header, a "Popular seed slugs" block (18 highest-degree skill/agent/MCP/harness entities as clickable chips), search box for any skill/agent/MCP/harness slug, and the cytoscape canvas. Clicking a seed chip navigates to `/graph?slug=&type=`. |
| `/graph?slug=&type=` | **Cytoscape-rendered** 1-hop neighborhood around the target skill/agent/MCP/harness slug. Node colors: emerald=focus, indigo=skill, amber=agent, red diamond=MCP server, green hexagon=harness. Edge width maps to blended graph weight. Tap any node to navigate to that entity's typed wiki page. Type and tag filters run client-side. |
| `/status` | Durable queue and artifact status: job counts by state, recent queue jobs, graph/wiki artifact sizes, and crash-safe promotion metadata. |
| `/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 |
+| `/sessions` | Index of every session (audit + skill-events), first/last seen, counts of skills loaded/unloaded, agents loaded/unloaded, MCPs loaded/unloaded, and lifecycle transitions |
| `/session/` | 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 |
@@ -173,7 +182,7 @@ installation, update, uninstall, and quality scoring remain CLI/API workflows.
### Mutation endpoints
-Both POST endpoints enforce same-origin (browser tab open on another
+Dashboard GET views are read-only. 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
@@ -183,13 +192,20 @@ load/unload mutation endpoint yet.
| Route | Body | Calls |
|---|---|---|
-| `POST /api/load` | `{"slug": "..."}` | `skill_loader.load_skill(slug)` |
+| `POST /api/load` | `{"slug": "...", "entity_type": "skill"}` | `skill_install.install_skill(slug)` |
+| `POST /api/load` | `{"slug": "...", "entity_type": "agent"}` | `agent_install.install_agent(slug)` |
+| `POST /api/load` | `{"slug": "...", "entity_type": "mcp-server"}` | `mcp_install.install_mcp(slug, command?, json_config?, auto=True)` |
| `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.
+| `POST /api/unload` | `{"slug": "...", "entity_type": "agent"}` | remove the agent row from `skill-manifest.json` and append an unload row |
+| `POST /api/unload` | `{"slug": "...", "entity_type": "mcp-server"}` | `mcp_install.uninstall_mcp(slug, wiki_dir=...)` |
+
+Harness load/unload POSTs are rejected with the exact
+`ctx-harness-install ... --dry-run` command to run instead. Skill rows emit
+`skill.loaded` / `skill.unloaded`, agent rows emit `agent.loaded` /
+`agent.unloaded`, and MCP rows emit `toolbox.triggered` with
+`meta.entity_type="mcp-server"` and `meta.action` set to `loaded` or
+`unloaded`. All dashboard-driven rows use `actor=user` and
+`meta.via="ctx-monitor"` so they appear in the session timeline.
## KPIs, measures, scores
diff --git a/docs/harness/attaching-to-hosts.md b/docs/harness/attaching-to-hosts.md
index 00e3ab93f55360d10b03c306e9377f2445ec7493..160e1e0ad92de790b447cc66dcb478976238b85e 100644
--- a/docs/harness/attaching-to-hosts.md
+++ b/docs/harness/attaching-to-hosts.md
@@ -216,6 +216,35 @@ system prompt overrides, session resume, JSON output, ...).
---
+## Installed harness attachment
+
+`ctx-harness-install ` creates `.ctx/attach/` inside the installed
+harness target. The directory contains the attach files for the modes that
+catalog entry supports:
+
+- `README.md` describes the supported modes and safety expectations.
+- `mcp.json` starts `ctx-mcp-server` for MCP-speaking hosts.
+- `python.py` shows the Python recommendation/wiki calls for custom loops.
+- `ctx-run.txt` gives a `ctx run` command template.
+
+The install command does not run the harness or store secrets in those files.
+Setup commands still require `--approve-commands`; verification commands still
+require `--run-verify`.
+
+If no catalog harness fits, generate a build handoff instead of forcing a weak
+match:
+
+```bash
+ctx-harness-install --recommend \
+ --goal "build a private CAD workflow with a local model" \
+ --model-provider ollama \
+ --model ollama/llama3.1 \
+ --plan-on-no-fit \
+ --plan-output custom-harness.md
+```
+
+---
+
## Choosing the right path
| Situation | Path |
@@ -223,6 +252,7 @@ system prompt overrides, session resume, JSON output, ...).
| 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) |
+| No catalog harness fits your model/goal | generated custom harness plan |
| 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
diff --git a/docs/harness/clean-host-contract.md b/docs/harness/clean-host-contract.md
index 793ca1e01ffa30169a78d40042ca66ffd00edbb1..37e5251df88e34d0333ef6dfc72a892f863f182d 100644
--- a/docs/harness/clean-host-contract.md
+++ b/docs/harness/clean-host-contract.md
@@ -38,8 +38,8 @@ contract stabilizes.
- 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 enough
-for the default CI path.
+Those checks stay intentionally manual or opt-in until they are stable enough
+for the default CI path.
## Local Usage
diff --git a/docs/huggingface-publish.md b/docs/huggingface-publish.md
index e1707b7bba28ff9716eca3cb9558a2f38a5a0e36..90db8b82ee0cc3bed22609e6f7d23cdcfbc17a26 100644
--- a/docs/huggingface-publish.md
+++ b/docs/huggingface-publish.md
@@ -18,113 +18,30 @@ by git.
## Publish command
-Set the token in the process environment. Do not pass it on a command line
-that will be saved in shell history.
+Use the repository sync script. It exports only tracked files, adds the
+Hugging Face repo-card frontmatter to the uploaded `README.md`, and refuses to
+publish if `graph/wiki-graph.tar.gz` or `graph/skills-sh-catalog.json.gz` is
+missing, too small, or still a Git LFS pointer.
+
+Do not paste the token into a command line. Prompt for it, set it only for the
+current process, and clear it after the upload.
```powershell
-$env:HF_TOKEN = ""
python -m pip install --upgrade huggingface_hub
git lfs install
-git lfs pull --include="graph/wiki-graph.tar.gz"
-@'
-from __future__ import annotations
-
-import os
-import shutil
-import subprocess
-import tempfile
-from pathlib import Path
-
-from huggingface_hub import HfApi
-
-root = Path.cwd()
-token = os.environ["HF_TOKEN"]
-api = HfApi(token=token)
-owner = api.whoami()["name"]
-repo_id = f"{owner}/ctx"
-repo_type = "dataset"
-sha = subprocess.check_output(["git", "rev-parse", "--short", "HEAD"], text=True).strip()
-files = [
- Path(raw.decode("utf-8"))
- for raw in subprocess.check_output(["git", "ls-files", "-z"], cwd=root).split(b"\0")
- if raw
-]
-graph_tar = root / "graph" / "wiki-graph.tar.gz"
-if not graph_tar.is_file() or graph_tar.stat().st_size < 100_000_000:
- raise SystemExit(
- "graph/wiki-graph.tar.gz is not hydrated; run git lfs pull before publishing"
- )
-
-api.create_repo(repo_id=repo_id, repo_type=repo_type, private=False, exist_ok=True, token=token)
-staging = Path(tempfile.mkdtemp(prefix="ctx-hf-upload-"))
-try:
- for rel in files:
- src = root / rel
- if not src.is_file():
- continue
- dst = staging / rel
- dst.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(src, dst)
- api.upload_folder(
- repo_id=repo_id,
- repo_type=repo_type,
- folder_path=staging,
- commit_message=f"Publish ctx snapshot {sha}",
- token=token,
- )
-finally:
- shutil.rmtree(staging, ignore_errors=True)
-'@ | python -
-```
-
-Then upload the dataset-card metadata wrapper for `README.md`:
-
-```powershell
-$env:HF_TOKEN = ""
-@'
-from __future__ import annotations
-
-import os
-import tempfile
-from pathlib import Path
-
-from huggingface_hub import HfApi
-
-token = os.environ["HF_TOKEN"]
-api = HfApi(token=token)
-repo_id = f"{api.whoami()['name']}/ctx"
-frontmatter = """---
-license: mit
-tags:
-- agents
-- mcp
-- skills
-- knowledge-graph
-- llm-wiki
-- recommendation-system
-- harness
-- codex
-- claude-code
-pretty_name: ctx
----
-
-"""
-with tempfile.NamedTemporaryFile("w", encoding="utf-8", suffix=".md", delete=False) as fh:
- path = Path(fh.name)
- fh.write(frontmatter)
- fh.write(Path("README.md").read_text(encoding="utf-8"))
-try:
- api.upload_file(
- repo_id=repo_id,
- repo_type="dataset",
- path_or_fileobj=path,
- path_in_repo="README.md",
- commit_message="Add Hugging Face dataset card metadata",
- token=token,
- )
-finally:
- path.unlink(missing_ok=True)
-'@ | python -
+git lfs pull --include="graph/wiki-graph.tar.gz,graph/skills-sh-catalog.json.gz"
+
+$secureToken = Read-Host "HF write token" -AsSecureString
+$tokenPtr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureToken)
+try {
+ $env:HF_TOKEN = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($tokenPtr)
+ python scripts/sync_huggingface.py --repo . --repo-id Stevesolun/ctx --repo-type dataset
+} finally {
+ if ($tokenPtr -ne [IntPtr]::Zero) {
+ [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($tokenPtr)
+ }
+ Remove-Item Env:\HF_TOKEN -ErrorAction SilentlyContinue
+}
```
## Verify
diff --git a/docs/index.md b/docs/index.md
index 4000b09102adf7d374bf83826ebaf658427b372c..c148625ceedc02c358ebfe25eb56f0aaa86fd6ea 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -181,14 +181,13 @@ ones are flagged. New ones self-ingest.
---
**v0.7.x** — MIT, CI-matrixed (Ubuntu + Windows × Python 3.11/3.12),
- 3,501 tests collected. Ships console scripts including `ctx-init`,
+ 3,617 tests collected. Ships console scripts including `ctx-init`,
`ctx-monitor` (local dashboard with graph + wiki + load/unload for
skills, agents, and MCP servers, plus harness wiki/graph browsing),
`ctx-dedup-check` (pre-ship near-duplicate gate), and
`ctx-tag-backfill` (catalog hygiene), plus the ~336 MiB pre-built
wiki tarball with **102,696 nodes / 2,900,834 edges / 52 Louvain
- communities**. Hardened across the Strix audit + a 12-finding
- codex review.
+ communities**.
[:octicons-arrow-right-24: CHANGELOG](https://github.com/stevesolun/ctx/blob/main/CHANGELOG.md) ·
[Repository](https://github.com/stevesolun/ctx)
diff --git a/docs/knowledge-graph.md b/docs/knowledge-graph.md
index 26045a96742ecaa18905c9f84793698116d4360b..a7a272249232a2d8109fe6fdceccbdb4fe7d4d74 100644
--- a/docs/knowledge-graph.md
+++ b/docs/knowledge-graph.md
@@ -4,8 +4,11 @@ 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, including
plain-slug graph walks from `harness:` nodes. `ctx-monitor`
-exposes skill/agent/MCP/harness wiki and graph views; harness install,
-update, load/unload, and quality scoring remain CLI/API workflows.
+exposes skill/agent/MCP/harness wiki and graph views. Harness installation,
+update, and uninstall are handled by `ctx-harness-install`; dashboard
+load/unload POSTs deliberately reject harnesses and return the dry-run CLI
+command to use instead. Quality scoring is exposed for sidecar-backed skills,
+agents, and MCP servers.
## What's in it
@@ -16,10 +19,11 @@ local rebuilds and the separate harness-catalog recommendation path. The
tarball also carries **89,463 body-backed Skills.sh `skill` nodes**,
matching skill pages under `entities/skills/skills-sh-*.md`. **89,463**
hydrated Skills.sh bodies are shipped as installable `SKILL.md` files under
-`converted/skills-sh-*/`; the **28,611** entries over the configured line
+`converted/skills-sh-*/`; the **28,612** entries over the configured line
limit were converted to gated micro-skill orchestrators. Full original bodies
are used during graph rebuilds for semantic similarity, but
-`SKILL.md.original` backups are omitted from the shipped tarball.
+`SKILL.md.original` backups and transient `.lock` files are omitted from the
+shipped tarball.
| | Count |
|---|---:|
@@ -207,11 +211,12 @@ After you add a skill, agent, MCP server, or harness entity page:
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.
+The pre-commit hook (`.githooks/pre-commit`) does **not** rebuild or
+repack graph artifacts from `~/.claude/skill-wiki/`; that local wiki can
+contain private entities. It refreshes cheap README stats when relevant
+checked-in files are staged and warns when entity sources changed. Run
+`ctx-wiki-graphify`, validate, repack, and stage the artifacts explicitly
+for skill, agent, MCP server, or harness catalog releases.
## Edge-count history
@@ -229,6 +234,7 @@ if your hook config does not include those paths.
| 2026-05-02 GitNexus MCP pass | **2,960,215** | Added GitNexus as a cataloged MCP server entity with 26 cross-type edges to its Skills.sh skill pages and related architecture/refactoring agents; semantic edge count unchanged. |
| 2026-05-04 v0.7.3 artifact refresh | **2,960,215** | Hydrated one recoverable Skills.sh command-injection-testing body, raising hydrated Skills.sh `SKILL.md` files to 89,463; generated micro-skill markdown now defangs high-risk command-injection payloads before packaging. Graph topology unchanged. |
| 2026-05-04 body-backed Skills.sh prune | **2,900,834** | Removed 1,383 Skills.sh records that had no packaged `SKILL.md` body and no parseable Skills.sh prose body. Remaining Skills.sh catalog entries, graph nodes, entity pages, and converted `SKILL.md` bodies are all **89,463**. |
+| 2026-05-05 artifact hygiene refresh | **2,900,834** | Repacked `graph/wiki-graph.tar.gz` to remove transient `.lock` files from the shipped LLM-wiki. Topology unchanged; current tar members: **598,133**. |
The full audit history lives in `CHANGELOG.md`. The current build is
fully reproducible from the wiki content.
diff --git a/docs/marketplace-registry.md b/docs/marketplace-registry.md
index 0d813bb0fdfa41b37bdfdf6363bc307f3fd793e9..7ac29c96f25cf18953b38621b479ff46ddb06311 100644
--- a/docs/marketplace-registry.md
+++ b/docs/marketplace-registry.md
@@ -1,157 +1,157 @@
-# 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
-
-```yaml
-name: local
-type: filesystem
-path: /mnt/skills/
-scan_method: directory listing
-refresh: always current
-priority: 1 # check first
-```
-
-List all installed skills:
-```bash
-find /mnt/skills/ -name "SKILL.md" -maxdepth 3
-```
-
-### 2. User Skills Directory
-
-```yaml
-name: user-local
-type: filesystem
-path: /mnt/skills/user/
-scan_method: directory listing
-refresh: always current
-priority: 2
-```
-
-User-uploaded or custom skills. Same scan as local but separate namespace.
-
-### 3. Example Skills
-
-```yaml
-name: examples
-type: filesystem
-path: /mnt/skills/examples/
-scan_method: directory listing
-refresh: always current
-priority: 3
-```
-
-Bundled example skills that may not be active but can be copied to user skills.
-
-### 4. GitHub Skill Repos
-
-```yaml
-name: github
-type: git
-base_url: https://github.com
-search_method: topic search "claude-skill" OR "hermes-skill"
-install_method: git clone + copy SKILL.md to /mnt/skills/user/
-refresh: on-demand
-priority: 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 fallback
-web_search "claude skill github site:github.com"
-```
-
-### 5. npm Registry (for JS/TS skills packaged as npm)
-
-```yaml
-name: npm
-type: package-registry
-base_url: https://registry.npmjs.org
-search_method: keyword search "claude-skill"
-install_method: npm install -g
-refresh: on-demand
-priority: 6
-```
-
-### 6. PyPI (for Python skills packaged as pip)
-
-```yaml
-name: pypi
-type: package-registry
-base_url: https://pypi.org
-search_method: keyword search "claude-skill" OR "hermes-skill"
-install_method: pip install
-refresh: on-demand
-priority: 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 data
-3. 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 pages
-4. Present findings to user with install commands
-```
-
-## Caching
-
-Marketplace results are cached in the wiki at:
-```
-raw/marketplace-dumps/-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's
-entity 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 confirms
-3. 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 it
-5. Add to current manifest and load
-6. 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 permissions
+# 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
+
+```yaml
+name: local
+type: filesystem
+path: /mnt/skills/
+scan_method: directory listing
+refresh: always current
+priority: 1 # check first
+```
+
+List all installed skills:
+```bash
+find /mnt/skills/ -name "SKILL.md" -maxdepth 3
+```
+
+### 2. User Skills Directory
+
+```yaml
+name: user-local
+type: filesystem
+path: /mnt/skills/user/
+scan_method: directory listing
+refresh: always current
+priority: 2
+```
+
+User-uploaded or custom skills. Same scan as local but separate namespace.
+
+### 3. Example Skills
+
+```yaml
+name: examples
+type: filesystem
+path: /mnt/skills/examples/
+scan_method: directory listing
+refresh: always current
+priority: 3
+```
+
+Bundled example skills that may not be active but can be copied to user skills.
+
+### 4. GitHub Skill Repos
+
+```yaml
+name: github
+type: git
+base_url: https://github.com
+search_method: topic search "claude-skill" OR "hermes-skill"
+install_method: git clone + copy SKILL.md to /mnt/skills/user/
+refresh: on-demand
+priority: 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 fallback
+web_search "claude skill github site:github.com"
+```
+
+### 5. npm Registry (for JS/TS skills packaged as npm)
+
+```yaml
+name: npm
+type: package-registry
+base_url: https://registry.npmjs.org
+search_method: keyword search "claude-skill"
+install_method: npm install -g
+refresh: on-demand
+priority: 6
+```
+
+### 6. PyPI (for Python skills packaged as pip)
+
+```yaml
+name: pypi
+type: package-registry
+base_url: https://pypi.org
+search_method: keyword search "claude-skill" OR "hermes-skill"
+install_method: pip install
+refresh: on-demand
+priority: 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 data
+3. 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 pages
+4. Present findings to user with install commands
+```
+
+## Caching
+
+Marketplace results are cached in the wiki at:
+```
+raw/marketplace-dumps/-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's
+entity 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 confirms
+3. 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 it
+5. Add to current manifest and load
+6. 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 permissions
diff --git a/docs/services/macos/com.claude.backup.watchdog.plist b/docs/services/macos/com.claude.backup.watchdog.plist
index 2bf51965f51494fa7babacbb80bbbee80d16a79f..52e438ce6139ef38fad8fb111592abfaf7b6b9e3 100644
--- a/docs/services/macos/com.claude.backup.watchdog.plist
+++ b/docs/services/macos/com.claude.backup.watchdog.plist
@@ -1,58 +1,58 @@
-
-
-
-
-
- Label
- com.claude.backup.watchdog
-
-
- ProgramArguments
-
- /usr/bin/python3
- /Users/YOUR_USER/ctx/src/backup_mirror.py
- watchdog
- --interval
- 60
-
-
- RunAtLoad
-
-
-
- KeepAlive
-
- SuccessfulExit
-
-
- ThrottleInterval
- 30
-
- StandardOutPath
- /Users/YOUR_USER/Library/Logs/claude-backup-watchdog.log
- StandardErrorPath
- /Users/YOUR_USER/Library/Logs/claude-backup-watchdog.log
-
- ProcessType
- Background
-
-
+
+
+
+
+
+ Label
+ com.claude.backup.watchdog
+
+
+ ProgramArguments
+
+ /usr/bin/python3
+ /Users/YOUR_USER/ctx/src/backup_mirror.py
+ watchdog
+ --interval
+ 60
+
+
+ RunAtLoad
+
+
+
+ KeepAlive
+
+ SuccessfulExit
+
+
+ ThrottleInterval
+ 30
+
+ StandardOutPath
+ /Users/YOUR_USER/Library/Logs/claude-backup-watchdog.log
+ StandardErrorPath
+ /Users/YOUR_USER/Library/Logs/claude-backup-watchdog.log
+
+ ProcessType
+ Background
+
+
diff --git a/docs/services/systemd/claude-backup-watchdog.service b/docs/services/systemd/claude-backup-watchdog.service
index 829eae200e58d679a0581fb07bf4c639465c1172..267d236b680b69becac9688e0474d1d5f1692571 100644
--- a/docs/services/systemd/claude-backup-watchdog.service
+++ b/docs/services/systemd/claude-backup-watchdog.service
@@ -1,40 +1,40 @@
-# 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/ctx
-ExecStart=/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-failure
-RestartSec=5
-StartLimitIntervalSec=60
-StartLimitBurst=3
-# Least-privilege: the watchdog only needs to read ~/.claude and write
-# ~/.claude/backups. No network. No privilege escalation.
-NoNewPrivileges=yes
-PrivateTmp=yes
-ProtectSystem=strict
-ProtectHome=read-only
-ReadWritePaths=%h/.claude/backups
-
-[Install]
-WantedBy=default.target
+# 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/ctx
+ExecStart=/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-failure
+RestartSec=5
+StartLimitIntervalSec=60
+StartLimitBurst=3
+# Least-privilege: the watchdog only needs to read ~/.claude and write
+# ~/.claude/backups. No network. No privilege escalation.
+NoNewPrivileges=yes
+PrivateTmp=yes
+ProtectSystem=strict
+ProtectHome=read-only
+ReadWritePaths=%h/.claude/backups
+
+[Install]
+WantedBy=default.target
diff --git a/docs/services/windows/install-backup-watchdog.ps1 b/docs/services/windows/install-backup-watchdog.ps1
index fce97fdbf292165293bfe4da47d73891f1786352..290c80e846ee1b51c04de680f25c81b0a45edeb0 100644
--- a/docs/services/windows/install-backup-watchdog.ps1
+++ b/docs/services/windows/install-backup-watchdog.ps1
@@ -1,120 +1,120 @@
-# 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 ."
- }
-}
-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"
+# 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 ."
+ }
+}
+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"
diff --git a/docs/skill-lifecycle-and-dashboard.md b/docs/skill-lifecycle-and-dashboard.md
index 9b84d661439924dd65be8c3eabca349828bb7cf0..84cceaede3fe32886efe7954ecf8dc8f5c9d298f 100644
--- a/docs/skill-lifecycle-and-dashboard.md
+++ b/docs/skill-lifecycle-and-dashboard.md
@@ -1,8 +1,8 @@
# 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
+One page on running the lifecycle CLI, the category backfill, and the KPI
+dashboard. Prerequisite: the quality scorer is installed and has written at
+least one sidecar. See
[skill-quality-install.md](./skill-quality-install.md).
## What it does
diff --git a/docs/skill-quality-install.md b/docs/skill-quality-install.md
index 2f99dd898a4df557eec01bab834835e11e181e23..3d2c5f0e69e01e7e41d8709667a5021904a9c086 100644
--- a/docs/skill-quality-install.md
+++ b/docs/skill-quality-install.md
@@ -1,8 +1,7 @@
# 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.
+One page on running the quality scorer: install the Stop hook, seed the
+sidecars, and verify the data flows into the wiki and the knowledge graph.
## What it does
diff --git a/docs/skill-router/index.md b/docs/skill-router/index.md
index 576001a4dd7fa9f90c4d62760eb312f9493360a5..e7d0e345c629c4489b7df9f12ecdfca3ab805b57 100644
--- a/docs/skill-router/index.md
+++ b/docs/skill-router/index.md
@@ -1,49 +1,49 @@
-# Skill router
-
-The skill router decides which skills, plugins, and MCP servers load into
-a 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 and
-attention. 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.
+# Skill router
+
+The skill router decides which skills, plugins, and MCP servers load into
+a 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 and
+attention. 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.
diff --git a/docs/skill-stack-matrix.md b/docs/skill-stack-matrix.md
index 8ed835e9e4d4996f6ed115cc6c66170b38a70525..7113422aac0b66432d97a61b80a7fdb21ea85eec 100644
--- a/docs/skill-stack-matrix.md
+++ b/docs/skill-stack-matrix.md
@@ -1,165 +1,165 @@
-# Skill-Stack Matrix
-
-> Maps stack identifiers to the skills that serve them.
-> Used by resolve_skills.py to determine what to load.
-
-## Table of Contents
-1. [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.
+# Skill-Stack Matrix
+
+> Maps stack identifiers to the skills that serve them.
+> Used by resolve_skills.py to determine what to load.
+
+## Table of Contents
+1. [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.
diff --git a/docs/skills-health.md b/docs/skills-health.md
index da2fc183429cbf1f0867f9b68d5044de9ba74968..4176e16af38b4023a22869892eb65697d5aa9bc1 100644
--- a/docs/skills-health.md
+++ b/docs/skills-health.md
@@ -18,7 +18,7 @@ For each skill (`~/.claude/skills//SKILL.md`) and each agent
| `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 `skill_transformer.line_threshold`; the packaged default is 180 and users can override it in `~/.claude/skill-system-config.json` |
+| `over-threshold` | warning | Line count exceeds `skill_transformer.line_threshold`; the packaged default is 180 and users can override it in `~/.claude/skill-system-config.json` |
## Drift detection
diff --git a/docs/stack-signatures.md b/docs/stack-signatures.md
index c286a9655313bf3604550e63c746ee0e00ddd47f..5ed30ed62bc2498542a01656969f2c834a165ca8 100644
--- a/docs/stack-signatures.md
+++ b/docs/stack-signatures.md
@@ -1,164 +1,164 @@
-# 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 Contents
-1. [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 |
+# 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 Contents
+1. [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 |
diff --git a/docs/toolbox/hooks.md b/docs/toolbox/hooks.md
index 55ef4d55194affda84d8ac212c640657364578b0..26b2d5ff5cc503335d76a0e3b315db15e6226747 100644
--- a/docs/toolbox/hooks.md
+++ b/docs/toolbox/hooks.md
@@ -1,80 +1,80 @@
-# 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 ` | User-initiated | Anything |
-
-Each trigger in a toolbox's `trigger` map enables that toolbox on that
-event. 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 agent
-against 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/sh
-ctx-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` arg
-the 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 updated
-profile, 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.
+# 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 ` | User-initiated | Anything |
+
+Each trigger in a toolbox's `trigger` map enables that toolbox on that
+event. 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 agent
+against 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/sh
+ctx-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` arg
+the 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 updated
+profile, 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.
diff --git a/docs/toolbox/index.md b/docs/toolbox/index.md
index 9470af5c2fae80ae3da127de44f61413b05beab3..8b5ec606c41ecc75a758ec0ee45b8152948f37a4 100644
--- a/docs/toolbox/index.md
+++ b/docs/toolbox/index.md
@@ -50,11 +50,11 @@ toolboxes:
guardrail: true
```
-Run it manually:
-
-```bash
-ctx-toolbox run --event pre-commit
-```
+Run it manually:
+
+```bash
+ctx-toolbox run --event pre-commit
+```
Or let the `pre-commit` hook fire it automatically — see
[Hooks & triggers](hooks.md).
diff --git a/docs/toolbox/templates/docs-review.json b/docs/toolbox/templates/docs-review.json
index c3abfd37585c77d840449cdf5e3dad795ab18fc5..35684ce301d30ba0d07e9d57b892fc5d38b2e50c 100644
--- a/docs/toolbox/templates/docs-review.json
+++ b/docs/toolbox/templates/docs-review.json
@@ -1,30 +1,30 @@
-{
- "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
-}
+{
+ "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
+}
diff --git a/docs/toolbox/templates/fresh-repo-init.json b/docs/toolbox/templates/fresh-repo-init.json
index 4d5b5ee6f7d267330eb6aadcf23b7f2bc40ce6c2..0486aac5af00d044a62415c280a008f3875cc284 100644
--- a/docs/toolbox/templates/fresh-repo-init.json
+++ b/docs/toolbox/templates/fresh-repo-init.json
@@ -1,29 +1,29 @@
-{
- "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
-}
+{
+ "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
+}
diff --git a/docs/toolbox/templates/refactor-safety.json b/docs/toolbox/templates/refactor-safety.json
index 3b110b80d03a3b943071eff25a1455ed484953c6..c2be0157bf5b980b3b31392b847352d0f835e94a 100644
--- a/docs/toolbox/templates/refactor-safety.json
+++ b/docs/toolbox/templates/refactor-safety.json
@@ -1,31 +1,31 @@
-{
- "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
-}
+{
+ "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
+}
diff --git a/docs/toolbox/templates/security-sweep.json b/docs/toolbox/templates/security-sweep.json
index a6cf01db115770e2b65cc0940ba68a8d9a78884b..24bfe12187a81b7a7ff6c48894cf4726fdf83005 100644
--- a/docs/toolbox/templates/security-sweep.json
+++ b/docs/toolbox/templates/security-sweep.json
@@ -1,31 +1,31 @@
-{
- "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
-}
+{
+ "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
+}
diff --git a/docs/toolbox/templates/ship-it.json b/docs/toolbox/templates/ship-it.json
index 1aa7b9c6d1e9985f9aa8ae5bf3b1e6f6b4f76903..924ef774011e9c407793ca33b64184d21f1965e4 100644
--- a/docs/toolbox/templates/ship-it.json
+++ b/docs/toolbox/templates/ship-it.json
@@ -1,33 +1,33 @@
-{
- "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
-}
+{
+ "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
+}
diff --git a/graph/README.md b/graph/README.md
index 9f54d7dc5b103eea23c9225b9d075027af3a7d50..942e020913698b308c4f3fbb5557dcc756f79de6 100644
--- a/graph/README.md
+++ b/graph/README.md
@@ -1,169 +1,123 @@
-# Knowledge Graph
+# Knowledge Graph Artifacts
-Pre-built knowledge graph of **102,696 nodes** and **2,900,834 edges** across **52 communities** (Louvain). The curated core is **13,233 nodes** (1,969 curated skills + 464 agents + 10,787 MCP servers + 13 cataloged harnesses). The Skills.sh catalog contributes **89,463 first-class body-backed `skill` nodes**, **89,463 skill entity pages under `entities/skills/skills-sh-*.md`**, and **89,463 hydrated installable Skills.sh `SKILL.md` files** under `converted/skills-sh-*/`, with the **28,611** long entries converted to gated micro-skill orchestrators. Edges are blended from three signals: semantic cosine (**1,682,825** edges, default weight 0.70), explicit `tags:` overlap (**891,684** candidate pairs, weight 0.15), and sparse slug-token overlap (**433,074** candidate pairs, weight 0.15). Skills.sh is full-body semantic: **1,500,685** Skills.sh-incident edges have non-zero `semantic_sim`, including **1,412,547** Skills.sh-to-Skills.sh semantic edges. Rebuild with `python -m ctx.core.wiki.wiki_graphify`, add harnesses with `ctx-harness-add`, then refresh the Skills.sh catalog with `python src/import_skills_sh_catalog.py --from-api-union --drop-body-unavailable --update-wiki-tar`.
+This directory ships the pre-built ctx LLM-wiki and knowledge graph.
-Runtime recommendation is intentionally split into two paths: execution
-surfaces recommend only skills, agents, and MCP servers; custom/API/local model
-onboarding recommends harnesses from the same graph catalog with the higher
-harness match floor in `config.json`.
+Current snapshot:
-> **2026-04-30.** Completed the Skills.sh full-body semantic regraph. That build had **2,881,027** edges, including **1,626,632** semantic edges. Skills.sh nodes had **1,451,838** non-zero semantic incident edges. The slug-token dense threshold was tightened from 500 to 30 because hydrated Skills.sh slugs created 13M+ low-signal token-only pairs and made export fail; semantic top-K and explicit tags are now the primary large-scale signals.
+- **102,696 graph nodes**
+- **2,900,834 graph edges**
+- **52 Louvain communities**
+- **91,432 skill entity pages**: 1,969 curated/imported skills plus 89,463 body-backed Skills.sh skills
+- **464 agent pages**
+- **10,787 MCP server pages**
+- **13 harness pages**
+- **89,463 hydrated Skills.sh `SKILL.md` bodies**
+- **28,612 long Skills.sh bodies converted through the micro-skill gate**
-> **2026-05-01.** Converted the hydrated Skills.sh corpus to micro-skill form. All **89,461** hydrated Skills.sh `SKILL.md` files are now under the 180-line loader threshold; **28,611** long bodies were split into gated pipeline stages for loading. The full-body semantic graph was rebuilt from preserved source material before packaging, but `SKILL.md.original` backups are not shipped in `wiki-graph.tar.gz`. Generated stage/reference markdown is bounded to 40 lines and raw PHP openers are defanged in generated markdown. The graph now has **2,960,189** edges, including **1,707,435** semantic edges.
+The runtime recommendation paths use this graph in two ways:
-> **2026-05-02.** Added [GitNexus](https://github.com/abhigyanpatwari/GitNexus) as a first-class cataloged MCP server entity, linked to its Skills.sh GitNexus skill pages and related architecture/refactoring agents. Node count: 104,078 -> **104,079**. Edge count: 2,960,189 -> **2,960,215**. The GitNexus node has 26 incident cross-type edges and an MCP quality score of 0.8997 (grade A). Its PolyForm Noncommercial license is recorded in frontmatter, so install decisions remain explicit.
+- Development recommendations return skills, agents, and MCP servers only.
+- Custom/API/local model onboarding recommends harnesses from the harness catalog using the higher harness fit floor in `src/config.json`.
-> **2026-05-04.** Refreshed the v0.7.3 artifact after recovering one Skills.sh command-injection-testing body. Hydrated Skills.sh installable bodies increased from 89,462 to **89,463** and total converted skill bodies increased from 91,235 to **91,236**. Graph topology stayed at **104,079 nodes** and **2,960,215 edges**; generated micro-skill markdown now defangs high-risk command-injection payloads before packaging.
-
-> **2026-05-04.** Pruned **1,383** Skills.sh records that had no packaged `SKILL.md` body and no parseable Skills.sh prose body. The shipped catalog now contains **89,463** Skills.sh entries, and every Skills.sh catalog entry has a matching entity page plus converted `SKILL.md` body. Node count: 104,079 -> **102,696**. Edge count: 2,960,215 -> **2,900,834**. Communities: 53 -> **52**.
-
-> **2026-04-29.** Expanded the harness catalog to 13 first-class `harness` nodes/pages: LangGraph, CrewAI, AutoGen, Google ADK, Semantic Kernel, Mastra, Pydantic AI, Haystack, OpenAI Agents SDK, LiteLLM, Langfuse, AgentOps, and [`text-to-cad`](https://github.com/earthtojake/text-to-cad). Node count: 104,066 -> **104,078**. Edge count: 1,031,011 -> **1,033,253**. Harness incident edges now total 2,700: 2,411 curated-core edges plus 289 remote-cataloged Skills.sh metadata edges.
-
-> **2026-04-29.** Added the curated `find-skills` workflow and mirrored it into `converted/find-skills/SKILL.md`, so fresh clones can install it from the shipped wiki. Curated node count: 13,218 -> **13,219**. Curated edge count: 963,068 -> **963,312**. The tarball now also carries Skills.sh catalog coverage as **90,846 remote-cataloged `skill` nodes**, matching skill pages under `entities/skills/skills-sh-*.md`, and `external-catalogs/skills-sh/catalog.json`.
+## Files
-> **2026-04-27.** Two imports landed this day:
-> - **[mattpocock/skills](https://github.com/mattpocock/skills)** — 21 opinionated behavior skills (TDD, domain-model, ubiquitous-language, github-triage, plus 17 more) under the `mattpocock-` prefix.
-> - **[designdotmd.directory](https://designdotmd.directory)** — 156 DESIGN.md visual-identity files (color tokens, typography, spacing, component tokens, rationale) under the `designdotmd-` prefix. These are *reference designs* (data the agent reads when asked to build a UI), not behavior skills.
->
-> Node count: 13,041 → **13,218** (+177 = 21 mattpocock + 156 designdotmd). Edge count: 847,207 → **963,068** (+106,702 from designdotmd-driven tag/token overlap with the existing catalog).
+| File | Contents |
+|---|---|
+| `wiki-graph.tar.gz` | Full LLM-wiki: entity pages, converted skill bodies, mirrored agent bodies, concept pages, `graphify-out/graph.json`, communities, external catalogs, and Obsidian metadata |
+| `skills-sh-catalog.json.gz` | Compressed Skills.sh catalog for the 89,463 body-backed entries shipped in the wiki |
+| `communities.json` | Current Louvain community export |
+| `viz-overview.html` / `.png` | Plotly overview of the graph |
+| `viz-python.html` | Python-focused graph view |
+| `viz-security.html` / `.png` | Security-focused graph view |
+| `viz-ai-agents.html` | AI-agent-focused graph view |
+| `sample-top60.html` | Interactive top-degree sample |
+
+## What Is Inside `wiki-graph.tar.gz`
+
+- `entities/skills/` - all skill entity pages, including `skills-sh-*` pages
+- `entities/agents/` - agent entity pages
+- `entities/mcp-servers//` - sharded MCP server entity pages
+- `entities/harnesses/` - harness entity pages
+- `converted/` - installable skill bodies for curated and Skills.sh skills
+- `converted-agents/` - mirrored agent bodies
+- `concepts/` - community concept pages
+- `external-catalogs/skills-sh/` - Skills.sh catalog, summary, and coverage metadata
+- `graphify-out/graph.json` - NetworkX node-link graph
+- `graphify-out/communities.json` - community export
+- `SCHEMA.md`, `index.md`, `log.md`, `catalog.md` - wiki contract and indexes
+- `.obsidian/` - vault metadata for local graph browsing
+
+`SKILL.md.original` backups and transient `.lock` files are not shipped. Local
+micro-skill conversion may keep `.original` files for traceability, but the
+packaged tarball excludes them so users do not ingest raw long bodies after
+conversion.
+
+## Extract
-> **Bugs fixed in this release:**
->
-> - *Patch-path edge silence.* `wiki_graphify`'s incremental path used to keep stale edges when the semantic backend went from unavailable → available between runs (no node content changed, so the affected-set was empty, so freshly-computed semantic pairs never landed). Fixed: the build now detects "prior graph has 0 semantic edges but current run computed semantic pairs" and forces a full rebuild. Regression test added in `test_wiki_graphify_density.py`.
-> - *CNM community-detection hang.* The legacy CNM (greedy modularity) algorithm took 50+ minutes on the 13K-node graph stuck in `_siftup`. Fixed: switched default to **Louvain** (`networkx.algorithms.community.louvain_communities`) with deterministic seed=42. CNM still available behind `CTX_GRAPH_COMMUNITY=cnm` for legacy parity.
+```bash
+mkdir -p ~/.claude/skill-wiki
+tar xzf graph/wiki-graph.tar.gz -C ~/.claude/skill-wiki/
+```
-> **Edge-count history.** v0.5.x shipped a stale `graph.json` with 642K edges from a build path that no longer existed; the live rebuild silently produced only 861 edges because `DENSE_TAG_THRESHOLD=20` dropped every tag with more than 20 nodes. v0.6.0 fixed the threshold and added slug-token pseudo-tags, reaching a 454K-edge graph. v0.7 ingested 10,786 MCP servers from pulsemcp, added sentence-embedding semantic edges with a configurable `build_floor=0.50` / `min_cosine=0.80` split, wired the alive-loop cumulative-threshold trigger, and shipped install/uninstall CLIs. The curated-core rebuild added 21 mattpocock skills + 156 designdotmd designs, fixed the patch-path bug, and switched to Louvain, bringing the graph to 963K curated edges. The Skills.sh catalog/harness passes brought the graph to 1.03M edges. The full-body Skills.sh semantic regraph reached **2.88M** edges; the micro-skill conversion rebuild now ships **2.96M** edges with semantic top-K as the dominant large-scale signal.
+On Windows with Git Bash or MSYS tar, use `--force-local`:
-## Files
+```bash
+tar --force-local xzf graph/wiki-graph.tar.gz -C ~/.claude/skill-wiki/
+```
-| File | Size | Contents |
-|------|------|----------|
-| `wiki-graph.tar.gz` | ~334 MiB | **Full wiki** - entity cards, 89,463 Skills.sh converted skill bodies, 430 mirrored agent bodies, 102.7K-node / 2.9M-edge knowledge graph, concept pages, catalog, 13 cataloged harnesses, and first-class hydrated Skills.sh installable pages |
-| `skills-sh-catalog.json.gz` | ~11.1 MiB | Compressed Skills.sh catalog (89,463 observed body-backed entries, install commands, detail URLs, inferred tags, overlap metadata) |
-| `communities.json` | ~6.6 MiB | 52 detected communities (Louvain) with labels + member lists |
-| `viz-overview.html` / `.png` | — | Plotly-rendered overview of the full graph |
-| `viz-python.html` | — | Python-skills sub-view |
-| `viz-security.html` / `.png` | — | Security-skills sub-view |
-| `viz-ai-agents.html` | — | AI agents sub-view |
-| `sample-top60.html` | — | Top-60-by-degree nodes, interactive |
-
-### What's inside `wiki-graph.tar.gz`
-
-- `entities/skills/` - **91,432** skill entity pages: 1,969 curated ctx skills plus 89,463 body-backed Skills.sh pages under the `skills-sh-` prefix
-- `entities/agents/` — **464** agent entity pages
-- `entities/mcp-servers//` — **10,787** MCP entity pages (sharded by first-char to keep dirs scannable)
-- `entities/harnesses/` - **13** harness entity pages
-- `concepts/` - community concept pages generated from the current Louvain labels
-- `converted/` - **89,463** hydrated Skills.sh `SKILL.md` files plus curated skill bodies ready for `ctx-skill-install`. Long entries over the configured loader threshold are gated micro-skill orchestrators; no `SKILL.md.original` backups are shipped
-- `converted-agents/` — **430** agent bodies ready for `ctx-agent-install`
-- `graphify-out/graph.json` - full knowledge graph (102,696 nodes, 2,900,834 edges), including the curated core, cataloged harnesses, and full-body semantic Skills.sh skill nodes
-- `graphify-out/communities.json` - community detection results (52 communities, Louvain)
-- `external-catalogs/skills-sh/catalog.json` — Skills.sh catalog (89,463 observed body-backed entries; site reported 90,991 during the clean refresh), including graph node IDs, entity paths, install commands, duplicate hints, and quality signals
-- `external-catalogs/skills-sh/summary.json` and `README.md` — fetch/coverage/overlap metadata for the catalog
-- `catalog.md` — bulk listing of skills / agents / MCPs
-- `SCHEMA.md`, `index.md`, `log.md` — wiki infrastructure
-- `.obsidian/` — Obsidian vault config, so the extracted tree opens as a graph directly in Obsidian
-
-Excluded to keep the tarball reviewable (all regenerable on first local run): `raw/` (pulsemcp HTML cache, ~700MB), `.embedding-cache/` (sentence-transformer vectors + top-K state, hundreds of MB), `.ingest-checkpoint/`, `.enrich-checkpoint/`, `graphify-out/graph-delta.json`, and micro-skill `SKILL.md.original` backups.
-
-## Usage
-
-### Extract the wiki
+## Validate
```bash
-# Extract to ~/.claude/skill-wiki/
-mkdir -p ~/.claude/skill-wiki
-tar xzf graph/wiki-graph.tar.gz -C ~/.claude/skill-wiki/
+python src/validate_graph_artifacts.py --deep
+python src/update_repo_stats.py --check
```
-> **Windows / Git-Bash / MSYS:** pass `--force-local` so `tar` doesn't parse `c:` as a remote host: `tar --force-local xzf graph/wiki-graph.tar.gz -C ~/.claude/skill-wiki/`.
-
-This gives you:
-- Every curated entity (skill / agent / MCP / harness) plus every remote-cataloged Skills.sh skill page browsable as frontmatter-rich markdown
-- Installable content for every curated short/long skill, 89,463 hydrated Skills.sh `SKILL.md` files, and every mirrored agent (`ctx-skill-install`, `ctx-agent-install`)
-- The full knowledge graph (`graphify-out/graph.json`) and community detection (`communities.json`)
-- An Obsidian vault — open the extracted dir in Obsidian and the graph view renders directly
-
-### Load the graph in 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())
-# Auto-detect the NetworkX 2.x "links" vs 3.x "edges" schema.
-# v0.6.x graphs used "links"; v0.7+ uses "edges".
-edges_key = "links" if "links" in raw else "edges"
-G = node_link_graph(raw, edges=edges_key)
-
-# 102,696 nodes, 2,900,834 edges
-print(G.number_of_nodes(), G.number_of_edges())
-
-# Find entities related to "fastapi"
-fastapi = "skill:fastapi-pro"
-neighbors = sorted(G.neighbors(fastapi),
- key=lambda n: G[fastapi][n]["weight"], reverse=True)[:10]
-for n in neighbors:
- edge = G[fastapi][n]
- print(f" {G.nodes[n]['label']} (weight={edge['weight']})")
+For release-count validation, pin the exact snapshot numbers:
+
+```bash
+python src/validate_graph_artifacts.py --deep \
+ --expected-nodes 102696 \
+ --expected-edges 2900834 \
+ --expected-semantic-edges 1682825 \
+ --expected-harness-nodes 13 \
+ --expected-skills-sh-nodes 89463 \
+ --expected-skills-sh-catalog-entries 89463 \
+ --expected-skills-sh-converted 89463 \
+ --expected-skill-pages 91432 \
+ --expected-agent-pages 464 \
+ --expected-mcp-pages 10787 \
+ --expected-harness-pages 13
```
-Or just use the dashboard:
+Manual sanity checks:
```bash
-ctx-monitor serve
-# then open http://127.0.0.1:8765/graph?slug=fastapi-pro
+tar -tzf graph/wiki-graph.tar.gz | grep 'graphify-out/graph.json'
+tar -tzf graph/wiki-graph.tar.gz | grep 'external-catalogs/skills-sh/catalog.json'
+tar -tzf graph/wiki-graph.tar.gz | grep 'SKILL.md.original' && exit 1 || true
+tar -tzf graph/wiki-graph.tar.gz | grep '\.lock$' && exit 1 || true
```
-### Open in Obsidian
+Windows PowerShell equivalent for the exclusion checks:
-The extracted wiki is an Obsidian-compatible vault. Entity pages use `[[wikilinks]]` for cross-references. Open the directory in Obsidian and use the graph view to explore visually.
+```powershell
+tar -tzf graph/wiki-graph.tar.gz | Select-String 'SKILL.md.original'
+tar -tzf graph/wiki-graph.tar.gz | Select-String '\.lock$'
+```
+
+The PowerShell commands should print nothing.
## Rebuild
-After adding or changing skills, agents, MCP entities, or harnesses:
+After adding or updating skills, agents, MCP servers, or harnesses:
```bash
-python src/wiki_batch_entities.py --all # skills/agents only; MCPs/harnesses already write entity pages
-python -m ctx.core.wiki.wiki_graphify # rebuild graph + communities; --full to force semantic top-K
-ctx-dedup-check --threshold 0.85 # pre-ship dedup gate (flag-only, NEVER drops)
-ctx-tag-backfill # report-only by default; --apply to write
-python src/render_graph_viz.py # refresh graph/*.html and overview PNG snapshots
+ctx-wiki-graphify
+python src/validate_graph_artifacts.py --deep
+python src/update_repo_stats.py --check
```
-`nashsu/llm_wiki` was reviewed as a design reference for source traceability,
-ingest queues, graph insights, and budgeted retrieval. Its GPLv3 license is
-not compatible with copying code into this MIT repo, so ctx should adopt only
-independently implemented ideas.
-
-### Pre-ship gates
-
-Two gates run before the tarball is repackaged. Both are advisory: they
-generate local review reports and never auto-modify the catalog. Those
-reports are intentionally ignored by git because they can include local
-filesystem paths and human review notes.
-
-**`ctx-dedup-check`** — finds entity pairs (skill ↔ skill, skill ↔ agent,
-skill ↔ MCP, agent ↔ agent, agent ↔ MCP, MCP ↔ MCP) with cosine
-similarity ≥ 0.85. Emits ignored local files under `graph/`, including a
-top-results markdown report and gzipped JSON sidecar. Incremental: a
-`dedup-state.json` next to the embeddings cache means follow-up runs only
-re-check pairs involving entities whose content changed. Pairs that are
-legitimately distinct can be added to
-`.dedup-allowlist.txt` to suppress them in future reports without
-silencing the underlying detection.
-
-**`ctx-tag-backfill`** — finds skills/agents with empty or missing
-`tags:` frontmatter and proposes a backfill set drawn from the slug
-tokens, body keywords, and the existing tag vocabulary. Report-only by
-default; pass `--apply` to write. The generated markdown and JSON reports
-are ignored by git. Backfills are additive: the gate never removes or
-rewrites existing tags.
-
-Then re-archive. The pre-commit hook only reminds you when the tracked graph
-artifacts may be stale; graph archives are refreshed by explicit commands so
-the exclusion policy is visible and repeatable:
+After a full wiki refresh, repack with the same exclusion contract:
```bash
cd ~/.claude/skill-wiki
@@ -177,7 +131,21 @@ tar --force-local -czf /path/to/ctx/graph/wiki-graph.tar.gz \
--exclude='./graphify-out/graph-delta.json' \
--exclude='./graphify-out/graph.pickle' \
--exclude='*.original' \
+ --exclude='*.lock' \
.
```
-The exclusions keep the tarball under GitHub's 100MB file limit (raw/ alone is ~700MB of regenerable pulsemcp HTML). `--force-local` tells MSYS `tar` on Windows not to parse `c:` as a remote host. Non-Windows users can drop that flag.
+The excluded paths are regenerable local caches or trace files. They are omitted
+to keep the release artifact small and to prevent raw long skill bodies from
+being loaded by users.
+
+## Implementation Notes
+
+The graph is built by `ctx.core.wiki.wiki_graphify` and the `ctx-wiki-graphify`
+console script. Edges blend semantic similarity, explicit tag overlap,
+slug-token overlap, source overlap, direct links, quality, usage, type affinity,
+and graph-structure signals where available.
+
+`nashsu/llm_wiki` was reviewed for design ideas around persistent wiki
+contracts, queues, retrieval, and graph maintenance. ctx does not vendor that
+code in this MIT repository.
diff --git a/graph/skills-sh-catalog.json.gz b/graph/skills-sh-catalog.json.gz
index 525801e9a3e52ae5690098cd52d148ce78dd6994..7474c131d54a474f1de95710075dc4295ae074d2 100644
--- a/graph/skills-sh-catalog.json.gz
+++ b/graph/skills-sh-catalog.json.gz
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:42419057bb2f38988965cfe76925b57132e89dd0dd10d53004bb5aa883833a84
+oid sha256:7bc50901b213fe812bf5aac47dfcb5911e28652ee83e6a85c601b95212bf6d09
size 11656721
diff --git a/graph/wiki-graph.tar.gz b/graph/wiki-graph.tar.gz
index e8a8a75f4be9db758e41cc536c60d25b9ac6346c..f9f3b85f15ad580c7c13c6d07d56a2e9f8dffaa8 100644
--- a/graph/wiki-graph.tar.gz
+++ b/graph/wiki-graph.tar.gz
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:8f7fe19786afb7853896c7e82c59fd5408ed4aee684d71c28e712a67eadc041b
-size 350608878
+oid sha256:9c05b7cfc7cc6740212fa761f358a5e104084411cdb0cbf3bf0163f42ea1d03f
+size 350608323
diff --git a/hooks/backup_on_change.py b/hooks/backup_on_change.py
index 1e251d5bdcd851af05678fe465dbb0910a3f5043..f5bc73597814f526d01b017f9c9606391809464e 100644
--- a/hooks/backup_on_change.py
+++ b/hooks/backup_on_change.py
@@ -1,166 +1,166 @@
-#!/usr/bin/env python3
-"""
-backup_on_change.py -- PostToolUse hook that snapshots on config changes.
-
-Designed to be registered in ``~/.claude/settings.json`` under:
-
- "hooks": {
- "PostToolUse": [
- {
- "matcher": "Edit|Write|MultiEdit",
- "hooks": [
- {
- "type": "command",
- "command": "python /hooks/backup_on_change.py"
- }
- ]
- }
- ]
- }
-
-Claude Code delivers each PostToolUse event as a JSON payload on stdin.
-This script:
-
- 1. Parses the payload.
- 2. Checks whether the tool edited a file that BackupConfig tracks
- (top_files, trees, or projects/*/memory when memory_glob is on).
- 3. If so, shells out to ``python src/backup_mirror.py snapshot-if-changed
- --reason :`` so the snapshot name records what fired it.
- 4. Never blocks the tool: any error is logged to stderr and the hook
- exits 0 so a bug here can't stall the user's session.
-
-Snapshots only happen when content *actually* changed (SHA diff against
-the last snapshot's manifest) — so a no-op Edit won't create a folder.
-"""
-
-from __future__ import annotations
-
-import json
-import os
-import subprocess
-import sys
-from pathlib import Path
-from typing import Any
-
-
-REPO_ROOT = Path(__file__).resolve().parent.parent
-SRC = REPO_ROOT / "src"
-if str(SRC) not in sys.path:
- sys.path.insert(0, str(SRC))
-
-
-def _load_payload() -> dict[str, Any]:
- """Read the PostToolUse payload from stdin. Empty on error."""
- try:
- raw = sys.stdin.read()
- if not raw.strip():
- return {}
- data = json.loads(raw)
- return data if isinstance(data, dict) else {}
- except (json.JSONDecodeError, OSError):
- return {}
-
-
-def _extract_touched_path(payload: dict[str, Any]) -> Path | None:
- """Pull the file path out of an Edit / Write / MultiEdit payload."""
- tool_input = payload.get("tool_input") or {}
- if not isinstance(tool_input, dict):
- return None
- # Edit, Write, MultiEdit all use ``file_path``.
- candidate = tool_input.get("file_path")
- if isinstance(candidate, str) and candidate:
- try:
- return Path(candidate).expanduser().resolve(strict=False)
- except (OSError, ValueError):
- return None
- return None
-
-
-def _is_tracked(path: Path, claude_home: Path) -> bool:
- """True when ``path`` is one of the files BackupConfig mirrors."""
- # Lazy import: hook must still function even when the rest of the
- # repo's dependency graph is in a weird state (e.g. during install).
- try:
- from backup_config import from_ctx_config # noqa: PLC0415
- except ImportError:
- return False
-
- cfg = from_ctx_config()
-
- try:
- path_resolved = path.resolve(strict=False)
- home_resolved = claude_home.resolve(strict=False)
- except OSError:
- return False
-
- try:
- rel = path_resolved.relative_to(home_resolved)
- except ValueError:
- return False
-
- rel_posix = rel.as_posix()
-
- # Top-level files: match by basename against cfg.top_files.
- if rel_posix in cfg.top_files:
- return True
-
- # Trees: match any file under a tracked tree's src prefix.
- for tree in cfg.trees:
- prefix = tree.src.rstrip("/") + "/"
- if rel_posix == tree.src or rel_posix.startswith(prefix):
- return True
-
- # Memory glob: projects//memory/...
- if cfg.memory_glob:
- parts = rel.parts
- if len(parts) >= 3 and parts[0] == "projects" and parts[2] == "memory":
- return True
-
- return False
-
-
-def _invoke_snapshot(reason: str) -> int:
- """Shell out to snapshot-if-changed. Returns child exit code (or 0)."""
- mirror = SRC / "backup_mirror.py"
- if not mirror.is_file():
- print(f"[backup_on_change] missing {mirror}", file=sys.stderr)
- return 0
- try:
- result = subprocess.run(
- [sys.executable, str(mirror), "snapshot-if-changed",
- "--reason", reason],
- capture_output=True,
- text=True,
- timeout=60,
- check=False,
- )
- if result.stdout.strip():
- print(result.stdout.strip(), file=sys.stderr)
- if result.returncode != 0 and result.stderr.strip():
- print(result.stderr.strip(), file=sys.stderr)
- return result.returncode
- except (OSError, subprocess.TimeoutExpired) as exc:
- print(f"[backup_on_change] snapshot failed: {exc}", file=sys.stderr)
- return 0
-
-
-def main() -> int:
- payload = _load_payload()
- tool_name = str(payload.get("tool_name") or "unknown")
-
- touched = _extract_touched_path(payload)
- if touched is None:
- return 0
-
- claude_home = Path(os.path.expanduser("~/.claude"))
- if not _is_tracked(touched, claude_home):
- return 0
-
- reason = f"{tool_name}:{touched.name}"
- _invoke_snapshot(reason)
- # Always exit 0: hook failures must not block the user's tool.
- return 0
-
-
-if __name__ == "__main__":
- sys.exit(main())
+#!/usr/bin/env python3
+"""
+backup_on_change.py -- PostToolUse hook that snapshots on config changes.
+
+Designed to be registered in ``~/.claude/settings.json`` under:
+
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "Edit|Write|MultiEdit",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "python /hooks/backup_on_change.py"
+ }
+ ]
+ }
+ ]
+ }
+
+Claude Code delivers each PostToolUse event as a JSON payload on stdin.
+This script:
+
+ 1. Parses the payload.
+ 2. Checks whether the tool edited a file that BackupConfig tracks
+ (top_files, trees, or projects/*/memory when memory_glob is on).
+ 3. If so, shells out to ``python src/backup_mirror.py snapshot-if-changed
+ --reason :`` so the snapshot name records what fired it.
+ 4. Never blocks the tool: any error is logged to stderr and the hook
+ exits 0 so a bug here can't stall the user's session.
+
+Snapshots only happen when content *actually* changed (SHA diff against
+the last snapshot's manifest) — so a no-op Edit won't create a folder.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+from typing import Any
+
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+SRC = REPO_ROOT / "src"
+if str(SRC) not in sys.path:
+ sys.path.insert(0, str(SRC))
+
+
+def _load_payload() -> dict[str, Any]:
+ """Read the PostToolUse payload from stdin. Empty on error."""
+ try:
+ raw = sys.stdin.read()
+ if not raw.strip():
+ return {}
+ data = json.loads(raw)
+ return data if isinstance(data, dict) else {}
+ except (json.JSONDecodeError, OSError):
+ return {}
+
+
+def _extract_touched_path(payload: dict[str, Any]) -> Path | None:
+ """Pull the file path out of an Edit / Write / MultiEdit payload."""
+ tool_input = payload.get("tool_input") or {}
+ if not isinstance(tool_input, dict):
+ return None
+ # Edit, Write, MultiEdit all use ``file_path``.
+ candidate = tool_input.get("file_path")
+ if isinstance(candidate, str) and candidate:
+ try:
+ return Path(candidate).expanduser().resolve(strict=False)
+ except (OSError, ValueError):
+ return None
+ return None
+
+
+def _is_tracked(path: Path, claude_home: Path) -> bool:
+ """True when ``path`` is one of the files BackupConfig mirrors."""
+ # Lazy import: hook must still function even when the rest of the
+ # repo's dependency graph is in a weird state (e.g. during install).
+ try:
+ from backup_config import from_ctx_config # noqa: PLC0415
+ except ImportError:
+ return False
+
+ cfg = from_ctx_config()
+
+ try:
+ path_resolved = path.resolve(strict=False)
+ home_resolved = claude_home.resolve(strict=False)
+ except OSError:
+ return False
+
+ try:
+ rel = path_resolved.relative_to(home_resolved)
+ except ValueError:
+ return False
+
+ rel_posix = rel.as_posix()
+
+ # Top-level files: match by basename against cfg.top_files.
+ if rel_posix in cfg.top_files:
+ return True
+
+ # Trees: match any file under a tracked tree's src prefix.
+ for tree in cfg.trees:
+ prefix = tree.src.rstrip("/") + "/"
+ if rel_posix == tree.src or rel_posix.startswith(prefix):
+ return True
+
+ # Memory glob: projects//memory/...
+ if cfg.memory_glob:
+ parts = rel.parts
+ if len(parts) >= 3 and parts[0] == "projects" and parts[2] == "memory":
+ return True
+
+ return False
+
+
+def _invoke_snapshot(reason: str) -> int:
+ """Shell out to snapshot-if-changed. Returns child exit code (or 0)."""
+ mirror = SRC / "backup_mirror.py"
+ if not mirror.is_file():
+ print(f"[backup_on_change] missing {mirror}", file=sys.stderr)
+ return 0
+ try:
+ result = subprocess.run(
+ [sys.executable, str(mirror), "snapshot-if-changed",
+ "--reason", reason],
+ capture_output=True,
+ text=True,
+ timeout=60,
+ check=False,
+ )
+ if result.stdout.strip():
+ print(result.stdout.strip(), file=sys.stderr)
+ if result.returncode != 0 and result.stderr.strip():
+ print(result.stderr.strip(), file=sys.stderr)
+ return result.returncode
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ print(f"[backup_on_change] snapshot failed: {exc}", file=sys.stderr)
+ return 0
+
+
+def main() -> int:
+ payload = _load_payload()
+ tool_name = str(payload.get("tool_name") or "unknown")
+
+ touched = _extract_touched_path(payload)
+ if touched is None:
+ return 0
+
+ claude_home = Path(os.path.expanduser("~/.claude"))
+ if not _is_tracked(touched, claude_home):
+ return 0
+
+ reason = f"{tool_name}:{touched.name}"
+ _invoke_snapshot(reason)
+ # Always exit 0: hook failures must not block the user's tool.
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/hooks/quality_on_session_end.py b/hooks/quality_on_session_end.py
index a4a636d450e8eb161af710bd7db2312a9a4524eb..ef3d977489ac02a0b5f5b2f39cd27d7c4ebf8637 100644
--- a/hooks/quality_on_session_end.py
+++ b/hooks/quality_on_session_end.py
@@ -1,223 +1,223 @@
-#!/usr/bin/env python3
-"""
-quality_on_session_end.py -- Stop hook that recomputes quality for the slugs
-this session touched.
-
-Designed for ``~/.claude/settings.json``:
-
- "hooks": {
- "Stop": [
- {
- "hooks": [
- {
- "type": "command",
- "command": "python /hooks/quality_on_session_end.py"
- }
- ]
- }
- ]
- }
-
-Why incremental instead of ``recompute --all``:
-
- - Full recompute walks every installed skill + agent (2,000+ pages) and
- runs four signal extractors per page. That's ~30s on a warm cache and
- dominates the tail of every session.
- - The only signals that *changed* since last session are telemetry
- (we logged new loads) and maybe intake (if the user edited a skill
- file). Every other signal moves on a slower clock.
- - So we compute the set of slugs that showed up in the telemetry event
- stream since the last time this hook ran, and rescore just those.
-
-Always exits 0: a hook that blocks session shutdown is worse than a
-slightly stale quality score.
-"""
-
-from __future__ import annotations
-
-import json
-import os
-import subprocess
-import sys
-from datetime import datetime, timedelta, timezone
-from pathlib import Path
-from typing import Any
-
-
-REPO_ROOT = Path(__file__).resolve().parent.parent
-SRC = REPO_ROOT / "src"
-if str(SRC) not in sys.path:
- sys.path.insert(0, str(SRC))
-
-
-# How far back to look for touched slugs if no marker file exists.
-# Matches ``recent_window_days`` default in ``QualityConfig`` so a
-# freshly-installed system scores every recently-loaded skill on first run.
-_DEFAULT_LOOKBACK_HOURS = 24
-
-# State file: stores the ISO timestamp of the last successful run. Lives
-# under ~/.claude so it persists across repo clones and venv moves.
-_STATE_PATH = Path(os.path.expanduser("~/.claude/skill-quality/.hook-state.json"))
-_EVENTS_PATH = Path(os.path.expanduser("~/.claude/skill-events.jsonl"))
-
-# Upper bound on how many slugs we'll hand to the recompute subcommand in
-# one invocation. Pathological: a user loads 500 distinct skills in one
-# session. We'd rather recompute the top 50 than stall on session-end.
-_MAX_SLUGS_PER_RUN = 50
-
-
-def _load_payload() -> dict[str, Any]:
- try:
- raw = sys.stdin.read()
- if not raw.strip():
- return {}
- data = json.loads(raw)
- return data if isinstance(data, dict) else {}
- except (json.JSONDecodeError, OSError):
- return {}
-
-
-def _read_cutoff() -> datetime:
- """Return the 'since' cutoff for scanning events."""
- if _STATE_PATH.is_file():
- try:
- data = json.loads(_STATE_PATH.read_text(encoding="utf-8"))
- ts = data.get("last_run_at")
- if isinstance(ts, str):
- parsed = datetime.fromisoformat(ts)
- if parsed.tzinfo is None:
- parsed = parsed.replace(tzinfo=timezone.utc)
- return parsed.astimezone(timezone.utc)
- except (json.JSONDecodeError, ValueError, OSError):
- pass
- return datetime.now(timezone.utc) - timedelta(hours=_DEFAULT_LOOKBACK_HOURS)
-
-
-def _write_state(now: datetime) -> None:
- try:
- _STATE_PATH.parent.mkdir(parents=True, exist_ok=True)
- _STATE_PATH.write_text(
- json.dumps({"last_run_at": now.isoformat(timespec="seconds")}),
- encoding="utf-8",
- )
- except OSError as exc:
- print(f"[quality_on_session_end] could not write state: {exc}",
- file=sys.stderr)
-
-
-def _touched_slugs_since(cutoff: datetime, events_path: Path) -> list[str]:
- """Return a deduplicated list of skill slugs that appear after ``cutoff``."""
- if not events_path.is_file():
- return []
- seen: dict[str, None] = {}
- try:
- with events_path.open(encoding="utf-8") as fh:
- for raw in fh:
- line = raw.strip()
- if not line:
- continue
- try:
- obj = json.loads(line)
- except json.JSONDecodeError:
- continue
- if not isinstance(obj, dict):
- continue
- slug = obj.get("skill")
- ts_raw = obj.get("timestamp")
- if not isinstance(slug, str) or not isinstance(ts_raw, str):
- continue
- try:
- parsed = datetime.fromisoformat(ts_raw)
- except ValueError:
- continue
- if parsed.tzinfo is None:
- parsed = parsed.replace(tzinfo=timezone.utc)
- if parsed < cutoff:
- continue
- # Insertion order preserved by dict in Python 3.7+.
- seen.setdefault(slug, None)
- except OSError:
- return []
- return list(seen.keys())[:_MAX_SLUGS_PER_RUN]
-
-
-def _invoke_recompute(slugs: list[str], session_id: str | None = None) -> int:
- if not slugs:
- return 0
- script = SRC / "skill_quality.py"
- if not script.is_file():
- print(f"[quality_on_session_end] missing {script}", file=sys.stderr)
- return 0
- # Propagate session_id via environment so the per-slug
- # skill.score_updated audit rows carry it. Without this the
- # dashboard's per-session timeline drops the middle event in the
- # load -> score_updated -> unload triad.
- env = dict(os.environ)
- if session_id:
- env["CTX_SESSION_ID"] = session_id
- try:
- result = subprocess.run(
- [sys.executable, str(script), "recompute",
- "--slugs", ",".join(slugs)],
- capture_output=True,
- text=True,
- timeout=120,
- check=False,
- env=env,
- )
- if result.stderr.strip():
- print(result.stderr.strip(), file=sys.stderr)
- return result.returncode
- except (OSError, subprocess.TimeoutExpired) as exc:
- print(f"[quality_on_session_end] recompute failed: {exc}",
- file=sys.stderr)
- return 0
-
-
-def main() -> int:
- payload = _load_payload() # consume stdin even if we don't use it
- now = datetime.now(timezone.utc)
- cutoff = _read_cutoff()
- slugs = _touched_slugs_since(cutoff, _EVENTS_PATH)
-
- # Resolve session_id up-front so it can flow into both the
- # recompute subprocess (via CTX_SESSION_ID env) AND the session.ended
- # audit record below. Previously the score_updated rows had no
- # session_id, breaking the dashboard's per-session timeline.
- session_id: str | None = None
- if isinstance(payload, dict):
- session_id = payload.get("session_id") or payload.get("sessionId")
- if not session_id:
- session_id = f"session-{now.strftime('%Y%m%dT%H%M%SZ')}"
-
- _invoke_recompute(slugs, session_id=session_id)
- _write_state(now)
-
- # Unified audit: one line per session boundary + rotate if big.
- # Guarded with try/except because a hook that fails on audit is
- # worse than one that runs without telemetry.
- try:
- # ctx_audit_log lives in src/. Add src/ to path so this hook
- # (which runs out of hooks/) can import it regardless of whether
- # the user is on the editable install or the pip-installed copy.
- _SRC = Path(__file__).parent.parent / "src"
- if str(_SRC) not in sys.path:
- sys.path.insert(0, str(_SRC))
- from ctx_audit_log import log_session_event, rotate_if_needed
-
- # session_id resolved above — reuse it so the audit record
- # agrees with the CTX_SESSION_ID that score_updated rows carry.
- log_session_event(
- "session.ended", session_id, actor="hook",
- meta={"recomputed_slugs": len(slugs), "cutoff": cutoff.isoformat()},
- )
- rotate_if_needed()
- except Exception: # noqa: BLE001 — audit is advisory
- pass
-
- # Always exit 0: hook errors must not stall session shutdown.
- return 0
-
-
-if __name__ == "__main__":
- sys.exit(main())
+#!/usr/bin/env python3
+"""
+quality_on_session_end.py -- Stop hook that recomputes quality for the slugs
+this session touched.
+
+Designed for ``~/.claude/settings.json``:
+
+ "hooks": {
+ "Stop": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "python /hooks/quality_on_session_end.py"
+ }
+ ]
+ }
+ ]
+ }
+
+Why incremental instead of ``recompute --all``:
+
+ - Full recompute walks every installed skill + agent (2,000+ pages) and
+ runs four signal extractors per page. That's ~30s on a warm cache and
+ dominates the tail of every session.
+ - The only signals that *changed* since last session are telemetry
+ (we logged new loads) and maybe intake (if the user edited a skill
+ file). Every other signal moves on a slower clock.
+ - So we compute the set of slugs that showed up in the telemetry event
+ stream since the last time this hook ran, and rescore just those.
+
+Always exits 0: a hook that blocks session shutdown is worse than a
+slightly stale quality score.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from typing import Any
+
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+SRC = REPO_ROOT / "src"
+if str(SRC) not in sys.path:
+ sys.path.insert(0, str(SRC))
+
+
+# How far back to look for touched slugs if no marker file exists.
+# Matches ``recent_window_days`` default in ``QualityConfig`` so a
+# freshly-installed system scores every recently-loaded skill on first run.
+_DEFAULT_LOOKBACK_HOURS = 24
+
+# State file: stores the ISO timestamp of the last successful run. Lives
+# under ~/.claude so it persists across repo clones and venv moves.
+_STATE_PATH = Path(os.path.expanduser("~/.claude/skill-quality/.hook-state.json"))
+_EVENTS_PATH = Path(os.path.expanduser("~/.claude/skill-events.jsonl"))
+
+# Upper bound on how many slugs we'll hand to the recompute subcommand in
+# one invocation. Pathological: a user loads 500 distinct skills in one
+# session. We'd rather recompute the top 50 than stall on session-end.
+_MAX_SLUGS_PER_RUN = 50
+
+
+def _load_payload() -> dict[str, Any]:
+ try:
+ raw = sys.stdin.read()
+ if not raw.strip():
+ return {}
+ data = json.loads(raw)
+ return data if isinstance(data, dict) else {}
+ except (json.JSONDecodeError, OSError):
+ return {}
+
+
+def _read_cutoff() -> datetime:
+ """Return the 'since' cutoff for scanning events."""
+ if _STATE_PATH.is_file():
+ try:
+ data = json.loads(_STATE_PATH.read_text(encoding="utf-8"))
+ ts = data.get("last_run_at")
+ if isinstance(ts, str):
+ parsed = datetime.fromisoformat(ts)
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return parsed.astimezone(timezone.utc)
+ except (json.JSONDecodeError, ValueError, OSError):
+ pass
+ return datetime.now(timezone.utc) - timedelta(hours=_DEFAULT_LOOKBACK_HOURS)
+
+
+def _write_state(now: datetime) -> None:
+ try:
+ _STATE_PATH.parent.mkdir(parents=True, exist_ok=True)
+ _STATE_PATH.write_text(
+ json.dumps({"last_run_at": now.isoformat(timespec="seconds")}),
+ encoding="utf-8",
+ )
+ except OSError as exc:
+ print(f"[quality_on_session_end] could not write state: {exc}",
+ file=sys.stderr)
+
+
+def _touched_slugs_since(cutoff: datetime, events_path: Path) -> list[str]:
+ """Return a deduplicated list of skill slugs that appear after ``cutoff``."""
+ if not events_path.is_file():
+ return []
+ seen: dict[str, None] = {}
+ try:
+ with events_path.open(encoding="utf-8") as fh:
+ for raw in fh:
+ line = raw.strip()
+ if not line:
+ continue
+ try:
+ obj = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if not isinstance(obj, dict):
+ continue
+ slug = obj.get("skill")
+ ts_raw = obj.get("timestamp")
+ if not isinstance(slug, str) or not isinstance(ts_raw, str):
+ continue
+ try:
+ parsed = datetime.fromisoformat(ts_raw)
+ except ValueError:
+ continue
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ if parsed < cutoff:
+ continue
+ # Insertion order preserved by dict in Python 3.7+.
+ seen.setdefault(slug, None)
+ except OSError:
+ return []
+ return list(seen.keys())[:_MAX_SLUGS_PER_RUN]
+
+
+def _invoke_recompute(slugs: list[str], session_id: str | None = None) -> int:
+ if not slugs:
+ return 0
+ script = SRC / "skill_quality.py"
+ if not script.is_file():
+ print(f"[quality_on_session_end] missing {script}", file=sys.stderr)
+ return 0
+ # Propagate session_id via environment so the per-slug
+ # skill.score_updated audit rows carry it. Without this the
+ # dashboard's per-session timeline drops the middle event in the
+ # load -> score_updated -> unload triad.
+ env = dict(os.environ)
+ if session_id:
+ env["CTX_SESSION_ID"] = session_id
+ try:
+ result = subprocess.run(
+ [sys.executable, str(script), "recompute",
+ "--slugs", ",".join(slugs)],
+ capture_output=True,
+ text=True,
+ timeout=120,
+ check=False,
+ env=env,
+ )
+ if result.stderr.strip():
+ print(result.stderr.strip(), file=sys.stderr)
+ return result.returncode
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ print(f"[quality_on_session_end] recompute failed: {exc}",
+ file=sys.stderr)
+ return 0
+
+
+def main() -> int:
+ payload = _load_payload() # consume stdin even if we don't use it
+ now = datetime.now(timezone.utc)
+ cutoff = _read_cutoff()
+ slugs = _touched_slugs_since(cutoff, _EVENTS_PATH)
+
+ # Resolve session_id up-front so it can flow into both the
+ # recompute subprocess (via CTX_SESSION_ID env) AND the session.ended
+ # audit record below. Previously the score_updated rows had no
+ # session_id, breaking the dashboard's per-session timeline.
+ session_id: str | None = None
+ if isinstance(payload, dict):
+ session_id = payload.get("session_id") or payload.get("sessionId")
+ if not session_id:
+ session_id = f"session-{now.strftime('%Y%m%dT%H%M%SZ')}"
+
+ _invoke_recompute(slugs, session_id=session_id)
+ _write_state(now)
+
+ # Unified audit: one line per session boundary + rotate if big.
+ # Guarded with try/except because a hook that fails on audit is
+ # worse than one that runs without telemetry.
+ try:
+ # ctx_audit_log lives in src/. Add src/ to path so this hook
+ # (which runs out of hooks/) can import it regardless of whether
+ # the user is on the editable install or the pip-installed copy.
+ _SRC = Path(__file__).parent.parent / "src"
+ if str(_SRC) not in sys.path:
+ sys.path.insert(0, str(_SRC))
+ from ctx_audit_log import log_session_event, rotate_if_needed
+
+ # session_id resolved above — reuse it so the audit record
+ # agrees with the CTX_SESSION_ID that score_updated rows carry.
+ log_session_event(
+ "session.ended", session_id, actor="hook",
+ meta={"recomputed_slugs": len(slugs), "cutoff": cutoff.isoformat()},
+ )
+ rotate_if_needed()
+ except Exception: # noqa: BLE001 — audit is advisory
+ pass
+
+ # Always exit 0: hook errors must not stall session shutdown.
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/imported-skills/designdotmd/ATTRIBUTION.md b/imported-skills/designdotmd/ATTRIBUTION.md
index 5f51ae8249b1d5cdb9075e7c786bb4c1329c3528..b1a4ce0a833411303cb7a22e93041242e7042a16 100644
--- a/imported-skills/designdotmd/ATTRIBUTION.md
+++ b/imported-skills/designdotmd/ATTRIBUTION.md
@@ -1,121 +1,121 @@
-# designdotmd.directory — Attribution & Usage
-
-This directory mirrors the design-token catalog from
-[designdotmd.directory](https://designdotmd.directory) — a curated set of
-DESIGN.md files describing visual identities (color, typography, spacing,
-component tokens, rationale) that any coding agent can read.
-
-## Provenance
-
-| Field | Value |
-|---|---|
-| Upstream site | https://designdotmd.directory |
-| List API | https://designdotmd.directory/api/designs |
-| Detail API | https://designdotmd.directory/api/designs/{id} |
-| Fetched on | 2026-04-27 |
-| Total designs | 156 |
-| Curated by | [@bidah](https://twitter.com/bidah) (Twitter creator handle from site meta tags); attributed author per design is **Rofi** |
-| License | **No explicit license posted on the site.** Treat as public reference material with upstream attribution. Review before redistributing. |
-
-## What's in here
-
-- `designs/.md` — verbatim copy of each upstream design markdown
- (YAML frontmatter with name + description + design tokens, plus a
- short prose `## Overview` body).
-- `designs/.meta.json` — listing metadata (id, name, author, tags,
- tagline) the upstream API returns for each design but doesn't ship
- inside the markdown itself.
-- `designs-listing.json` — full upstream listing in one file.
-- `MANIFEST.json` — machine-readable catalog generated by
- `build_manifest.py` (slug, name, tagline, author, tags, source path,
- line count). Tags are pulled from the listing API and written into
- the deployed `SKILL.md` because the upstream `.md` doesn't include
- them at the YAML level.
-- `build_manifest.py` — manifest regenerator.
-
-## How to integrate
-
-```bash
-python imported-skills/designdotmd/build_manifest.py # rebuild MANIFEST.json
-python src/import_designdotmd_skills.py --dry-run # preview
-python src/import_designdotmd_skills.py --install # deploy as designdotmd-
-```
-
-The importer:
-- Deploys each design to `~/.claude/skills/designdotmd-/SKILL.md`.
-- Preserves the upstream YAML frontmatter (colors, typography, spacing,
- components, rationale) verbatim.
-- **Injects** a `tags: [...]` line right after `description:` so the
- recommender's tag signal can match design tokens to user queries
- ("dark editorial typography" → `serif` + `dark` + `editorial` tags).
-- Prepends a one-line attribution comment so the upstream URL is
- visible inline in every deployed file.
-
-After install, refresh the wiki + graph:
-
-```bash
-python src/catalog_builder.py
-python src/wiki_batch_entities.py --all
-python -m ctx.core.wiki.wiki_graphify
-```
-
-## Why this set
-
-Most agent skills cover *behavior* (TDD, code review, debugging).
-Designs are different: they're **reference data** the agent reads when
-asked to produce a UI. A query like "build me a dashboard with a calm,
-research-paper feel" should surface `ai-labs`, `clinical`, or
-`paper-white` — visual identities, not coding playbooks.
-
-Adding 156 of these to the graph gives a clean second category of
-recommendations alongside the 1,800+ behavior skills, with no overlap
-risk because none of them describe agent actions — they're token sets
-plus rationale.
-
-## Categorisation (selected)
-
-| Category | Designs |
-|---|---|
-| Editorial / serif | heritage, terracotta, sunset-magazine, broadsheet-01, magazine-rouge, atelier-noir, wine-country |
-| Brutalist / bold | brutalist-office, concrete-lemon, streetwear-block, bauhaus |
-| Technical / dark | terminal, obsidian, graphite, zed-dev, devops-graphite, cyber-matrix |
-| Playful / retro | risograph, neon-arcade, y2k-chrome, candy-shop, pixel-quest, arcade-neon-pop |
-| Minimal | swiss-grid, paper-white, gallery-white, clinical, ai-labs, clinic-sage |
-| Finance | defi-chrome, neobank-mint, wealth-noir |
-| Healthcare | clinic-sage, wellness-coral |
-| Music / fashion | record-sleeve, rave-poster, atelier-noir |
-| Sports / gaming HUD | sports-hud, dungeon-crawl, candy-tap |
-
-The full set spans ~30 visual categories crossed with ~10 industry verticals.
-
-## License caveat
-
-I could not find an explicit license on the site (no LICENSE link,
-no terms page, no robots/about endpoint, no licensing metadata in the
-API response). The site explicitly says "Browse, preview, and install
-visual identities any coding agent can read" — that's a clear
-public-distribution intent for *reading and using*, but not a formal
-permission to redistribute under a known license.
-
-This import treats the corpus as **public reference material with
-upstream attribution preserved inline** (the HTML comment header on
-every deployed file links back to designdotmd.directory). If you plan
-to redistribute this catalog (e.g. ship the wiki tarball publicly),
-contact the upstream creator first to confirm permissions.
-
-## Limitations
-
-- **Frontmatter shape** — the designs use rich YAML (colors, typography,
- spacing, components, rationale) that's idiomatic for design tokens
- but goes beyond the `name` + `description` + `tags` shape Claude Code's
- skill loader requires. Extra fields are tolerated and unused; they
- remain readable when an agent loads the skill.
-- **No body conversion** — the `## Overview` prose body in each upstream
- file is preserved verbatim. The wiki's micro-skill pipeline does
- *not* run on these (they're not behavioral skills with implementation
- steps).
-- **Tag accuracy** — tags come from the upstream listing API and are
- lowercased. They're a sensible starting point but not exhaustive
- (e.g. `paper-white` is tagged `minimal serif reading` — accurate but
- doesn't capture "library", "research", "monograph" connotations).
- The recommender's slug-token + semantic signals fill in the gap.
+# designdotmd.directory — Attribution & Usage
+
+This directory mirrors the design-token catalog from
+[designdotmd.directory](https://designdotmd.directory) — a curated set of
+DESIGN.md files describing visual identities (color, typography, spacing,
+component tokens, rationale) that any coding agent can read.
+
+## Provenance
+
+| Field | Value |
+|---|---|
+| Upstream site | https://designdotmd.directory |
+| List API | https://designdotmd.directory/api/designs |
+| Detail API | https://designdotmd.directory/api/designs/{id} |
+| Fetched on | 2026-04-27 |
+| Total designs | 156 |
+| Curated by | [@bidah](https://twitter.com/bidah) (Twitter creator handle from site meta tags); attributed author per design is **Rofi** |
+| License | **No explicit license posted on the site.** Treat as public reference material with upstream attribution. Review before redistributing. |
+
+## What's in here
+
+- `designs/.md` — verbatim copy of each upstream design markdown
+ (YAML frontmatter with name + description + design tokens, plus a
+ short prose `## Overview` body).
+- `designs/.meta.json` — listing metadata (id, name, author, tags,
+ tagline) the upstream API returns for each design but doesn't ship
+ inside the markdown itself.
+- `designs-listing.json` — full upstream listing in one file.
+- `MANIFEST.json` — machine-readable catalog generated by
+ `build_manifest.py` (slug, name, tagline, author, tags, source path,
+ line count). Tags are pulled from the listing API and written into
+ the deployed `SKILL.md` because the upstream `.md` doesn't include
+ them at the YAML level.
+- `build_manifest.py` — manifest regenerator.
+
+## How to integrate
+
+```bash
+python imported-skills/designdotmd/build_manifest.py # rebuild MANIFEST.json
+python src/import_designdotmd_skills.py --dry-run # preview
+python src/import_designdotmd_skills.py --install # deploy as designdotmd-
+```
+
+The importer:
+- Deploys each design to `~/.claude/skills/designdotmd-/SKILL.md`.
+- Preserves the upstream YAML frontmatter (colors, typography, spacing,
+ components, rationale) verbatim.
+- **Injects** a `tags: [...]` line right after `description:` so the
+ recommender's tag signal can match design tokens to user queries
+ ("dark editorial typography" → `serif` + `dark` + `editorial` tags).
+- Prepends a one-line attribution comment so the upstream URL is
+ visible inline in every deployed file.
+
+After install, refresh the wiki + graph:
+
+```bash
+python src/catalog_builder.py
+python src/wiki_batch_entities.py --all
+python -m ctx.core.wiki.wiki_graphify
+```
+
+## Why this set
+
+Most agent skills cover *behavior* (TDD, code review, debugging).
+Designs are different: they're **reference data** the agent reads when
+asked to produce a UI. A query like "build me a dashboard with a calm,
+research-paper feel" should surface `ai-labs`, `clinical`, or
+`paper-white` — visual identities, not coding playbooks.
+
+Adding 156 of these to the graph gives a clean second category of
+recommendations alongside the 1,800+ behavior skills, with no overlap
+risk because none of them describe agent actions — they're token sets
+plus rationale.
+
+## Categorisation (selected)
+
+| Category | Designs |
+|---|---|
+| Editorial / serif | heritage, terracotta, sunset-magazine, broadsheet-01, magazine-rouge, atelier-noir, wine-country |
+| Brutalist / bold | brutalist-office, concrete-lemon, streetwear-block, bauhaus |
+| Technical / dark | terminal, obsidian, graphite, zed-dev, devops-graphite, cyber-matrix |
+| Playful / retro | risograph, neon-arcade, y2k-chrome, candy-shop, pixel-quest, arcade-neon-pop |
+| Minimal | swiss-grid, paper-white, gallery-white, clinical, ai-labs, clinic-sage |
+| Finance | defi-chrome, neobank-mint, wealth-noir |
+| Healthcare | clinic-sage, wellness-coral |
+| Music / fashion | record-sleeve, rave-poster, atelier-noir |
+| Sports / gaming HUD | sports-hud, dungeon-crawl, candy-tap |
+
+The full set spans ~30 visual categories crossed with ~10 industry verticals.
+
+## License caveat
+
+I could not find an explicit license on the site (no LICENSE link,
+no terms page, no robots/about endpoint, no licensing metadata in the
+API response). The site explicitly says "Browse, preview, and install
+visual identities any coding agent can read" — that's a clear
+public-distribution intent for *reading and using*, but not a formal
+permission to redistribute under a known license.
+
+This import treats the corpus as **public reference material with
+upstream attribution preserved inline** (the HTML comment header on
+every deployed file links back to designdotmd.directory). If you plan
+to redistribute this catalog (e.g. ship the wiki tarball publicly),
+contact the upstream creator first to confirm permissions.
+
+## Limitations
+
+- **Frontmatter shape** — the designs use rich YAML (colors, typography,
+ spacing, components, rationale) that's idiomatic for design tokens
+ but goes beyond the `name` + `description` + `tags` shape Claude Code's
+ skill loader requires. Extra fields are tolerated and unused; they
+ remain readable when an agent loads the skill.
+- **No body conversion** — the `## Overview` prose body in each upstream
+ file is preserved verbatim. The wiki's micro-skill pipeline does
+ *not* run on these (they're not behavioral skills with implementation
+ steps).
+- **Tag accuracy** — tags come from the upstream listing API and are
+ lowercased. They're a sensible starting point but not exhaustive
+ (e.g. `paper-white` is tagged `minimal serif reading` — accurate but
+ doesn't capture "library", "research", "monograph" connotations).
+ The recommender's slug-token + semantic signals fill in the gap.
diff --git a/imported-skills/designdotmd/build_manifest.py b/imported-skills/designdotmd/build_manifest.py
index d3e0a4f277e16ca15c9974fa7a29e57cb32d901d..fd04b0f58ad35f74a84750f68a7c5bd9a5e703c4 100644
--- a/imported-skills/designdotmd/build_manifest.py
+++ b/imported-skills/designdotmd/build_manifest.py
@@ -1,60 +1,60 @@
-#!/usr/bin/env python3
-"""Generate MANIFEST.json for the imported designdotmd.directory set.
-
-Each entry pairs a markdown file under ``designs/.md`` (fetched
-directly from the upstream API) with the listing-API metadata
-(``id``, ``name``, ``author``, ``tags``, ``tagline``).
-"""
-
-from __future__ import annotations
-
-import datetime
-import json
-from pathlib import Path
-
-ROOT = Path(__file__).parent
-DESIGNS_DIR = ROOT / "designs"
-LISTING_PATH = ROOT / "designs-listing.json"
-UPSTREAM = "https://designdotmd.directory"
-UPSTREAM_API = f"{UPSTREAM}/api/designs"
-
-
-def build() -> dict:
- listing = json.loads(LISTING_PATH.read_text(encoding="utf-8"))
- entries: list[dict] = []
- for d in listing:
- slug = d["id"]
- md_path = DESIGNS_DIR / f"{slug}.md"
- if not md_path.is_file():
- continue
- text = md_path.read_text(encoding="utf-8")
- entries.append({
- "name": d.get("name") or slug,
- "tagline": d.get("tagline", "").strip(),
- "author": d.get("author", "").strip(),
- "tags": [str(t).strip().lower() for t in d.get("tags", []) if str(t).strip()],
- "slug": slug,
- "source_path": (md_path.relative_to(ROOT)).as_posix(),
- "lines": len(text.splitlines()),
- })
- entries.sort(key=lambda e: e["slug"])
- return {
- "upstream": UPSTREAM,
- "upstream_api": UPSTREAM_API,
- "fetched_on": datetime.date.today().isoformat(),
- "license": "unknown (see ATTRIBUTION.md)",
- "namespace": "designdotmd",
- "total": len(entries),
- "entries": entries,
- }
-
-
-def main() -> None:
- manifest = build()
- out = ROOT / "MANIFEST.json"
- out.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
- print(f"Manifest written: {manifest['total']} designs")
-
-
-if __name__ == "__main__":
- main()
+#!/usr/bin/env python3
+"""Generate MANIFEST.json for the imported designdotmd.directory set.
+
+Each entry pairs a markdown file under ``designs/.md`` (fetched
+directly from the upstream API) with the listing-API metadata
+(``id``, ``name``, ``author``, ``tags``, ``tagline``).
+"""
+
+from __future__ import annotations
+
+import datetime
+import json
+from pathlib import Path
+
+ROOT = Path(__file__).parent
+DESIGNS_DIR = ROOT / "designs"
+LISTING_PATH = ROOT / "designs-listing.json"
+UPSTREAM = "https://designdotmd.directory"
+UPSTREAM_API = f"{UPSTREAM}/api/designs"
+
+
+def build() -> dict:
+ listing = json.loads(LISTING_PATH.read_text(encoding="utf-8"))
+ entries: list[dict] = []
+ for d in listing:
+ slug = d["id"]
+ md_path = DESIGNS_DIR / f"{slug}.md"
+ if not md_path.is_file():
+ continue
+ text = md_path.read_text(encoding="utf-8")
+ entries.append({
+ "name": d.get("name") or slug,
+ "tagline": d.get("tagline", "").strip(),
+ "author": d.get("author", "").strip(),
+ "tags": [str(t).strip().lower() for t in d.get("tags", []) if str(t).strip()],
+ "slug": slug,
+ "source_path": (md_path.relative_to(ROOT)).as_posix(),
+ "lines": len(text.splitlines()),
+ })
+ entries.sort(key=lambda e: e["slug"])
+ return {
+ "upstream": UPSTREAM,
+ "upstream_api": UPSTREAM_API,
+ "fetched_on": datetime.date.today().isoformat(),
+ "license": "unknown (see ATTRIBUTION.md)",
+ "namespace": "designdotmd",
+ "total": len(entries),
+ "entries": entries,
+ }
+
+
+def main() -> None:
+ manifest = build()
+ out = ROOT / "MANIFEST.json"
+ out.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
+ print(f"Manifest written: {manifest['total']} designs")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/imported-skills/mattpocock/ATTRIBUTION.md b/imported-skills/mattpocock/ATTRIBUTION.md
index 655c25a172a250869735f5955968fc1f882348b3..e4315e22b03f148d47d977081b0585cc06475832 100644
--- a/imported-skills/mattpocock/ATTRIBUTION.md
+++ b/imported-skills/mattpocock/ATTRIBUTION.md
@@ -1,103 +1,103 @@
-# Mattpocock Skills Import — Attribution & Usage
-
-This directory mirrors Matt Pocock's personal `.claude/` skill set — opinionated
-agent skills covering TDD, domain modelling, codebase architecture review,
-github triage, and meta-workflows for working with Claude Code.
-
-## Provenance
-
-| Field | Value |
-|---|---|
-| Upstream repo | https://github.com/mattpocock/skills |
-| Revision | `90ea8eec03d4ae8f43427aaf6fe4722653561a42` |
-| Revision date | 2026-04-26 |
-| Upstream license | MIT (see `LICENSE`) |
-| Imported on | 2026-04-27 |
-| Skill count | 21 |
-
-## What's in here
-
-Each top-level directory is one skill, with `SKILL.md` as the entry point and
-optional supporting `.md` / `.sh` files alongside it (e.g. `tdd/deep-modules.md`,
-`domain-model/ADR-FORMAT.md`, `git-guardrails-claude-code/scripts/block-dangerous-git.sh`).
-
-| Skill | Purpose |
-|---|---|
-| `tdd` | Red-green-refactor TDD discipline (with deep-modules / mocking / refactoring sidecars) |
-| `qa` | Interactive QA conversation that files GitHub issues using project domain language |
-| `caveman` | Ultra-compressed communication mode (~75% token reduction) |
-| `domain-model` | Stress-test plans against existing domain model + ADRs (with `ADR-FORMAT.md` + `CONTEXT-FORMAT.md`) |
-| `ubiquitous-language` | DDD-style shared vocabulary discipline |
-| `design-an-interface` | Generate multiple radically different API designs via parallel sub-agents |
-| `improve-codebase-architecture` | Architecture review playbook (with `DEEPENING.md`, `INTERFACE-DESIGN.md`, `LANGUAGE.md` sidecars) |
-| `github-triage` | Triage GitHub issues with agent-brief + out-of-scope guardrails |
-| `triage-issue` | Single-issue triage workflow |
-| `to-issues` | Convert plans/notes into well-formed issues |
-| `to-prd` | Convert sketches into a product requirements document |
-| `request-refactor-plan` | Plan a refactor before touching code |
-| `migrate-to-shoehorn` | Migration playbook to the `shoehorn` library |
-| `setup-pre-commit` | Pre-commit hook bootstrap |
-| `scaffold-exercises` | Scaffold programming exercises |
-| `git-guardrails-claude-code` | Block dangerous git ops in Claude Code (with hook script) |
-| `obsidian-vault` | Obsidian vault management workflow |
-| `edit-article` | Editing pass for article drafts |
-| `grill-me` | Adversarial questioning to stress-test a plan |
-| `write-a-skill` | Meta: how to write a skill |
-| `zoom-out` | Force a higher-altitude review of current work |
-
-## License compliance
-
-Per the MIT license:
-- Upstream `LICENSE` text is preserved alongside the imported files.
-- Files are imported verbatim. The deployed copies (under `~/.claude/skills/`) prepend
- an HTML-comment attribution header before the original `---` frontmatter so
- provenance is visible inline; the original content below is unmodified.
-
-## How to integrate
-
-Skills are staged in this directory and **not** deployed to `~/.claude/skills/`
-until you run the importer:
-
-```bash
-python imported-skills/mattpocock/build_manifest.py # rebuild MANIFEST.json
-python src/import_mattpocock_skills.py --dry-run # preview
-python src/import_mattpocock_skills.py --install # deploy as mattpocock-
-```
-
-Each skill lands as `~/.claude/skills/mattpocock-/` with all its support
-files copied alongside `SKILL.md`. Directory namespacing prevents collisions
-with same-named skills already in the wiki (e.g. existing `tdd-orchestrator`
-agent + `python-testing` skill coexist with `mattpocock-tdd`).
-
-After install, refresh the wiki + graph:
-
-```bash
-python src/catalog_builder.py
-python src/wiki_batch_entities.py --all
-python -m ctx.core.wiki.wiki_graphify
-```
-
-## Why this set
-
-mattpocock's skills are short, opinionated, and prose-style — closer to
-checklists or playbooks than reference manuals. They complement the larger
-catalogue (which leans dense + comprehensive) by providing crisp,
-single-purpose workflows for everyday engineering tasks.
-
-The `tdd`, `domain-model`, `ubiquitous-language`, and
-`improve-codebase-architecture` set in particular form a cohesive DDD-leaning
-toolkit. The `caveman`, `grill-me`, `zoom-out` set are useful behavioural
-modes for steering a Claude Code session.
-
-## Limitations
-
-- **Frontmatter format** — uses YAML frontmatter with `name:` + `description:`;
- some entries use `disable-model-invocation: true` (Claude Code reads this).
- The importer preserves these fields as-is.
-- **Tool assumptions** — `git-guardrails-claude-code` ships a `block-dangerous-git.sh`
- hook that expects POSIX `bash` on PATH; on Windows it requires Git-Bash or
- WSL. The hook is copied but not wired into your Claude Code settings — wire
- manually if you want it active.
-- **Opinionated** — these reflect one engineer's workflow. Treat them as
- starting points; nothing here is universally correct (e.g. `grill-me`'s
- adversarial style isn't right for every team).
+# Mattpocock Skills Import — Attribution & Usage
+
+This directory mirrors Matt Pocock's personal `.claude/` skill set — opinionated
+agent skills covering TDD, domain modelling, codebase architecture review,
+github triage, and meta-workflows for working with Claude Code.
+
+## Provenance
+
+| Field | Value |
+|---|---|
+| Upstream repo | https://github.com/mattpocock/skills |
+| Revision | `90ea8eec03d4ae8f43427aaf6fe4722653561a42` |
+| Revision date | 2026-04-26 |
+| Upstream license | MIT (see `LICENSE`) |
+| Imported on | 2026-04-27 |
+| Skill count | 21 |
+
+## What's in here
+
+Each top-level directory is one skill, with `SKILL.md` as the entry point and
+optional supporting `.md` / `.sh` files alongside it (e.g. `tdd/deep-modules.md`,
+`domain-model/ADR-FORMAT.md`, `git-guardrails-claude-code/scripts/block-dangerous-git.sh`).
+
+| Skill | Purpose |
+|---|---|
+| `tdd` | Red-green-refactor TDD discipline (with deep-modules / mocking / refactoring sidecars) |
+| `qa` | Interactive QA conversation that files GitHub issues using project domain language |
+| `caveman` | Ultra-compressed communication mode (~75% token reduction) |
+| `domain-model` | Stress-test plans against existing domain model + ADRs (with `ADR-FORMAT.md` + `CONTEXT-FORMAT.md`) |
+| `ubiquitous-language` | DDD-style shared vocabulary discipline |
+| `design-an-interface` | Generate multiple radically different API designs via parallel sub-agents |
+| `improve-codebase-architecture` | Architecture review playbook (with `DEEPENING.md`, `INTERFACE-DESIGN.md`, `LANGUAGE.md` sidecars) |
+| `github-triage` | Triage GitHub issues with agent-brief + out-of-scope guardrails |
+| `triage-issue` | Single-issue triage workflow |
+| `to-issues` | Convert plans/notes into well-formed issues |
+| `to-prd` | Convert sketches into a product requirements document |
+| `request-refactor-plan` | Plan a refactor before touching code |
+| `migrate-to-shoehorn` | Migration playbook to the `shoehorn` library |
+| `setup-pre-commit` | Pre-commit hook bootstrap |
+| `scaffold-exercises` | Scaffold programming exercises |
+| `git-guardrails-claude-code` | Block dangerous git ops in Claude Code (with hook script) |
+| `obsidian-vault` | Obsidian vault management workflow |
+| `edit-article` | Editing pass for article drafts |
+| `grill-me` | Adversarial questioning to stress-test a plan |
+| `write-a-skill` | Meta: how to write a skill |
+| `zoom-out` | Force a higher-altitude review of current work |
+
+## License compliance
+
+Per the MIT license:
+- Upstream `LICENSE` text is preserved alongside the imported files.
+- Files are imported verbatim. The deployed copies (under `~/.claude/skills/`) prepend
+ an HTML-comment attribution header before the original `---` frontmatter so
+ provenance is visible inline; the original content below is unmodified.
+
+## How to integrate
+
+Skills are staged in this directory and **not** deployed to `~/.claude/skills/`
+until you run the importer:
+
+```bash
+python imported-skills/mattpocock/build_manifest.py # rebuild MANIFEST.json
+python src/import_mattpocock_skills.py --dry-run # preview
+python src/import_mattpocock_skills.py --install # deploy as mattpocock-
+```
+
+Each skill lands as `~/.claude/skills/mattpocock-/` with all its support
+files copied alongside `SKILL.md`. Directory namespacing prevents collisions
+with same-named skills already in the wiki (e.g. existing `tdd-orchestrator`
+agent + `python-testing` skill coexist with `mattpocock-tdd`).
+
+After install, refresh the wiki + graph:
+
+```bash
+python src/catalog_builder.py
+python src/wiki_batch_entities.py --all
+python -m ctx.core.wiki.wiki_graphify
+```
+
+## Why this set
+
+mattpocock's skills are short, opinionated, and prose-style — closer to
+checklists or playbooks than reference manuals. They complement the larger
+catalogue (which leans dense + comprehensive) by providing crisp,
+single-purpose workflows for everyday engineering tasks.
+
+The `tdd`, `domain-model`, `ubiquitous-language`, and
+`improve-codebase-architecture` set in particular form a cohesive DDD-leaning
+toolkit. The `caveman`, `grill-me`, `zoom-out` set are useful behavioural
+modes for steering a Claude Code session.
+
+## Limitations
+
+- **Frontmatter format** — uses YAML frontmatter with `name:` + `description:`;
+ some entries use `disable-model-invocation: true` (Claude Code reads this).
+ The importer preserves these fields as-is.
+- **Tool assumptions** — `git-guardrails-claude-code` ships a `block-dangerous-git.sh`
+ hook that expects POSIX `bash` on PATH; on Windows it requires Git-Bash or
+ WSL. The hook is copied but not wired into your Claude Code settings — wire
+ manually if you want it active.
+- **Opinionated** — these reflect one engineer's workflow. Treat them as
+ starting points; nothing here is universally correct (e.g. `grill-me`'s
+ adversarial style isn't right for every team).
diff --git a/imported-skills/mattpocock/build_manifest.py b/imported-skills/mattpocock/build_manifest.py
index d08eac798147687b0f5f5e3908bd3c8c2db6ef14..75e07baa883fd38c2884b3ea679213043a38ed47 100644
--- a/imported-skills/mattpocock/build_manifest.py
+++ b/imported-skills/mattpocock/build_manifest.py
@@ -1,98 +1,98 @@
-#!/usr/bin/env python3
-"""Generate MANIFEST.json for the imported mattpocock/skills set.
-
-Each top-level directory under imported-skills/mattpocock/ is one skill.
-SKILL.md is the entry point; sibling .md/.sh files travel with the skill
-and are deployed into the same target directory.
-"""
-
-from __future__ import annotations
-
-import json
-import re
-import subprocess
-from pathlib import Path
-
-ROOT = Path(__file__).parent
-FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL)
-UPSTREAM = "https://github.com/mattpocock/skills"
-LICENSE = "MIT"
-
-
-def parse_frontmatter(text: str) -> dict[str, str]:
- m = FRONTMATTER_RE.match(text)
- if not m:
- return {}
- out: dict[str, str] = {}
- pending_key: str | None = None
- for raw in m.group(1).splitlines():
- if pending_key and raw.startswith((" ", "\t")):
- out[pending_key] = (out[pending_key] + " " + raw.strip()).strip()
- continue
- pending_key = None
- if ":" not in raw:
- continue
- k, _, v = raw.partition(":")
- v = v.strip()
- if v in {"", ">", "|"}:
- pending_key = k.strip()
- out[pending_key] = ""
- else:
- out[k.strip()] = v.strip('"').strip("'")
- return out
-
-
-def support_files(skill_dir: Path) -> list[str]:
- out: list[str] = []
- for p in sorted(skill_dir.rglob("*")):
- if not p.is_file() or p.name == "SKILL.md":
- continue
- out.append(p.relative_to(skill_dir).as_posix())
- return out
-
-
-def upstream_revision() -> str:
- try:
- return subprocess.check_output(
- ["git", "-C", str(ROOT), "rev-parse", "HEAD"],
- text=True,
- ).strip()
- except Exception:
- return "unknown"
-
-
-def build() -> dict:
- entries: list[dict] = []
- for skill_dir in sorted(p for p in ROOT.iterdir() if p.is_dir() and (p / "SKILL.md").exists()):
- skill_md = skill_dir / "SKILL.md"
- text = skill_md.read_text(encoding="utf-8")
- fm = parse_frontmatter(text)
- slug = skill_dir.name
- entries.append({
- "name": fm.get("name", slug),
- "description": fm.get("description", "").strip(),
- "slug": slug,
- "source_path": (skill_dir.relative_to(ROOT) / "SKILL.md").as_posix(),
- "support_files": support_files(skill_dir),
- "lines": len(text.splitlines()),
- })
- rev = upstream_revision()
- return {
- "upstream": UPSTREAM,
- "upstream_revision": rev,
- "license": LICENSE,
- "namespace": "mattpocock",
- "total": len(entries),
- "entries": entries,
- }
-
-
-def main() -> None:
- manifest = build()
- out = ROOT / "MANIFEST.json"
- out.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
- print(f"Manifest written: {manifest['total']} skills @ {manifest['upstream_revision'][:12]}")
-
-
-if __name__ == "__main__":
- main()
+#!/usr/bin/env python3
+"""Generate MANIFEST.json for the imported mattpocock/skills set.
+
+Each top-level directory under imported-skills/mattpocock/ is one skill.
+SKILL.md is the entry point; sibling .md/.sh files travel with the skill
+and are deployed into the same target directory.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import subprocess
+from pathlib import Path
+
+ROOT = Path(__file__).parent
+FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL)
+UPSTREAM = "https://github.com/mattpocock/skills"
+LICENSE = "MIT"
+
+
+def parse_frontmatter(text: str) -> dict[str, str]:
+ m = FRONTMATTER_RE.match(text)
+ if not m:
+ return {}
+ out: dict[str, str] = {}
+ pending_key: str | None = None
+ for raw in m.group(1).splitlines():
+ if pending_key and raw.startswith((" ", "\t")):
+ out[pending_key] = (out[pending_key] + " " + raw.strip()).strip()
+ continue
+ pending_key = None
+ if ":" not in raw:
+ continue
+ k, _, v = raw.partition(":")
+ v = v.strip()
+ if v in {"", ">", "|"}:
+ pending_key = k.strip()
+ out[pending_key] = ""
+ else:
+ out[k.strip()] = v.strip('"').strip("'")
+ return out
+
+
+def support_files(skill_dir: Path) -> list[str]:
+ out: list[str] = []
+ for p in sorted(skill_dir.rglob("*")):
+ if not p.is_file() or p.name == "SKILL.md":
+ continue
+ out.append(p.relative_to(skill_dir).as_posix())
+ return out
+
+
+def upstream_revision() -> str:
+ try:
+ return subprocess.check_output(
+ ["git", "-C", str(ROOT), "rev-parse", "HEAD"],
+ text=True,
+ ).strip()
+ except Exception:
+ return "unknown"
+
+
+def build() -> dict:
+ entries: list[dict] = []
+ for skill_dir in sorted(p for p in ROOT.iterdir() if p.is_dir() and (p / "SKILL.md").exists()):
+ skill_md = skill_dir / "SKILL.md"
+ text = skill_md.read_text(encoding="utf-8")
+ fm = parse_frontmatter(text)
+ slug = skill_dir.name
+ entries.append({
+ "name": fm.get("name", slug),
+ "description": fm.get("description", "").strip(),
+ "slug": slug,
+ "source_path": (skill_dir.relative_to(ROOT) / "SKILL.md").as_posix(),
+ "support_files": support_files(skill_dir),
+ "lines": len(text.splitlines()),
+ })
+ rev = upstream_revision()
+ return {
+ "upstream": UPSTREAM,
+ "upstream_revision": rev,
+ "license": LICENSE,
+ "namespace": "mattpocock",
+ "total": len(entries),
+ "entries": entries,
+ }
+
+
+def main() -> None:
+ manifest = build()
+ out = ROOT / "MANIFEST.json"
+ out.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
+ print(f"Manifest written: {manifest['total']} skills @ {manifest['upstream_revision'][:12]}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/imported-skills/strix/ATTRIBUTION.md b/imported-skills/strix/ATTRIBUTION.md
index 10d1820dbcc7090944afba934940e67a3157827a..4351c705177a42c64b8d0498f85ec429ea09813c 100644
--- a/imported-skills/strix/ATTRIBUTION.md
+++ b/imported-skills/strix/ATTRIBUTION.md
@@ -1,97 +1,97 @@
-# Strix Skill Import — Attribution & Usage
-
-This directory contains security-testing skills and agent-architecture patterns
-sourced from [Strix](https://github.com/usestrix/strix), an open-source
-multi-agent cybersecurity penetration testing tool.
-
-## Provenance
-
-| Field | Value |
-|---|---|
-| Upstream repo | https://github.com/usestrix/strix |
-| Revision | `15c95718e600897a2a532a613a1c8fa6b712b144` |
-| Revision date | 2026-04-13 |
-| Upstream license | Apache License 2.0 (see `LICENSE`) |
-| Imported on | 2026-04-17 |
-
-## What's in here
-
-- `skills/` — **38 upstream skill markdown files** copied verbatim, organized in
- their original category tree (vulnerabilities, tooling, frameworks, etc.).
-- `agent-patterns/` — **5 agent-architecture notes** distilled from the Strix
- codebase (orchestrator/worker, skill-injection, shared-wiki-memory,
- sandboxed-tool-runtime, scan-mode-as-skill). These are original
- documentation, not copies — they describe reusable patterns observed in the
- Strix architecture.
-- `MANIFEST.json` — machine-readable index with name, description, category,
- and line count for every entry.
-- `build_manifest.py` — regenerator for `MANIFEST.json`.
-- `LICENSE` — Apache 2.0 license text from the upstream repo.
-
-## License compliance
-
-Per Apache-2.0 §4:
-- Upstream `LICENSE` is preserved alongside the imported files.
-- No `NOTICE` file exists in upstream — none required to reproduce.
-- Files have not been modified. Any downstream modification should add a
- prominent notice describing the change, per §4(b).
-
-## Why these were imported
-
-Strix's skill library is one of the highest-quality open catalogues of
-pentesting knowledge available as structured markdown with YAML frontmatter.
-Its format is **directly compatible** with this project's wiki/knowledge-graph
-ingestion pipeline, which already consumes markdown-with-frontmatter for
-skills and agents.
-
-The agent-patterns notes capture *design* insights — how Strix structures a
-multi-agent security runtime — that apply well beyond security:
-orchestrator/worker decomposition, skill injection, shared wiki memory,
-sandboxed tool execution, and scan-mode-as-skill are general multi-agent
-architecture patterns.
-
-## How to integrate
-
-These files are **staged** in the repo but not yet deployed to
-`~/.claude/skills/`. Two ways to consume them:
-
-### Option A — Feed them to the knowledge graph directly
-
-Use the wiki/graph builders with `--extra-dirs` to include this tree in the
-scan without installing the skills globally. Requires a minor patch to
-`catalog_builder.py` if not already supported.
-
-### Option B — Install as global skills
-
-Run `python src/import_strix_skills.py --install` (see that script for
-options). It creates one directory per Strix skill under `~/.claude/skills/`
-with the naming convention `strix--/SKILL.md` and prepends an
-attribution header to each file so provenance stays visible inline.
-
-## Which skills are highest value for general use
-
-Not every Strix skill applies outside security testing. These generalise:
-
-| Skill | Why it's broadly useful |
-|---|---|
-| `coordination/root_agent` | Multi-agent orchestration template — read first if designing any agent swarm |
-| `coordination/source_aware_whitebox` | White-box coordination pattern applicable to any code-review agent |
-| `scan_modes/{quick,standard,deep}` | Template for tiered operational modes |
-| `custom/source_aware_sast` | Concrete SAST playbook — semgrep + ast-grep + gitleaks + trivy |
-| `tooling/semgrep` | Semgrep playbook — universally useful for code review |
-| `tooling/nmap` | Network recon — infra/ops workflows |
-| All `agent-patterns/*` | Pure architecture patterns — 100% domain-agnostic |
-
-Security-specific skills (XSS, SQLi, IDOR, etc.) remain valuable for any
-project that touches web application code review.
-
-## Limitations
-
-- **Skills only, not the runtime** — Strix's agent runtime (the actual
- Python engine, Docker sandbox, tool-server) is not imported. Those
- components are design-referenced in `agent-patterns/` but not copied.
-- **No fine-tuning or prompts-as-code** — these are human-readable skill
- documents, not prompt-chains or LangChain templates.
-- **Source-aware tooling assumed to exist** — SAST skills assume `semgrep`,
- `ast-grep`, `gitleaks`, `trufflehog`, and `trivy` are installed on the
- agent's runtime path.
+# Strix Skill Import — Attribution & Usage
+
+This directory contains security-testing skills and agent-architecture patterns
+sourced from [Strix](https://github.com/usestrix/strix), an open-source
+multi-agent cybersecurity penetration testing tool.
+
+## Provenance
+
+| Field | Value |
+|---|---|
+| Upstream repo | https://github.com/usestrix/strix |
+| Revision | `15c95718e600897a2a532a613a1c8fa6b712b144` |
+| Revision date | 2026-04-13 |
+| Upstream license | Apache License 2.0 (see `LICENSE`) |
+| Imported on | 2026-04-17 |
+
+## What's in here
+
+- `skills/` — **38 upstream skill markdown files** copied verbatim, organized in
+ their original category tree (vulnerabilities, tooling, frameworks, etc.).
+- `agent-patterns/` — **5 agent-architecture notes** distilled from the Strix
+ codebase (orchestrator/worker, skill-injection, shared-wiki-memory,
+ sandboxed-tool-runtime, scan-mode-as-skill). These are original
+ documentation, not copies — they describe reusable patterns observed in the
+ Strix architecture.
+- `MANIFEST.json` — machine-readable index with name, description, category,
+ and line count for every entry.
+- `build_manifest.py` — regenerator for `MANIFEST.json`.
+- `LICENSE` — Apache 2.0 license text from the upstream repo.
+
+## License compliance
+
+Per Apache-2.0 §4:
+- Upstream `LICENSE` is preserved alongside the imported files.
+- No `NOTICE` file exists in upstream — none required to reproduce.
+- Files have not been modified. Any downstream modification should add a
+ prominent notice describing the change, per §4(b).
+
+## Why these were imported
+
+Strix's skill library is one of the highest-quality open catalogues of
+pentesting knowledge available as structured markdown with YAML frontmatter.
+Its format is **directly compatible** with this project's wiki/knowledge-graph
+ingestion pipeline, which already consumes markdown-with-frontmatter for
+skills and agents.
+
+The agent-patterns notes capture *design* insights — how Strix structures a
+multi-agent security runtime — that apply well beyond security:
+orchestrator/worker decomposition, skill injection, shared wiki memory,
+sandboxed tool execution, and scan-mode-as-skill are general multi-agent
+architecture patterns.
+
+## How to integrate
+
+These files are **staged** in the repo but not yet deployed to
+`~/.claude/skills/`. Two ways to consume them:
+
+### Option A — Feed them to the knowledge graph directly
+
+Use the wiki/graph builders with `--extra-dirs` to include this tree in the
+scan without installing the skills globally. Requires a minor patch to
+`catalog_builder.py` if not already supported.
+
+### Option B — Install as global skills
+
+Run `python src/import_strix_skills.py --install` (see that script for
+options). It creates one directory per Strix skill under `~/.claude/skills/`
+with the naming convention `strix--/SKILL.md` and prepends an
+attribution header to each file so provenance stays visible inline.
+
+## Which skills are highest value for general use
+
+Not every Strix skill applies outside security testing. These generalise:
+
+| Skill | Why it's broadly useful |
+|---|---|
+| `coordination/root_agent` | Multi-agent orchestration template — read first if designing any agent swarm |
+| `coordination/source_aware_whitebox` | White-box coordination pattern applicable to any code-review agent |
+| `scan_modes/{quick,standard,deep}` | Template for tiered operational modes |
+| `custom/source_aware_sast` | Concrete SAST playbook — semgrep + ast-grep + gitleaks + trivy |
+| `tooling/semgrep` | Semgrep playbook — universally useful for code review |
+| `tooling/nmap` | Network recon — infra/ops workflows |
+| All `agent-patterns/*` | Pure architecture patterns — 100% domain-agnostic |
+
+Security-specific skills (XSS, SQLi, IDOR, etc.) remain valuable for any
+project that touches web application code review.
+
+## Limitations
+
+- **Skills only, not the runtime** — Strix's agent runtime (the actual
+ Python engine, Docker sandbox, tool-server) is not imported. Those
+ components are design-referenced in `agent-patterns/` but not copied.
+- **No fine-tuning or prompts-as-code** — these are human-readable skill
+ documents, not prompt-chains or LangChain templates.
+- **Source-aware tooling assumed to exist** — SAST skills assume `semgrep`,
+ `ast-grep`, `gitleaks`, `trufflehog`, and `trivy` are installed on the
+ agent's runtime path.
diff --git a/imported-skills/strix/agent-patterns/orchestrator-worker-pattern.md b/imported-skills/strix/agent-patterns/orchestrator-worker-pattern.md
index b96a07d790e360857e7bcd013a72297592730d84..070c6a9944fd93af34158f0fd28941df23843373 100644
--- a/imported-skills/strix/agent-patterns/orchestrator-worker-pattern.md
+++ b/imported-skills/strix/agent-patterns/orchestrator-worker-pattern.md
@@ -1,54 +1,54 @@
----
-name: orchestrator-worker-pattern
-description: Hierarchical agent pattern — a root orchestrator decomposes work and spawns specialized workers with focused context
-source: Distilled from Strix (https://github.com/usestrix/strix, Apache-2.0) — rev 15c95718
-category: agent-architecture
----
-
-# Orchestrator/Worker Agent Pattern
-
-The root agent owns scope decomposition and aggregation. Specialized workers own narrow, parallelizable tasks. This pattern is what keeps multi-agent systems from drowning in context.
-
-## Roles
-
-**Root / Orchestrator**
-- Decomposes the target into discrete, parallelizable tasks
-- Decides *when* to spawn workers, not just at t=0 — spawn continues throughout execution as new findings emerge
-- Holds the global view; workers hold local views
-- Aggregates and de-duplicates worker output
-- Never performs primitive operations itself (no direct file reads, no direct tool calls on the target)
-
-**Specialized Worker**
-- One specific, measurable objective per worker
-- Narrow capability scope — loaded with only the skills relevant to its objective (e.g. `authentication_jwt`, `idor`)
-- Emits structured findings back to orchestrator
-- Terminates on success, explicit failure, or when its scope is invalidated
-
-## Coordination Principles
-
-1. **Task Independence** — parallel > sequential. Design each worker so it does not block on another worker's output.
-2. **Clear Objectives** — vague goals cause scope creep and duplicated work. Every worker's system prompt should answer "what does done look like?"
-3. **Avoid Duplication** — before spawning, the orchestrator must check whether an existing worker already covers the scope.
-4. **Hierarchical Delegation** — workers can spawn sub-workers when their scope expands (e.g. a discovery worker finds an endpoint → spawns a validator worker → spawns a report worker).
-5. **Minimum Message Passing** — message passing is reserved for critical handoffs (request/answer pairs). Prefer batched updates to routine status pings. Every message is context a worker has to re-read.
-6. **Resource Efficiency** — terminate workers when objectives are met or made irrelevant by new findings.
-
-## Completion Protocol
-
-When all workers report done:
-1. Collect and deduplicate findings (different workers frequently observe the same root cause from different angles).
-2. Assess overall posture / coverage — what wasn't tested, and why.
-3. Compile executive summary with prioritized recommendations.
-4. Invoke a final reporting tool (or agent) to produce the deliverable.
-
-## Why It Works
-
-- Each worker has a **fresh context window** tuned to its narrow task — they see only the skills and tools they need.
-- The orchestrator never fills its own context with raw tool output — workers pre-digest.
-- Parallelism is the primary speedup lever; this architecture is the enabling structure.
-
-## When NOT to Use
-
-- Single-file edits or one-shot queries — the overhead of spawning swamps the benefit.
-- Strongly sequential workflows where each step depends on the last's full output — use a pipeline, not a swarm.
-- When workers would all load the same large skills — the context savings evaporate.
+---
+name: orchestrator-worker-pattern
+description: Hierarchical agent pattern — a root orchestrator decomposes work and spawns specialized workers with focused context
+source: Distilled from Strix (https://github.com/usestrix/strix, Apache-2.0) — rev 15c95718
+category: agent-architecture
+---
+
+# Orchestrator/Worker Agent Pattern
+
+The root agent owns scope decomposition and aggregation. Specialized workers own narrow, parallelizable tasks. This pattern is what keeps multi-agent systems from drowning in context.
+
+## Roles
+
+**Root / Orchestrator**
+- Decomposes the target into discrete, parallelizable tasks
+- Decides *when* to spawn workers, not just at t=0 — spawn continues throughout execution as new findings emerge
+- Holds the global view; workers hold local views
+- Aggregates and de-duplicates worker output
+- Never performs primitive operations itself (no direct file reads, no direct tool calls on the target)
+
+**Specialized Worker**
+- One specific, measurable objective per worker
+- Narrow capability scope — loaded with only the skills relevant to its objective (e.g. `authentication_jwt`, `idor`)
+- Emits structured findings back to orchestrator
+- Terminates on success, explicit failure, or when its scope is invalidated
+
+## Coordination Principles
+
+1. **Task Independence** — parallel > sequential. Design each worker so it does not block on another worker's output.
+2. **Clear Objectives** — vague goals cause scope creep and duplicated work. Every worker's system prompt should answer "what does done look like?"
+3. **Avoid Duplication** — before spawning, the orchestrator must check whether an existing worker already covers the scope.
+4. **Hierarchical Delegation** — workers can spawn sub-workers when their scope expands (e.g. a discovery worker finds an endpoint → spawns a validator worker → spawns a report worker).
+5. **Minimum Message Passing** — message passing is reserved for critical handoffs (request/answer pairs). Prefer batched updates to routine status pings. Every message is context a worker has to re-read.
+6. **Resource Efficiency** — terminate workers when objectives are met or made irrelevant by new findings.
+
+## Completion Protocol
+
+When all workers report done:
+1. Collect and deduplicate findings (different workers frequently observe the same root cause from different angles).
+2. Assess overall posture / coverage — what wasn't tested, and why.
+3. Compile executive summary with prioritized recommendations.
+4. Invoke a final reporting tool (or agent) to produce the deliverable.
+
+## Why It Works
+
+- Each worker has a **fresh context window** tuned to its narrow task — they see only the skills and tools they need.
+- The orchestrator never fills its own context with raw tool output — workers pre-digest.
+- Parallelism is the primary speedup lever; this architecture is the enabling structure.
+
+## When NOT to Use
+
+- Single-file edits or one-shot queries — the overhead of spawning swamps the benefit.
+- Strongly sequential workflows where each step depends on the last's full output — use a pipeline, not a swarm.
+- When workers would all load the same large skills — the context savings evaporate.
diff --git a/imported-skills/strix/agent-patterns/sandboxed-tool-runtime.md b/imported-skills/strix/agent-patterns/sandboxed-tool-runtime.md
index bcda99b08edcd523df0a0eff9d178d30c2f25532..386615b5196a01d879ea08730c882a04064107dc 100644
--- a/imported-skills/strix/agent-patterns/sandboxed-tool-runtime.md
+++ b/imported-skills/strix/agent-patterns/sandboxed-tool-runtime.md
@@ -1,52 +1,52 @@
----
-name: sandboxed-tool-runtime
-description: Agent tool execution should happen inside a disposable container, not the host — isolation by default, not opt-in
-source: Distilled from Strix (https://github.com/usestrix/strix, Apache-2.0) — rev 15c95718
-category: agent-architecture
----
-
-# Sandboxed Tool Runtime
-
-When an LLM agent can run shell commands, HTTP requests, file operations, or code, the blast radius of a bad decision is unbounded. The sandboxed-runtime pattern constrains that blast radius by running every agent-initiated operation inside an ephemeral container.
-
-## Shape of the Pattern
-
-- One Docker (or equivalent) container per scan/session.
-- Container has the toolchain pre-installed (scanners, browsers, language runtimes) and no credentials except what the host explicitly injects.
-- Agent tool calls are serialized and sent to a tool-server process running *inside* the container.
-- Target source code or artifacts are mounted at `/workspace/...` inside the container, not bind-mounted read-write to host-sensitive paths.
-- Workspace subdirectories are created per-target so multiple targets in one run don't collide.
-- Container lifetime == session lifetime. Cleanup on exit.
-
-## Trust Boundaries
-
-- **Host** trusts the agent to ask for operations but not to execute them directly. All operations go through the container.
-- **Container** is untrusted by the host — its filesystem, network, and exit code are the only channels back.
-- **Agent** is untrusted by the container's outer security policy — it can only call the registered tool actions, not arbitrary binaries (though inside the container shell access is typically granted, it's still a container, so the explosion radius is one container).
-
-## Why This Beats Running Tools on the Host
-
-- LLM agents produce unpredictable command strings. If even 1 in 10,000 is destructive (rm of wrong path, overly-broad git reset), running on host is catastrophic.
-- Tooling dependencies (nmap, nuclei, specific Python versions, Playwright browsers) don't pollute the host.
-- Reruns are deterministic — start a fresh container, get the same initial state.
-- Credentials can be scoped to the session: inject `TOKEN=...` as container env, it's gone when the container exits.
-
-## Key Design Choices
-
-- **Non-interactive mode support** — the container runs long-lived tool-server; the agent talks to it via a local socket/HTTP boundary.
-- **Streaming output** — tool-server streams stdout/stderr back as it arrives, not in a single blob at the end.
-- **Cancellation** — the agent must be able to cancel a running tool (kill the process tree inside the container) without tearing down the whole session.
-- **Pre-pulled images** — first run pulls the sandbox image (often hundreds of MB). Subsequent runs are fast because the image is cached.
-
-## When This Is Overkill
-
-- Pure LLM workloads with no tool calls — no blast radius to contain.
-- Single-file text transforms where the agent rewrites and the host validates after — the host itself is the sandbox in effect.
-- Short, well-typed tool sets (e.g. "this agent can only call `search_docs` and `read_file`") where each tool is individually safe.
-
-## When This Is Required
-
-- Agent executes arbitrary shell or code.
-- Agent performs network operations against external targets.
-- Agent modifies files in arbitrary paths.
-- Multiple agent runs need reproducible, isolated environments.
+---
+name: sandboxed-tool-runtime
+description: Agent tool execution should happen inside a disposable container, not the host — isolation by default, not opt-in
+source: Distilled from Strix (https://github.com/usestrix/strix, Apache-2.0) — rev 15c95718
+category: agent-architecture
+---
+
+# Sandboxed Tool Runtime
+
+When an LLM agent can run shell commands, HTTP requests, file operations, or code, the blast radius of a bad decision is unbounded. The sandboxed-runtime pattern constrains that blast radius by running every agent-initiated operation inside an ephemeral container.
+
+## Shape of the Pattern
+
+- One Docker (or equivalent) container per scan/session.
+- Container has the toolchain pre-installed (scanners, browsers, language runtimes) and no credentials except what the host explicitly injects.
+- Agent tool calls are serialized and sent to a tool-server process running *inside* the container.
+- Target source code or artifacts are mounted at `/workspace/...` inside the container, not bind-mounted read-write to host-sensitive paths.
+- Workspace subdirectories are created per-target so multiple targets in one run don't collide.
+- Container lifetime == session lifetime. Cleanup on exit.
+
+## Trust Boundaries
+
+- **Host** trusts the agent to ask for operations but not to execute them directly. All operations go through the container.
+- **Container** is untrusted by the host — its filesystem, network, and exit code are the only channels back.
+- **Agent** is untrusted by the container's outer security policy — it can only call the registered tool actions, not arbitrary binaries (though inside the container shell access is typically granted, it's still a container, so the explosion radius is one container).
+
+## Why This Beats Running Tools on the Host
+
+- LLM agents produce unpredictable command strings. If even 1 in 10,000 is destructive (rm of wrong path, overly-broad git reset), running on host is catastrophic.
+- Tooling dependencies (nmap, nuclei, specific Python versions, Playwright browsers) don't pollute the host.
+- Reruns are deterministic — start a fresh container, get the same initial state.
+- Credentials can be scoped to the session: inject `TOKEN=...` as container env, it's gone when the container exits.
+
+## Key Design Choices
+
+- **Non-interactive mode support** — the container runs long-lived tool-server; the agent talks to it via a local socket/HTTP boundary.
+- **Streaming output** — tool-server streams stdout/stderr back as it arrives, not in a single blob at the end.
+- **Cancellation** — the agent must be able to cancel a running tool (kill the process tree inside the container) without tearing down the whole session.
+- **Pre-pulled images** — first run pulls the sandbox image (often hundreds of MB). Subsequent runs are fast because the image is cached.
+
+## When This Is Overkill
+
+- Pure LLM workloads with no tool calls — no blast radius to contain.
+- Single-file text transforms where the agent rewrites and the host validates after — the host itself is the sandbox in effect.
+- Short, well-typed tool sets (e.g. "this agent can only call `search_docs` and `read_file`") where each tool is individually safe.
+
+## When This Is Required
+
+- Agent executes arbitrary shell or code.
+- Agent performs network operations against external targets.
+- Agent modifies files in arbitrary paths.
+- Multiple agent runs need reproducible, isolated environments.
diff --git a/imported-skills/strix/agent-patterns/scan-mode-as-skill.md b/imported-skills/strix/agent-patterns/scan-mode-as-skill.md
index dae5e1baf733c992c745ea707e0677cd6bdb4bb9..27e42b820cba22610d4f796147fd7e24a0afefa1 100644
--- a/imported-skills/strix/agent-patterns/scan-mode-as-skill.md
+++ b/imported-skills/strix/agent-patterns/scan-mode-as-skill.md
@@ -1,57 +1,57 @@
----
-name: scan-mode-as-skill
-description: Operational modes (quick/standard/deep) should be first-class skills, not hard-coded branching — each mode defines its own phases, priorities, and completion criteria
-source: Distilled from Strix (https://github.com/usestrix/strix, Apache-2.0) — rev 15c95718
-category: agent-architecture
----
-
-# Scan-Mode-as-Skill
-
-Rather than hard-coding `if mode == "quick": do_x() else: do_y()` in the agent runtime, treat each operational mode as its own skill that the root agent loads at session start. Each mode skill encodes the phases, priorities, and exit criteria for that mode.
-
-## The Three Canonical Modes
-
-**Quick** — time-boxed rapid assessment
-- Prioritize breadth over depth.
-- Focus on recent changes (git diffs, modified files) — most likely to contain fresh bugs.
-- Load existing wiki notes instead of remapping from scratch.
-- Run fast static triage scoped to changed paths.
-- One of each essential pass: `semgrep`, `ast-grep` (or `tree-sitter`), secrets, `trivy fs` — scoped.
-- Use case: CI/CD check on a PR.
-
-**Standard** — balanced systematic assessment
-- Full attack surface mapping, but not exhaustive depth on every surface.
-- Understand the application before exploiting it.
-- Complete authentication/authorization review.
-- All major input vectors tested with primary techniques.
-- Use case: routine security review, release gate.
-
-**Deep** — exhaustive assessment
-- Maximum coverage, maximum depth. Finding what others miss is the goal.
-- Multi-phase: exhaustive recon → business logic deep dive → comprehensive attack surface → vulnerability chaining → persistent testing → comprehensive reporting.
-- Agents decompose hierarchically: component → feature → vulnerability, then scale horizontally.
-- Use case: thorough audit, adversarial assessment, post-incident deep dive.
-
-## Why This Beats Hard-Coding Modes
-
-- **Transparent** — users can read exactly what "deep" means in markdown, not reverse-engineer control flow.
-- **Extensible** — add `pr_review`, `red_team`, `compliance_scan` modes by dropping in new skill files.
-- **Tunable per domain** — an org can fork the skill to reflect its own priorities without forking the engine.
-- **Reusable pattern** — the same pattern works for any system that has "modes of operation": deployment modes, migration modes, refactor modes.
-
-## Anatomy of a Mode Skill
-
-- **Phase 1..N** — ordered steps with clear enter/exit criteria
-- **Whitebox vs blackbox variants** — most modes apply differently depending on input
-- **Agent strategy** — how to decompose work at this depth (what workers to spawn, how to parallelize)
-- **Completion criteria** — what "done" looks like for this mode
-- **Mindset guidance** — one paragraph setting the attitude (relentless vs. fast vs. thorough)
-
-## Portability Beyond Security
-
-The scan-mode-as-skill pattern maps cleanly onto any multi-step agent workflow where depth/time/rigor is a knob:
-- **Code review**: quick (syntax + obvious bugs) / standard (+ architecture) / deep (+ perf + security + maintainability)
-- **Refactoring**: quick (extract method) / standard (restructure module) / deep (cross-module redesign)
-- **Documentation**: quick (API signatures) / standard (+ usage examples) / deep (+ architectural context + migration notes)
-
-Each mode becomes a first-class, versioned, diffable artifact.
+---
+name: scan-mode-as-skill
+description: Operational modes (quick/standard/deep) should be first-class skills, not hard-coded branching — each mode defines its own phases, priorities, and completion criteria
+source: Distilled from Strix (https://github.com/usestrix/strix, Apache-2.0) — rev 15c95718
+category: agent-architecture
+---
+
+# Scan-Mode-as-Skill
+
+Rather than hard-coding `if mode == "quick": do_x() else: do_y()` in the agent runtime, treat each operational mode as its own skill that the root agent loads at session start. Each mode skill encodes the phases, priorities, and exit criteria for that mode.
+
+## The Three Canonical Modes
+
+**Quick** — time-boxed rapid assessment
+- Prioritize breadth over depth.
+- Focus on recent changes (git diffs, modified files) — most likely to contain fresh bugs.
+- Load existing wiki notes instead of remapping from scratch.
+- Run fast static triage scoped to changed paths.
+- One of each essential pass: `semgrep`, `ast-grep` (or `tree-sitter`), secrets, `trivy fs` — scoped.
+- Use case: CI/CD check on a PR.
+
+**Standard** — balanced systematic assessment
+- Full attack surface mapping, but not exhaustive depth on every surface.
+- Understand the application before exploiting it.
+- Complete authentication/authorization review.
+- All major input vectors tested with primary techniques.
+- Use case: routine security review, release gate.
+
+**Deep** — exhaustive assessment
+- Maximum coverage, maximum depth. Finding what others miss is the goal.
+- Multi-phase: exhaustive recon → business logic deep dive → comprehensive attack surface → vulnerability chaining → persistent testing → comprehensive reporting.
+- Agents decompose hierarchically: component → feature → vulnerability, then scale horizontally.
+- Use case: thorough audit, adversarial assessment, post-incident deep dive.
+
+## Why This Beats Hard-Coding Modes
+
+- **Transparent** — users can read exactly what "deep" means in markdown, not reverse-engineer control flow.
+- **Extensible** — add `pr_review`, `red_team`, `compliance_scan` modes by dropping in new skill files.
+- **Tunable per domain** — an org can fork the skill to reflect its own priorities without forking the engine.
+- **Reusable pattern** — the same pattern works for any system that has "modes of operation": deployment modes, migration modes, refactor modes.
+
+## Anatomy of a Mode Skill
+
+- **Phase 1..N** — ordered steps with clear enter/exit criteria
+- **Whitebox vs blackbox variants** — most modes apply differently depending on input
+- **Agent strategy** — how to decompose work at this depth (what workers to spawn, how to parallelize)
+- **Completion criteria** — what "done" looks like for this mode
+- **Mindset guidance** — one paragraph setting the attitude (relentless vs. fast vs. thorough)
+
+## Portability Beyond Security
+
+The scan-mode-as-skill pattern maps cleanly onto any multi-step agent workflow where depth/time/rigor is a knob:
+- **Code review**: quick (syntax + obvious bugs) / standard (+ architecture) / deep (+ perf + security + maintainability)
+- **Refactoring**: quick (extract method) / standard (restructure module) / deep (cross-module redesign)
+- **Documentation**: quick (API signatures) / standard (+ usage examples) / deep (+ architectural context + migration notes)
+
+Each mode becomes a first-class, versioned, diffable artifact.
diff --git a/imported-skills/strix/agent-patterns/shared-wiki-memory-pattern.md b/imported-skills/strix/agent-patterns/shared-wiki-memory-pattern.md
index e0d75c31f427ff290aa58e9bf0110f8931cbbb07..af81d8b4355bc4aad71d598bf5644c3a4324efc5 100644
--- a/imported-skills/strix/agent-patterns/shared-wiki-memory-pattern.md
+++ b/imported-skills/strix/agent-patterns/shared-wiki-memory-pattern.md
@@ -1,47 +1,47 @@
----
-name: shared-wiki-memory-pattern
-description: Multi-agent systems need a shared, append-only memory — one canonical note per entity, updated by every agent that touches it
-source: Distilled from Strix (https://github.com/usestrix/strix, Apache-2.0) — rev 15c95718
-category: agent-architecture
----
-
-# Shared Wiki Memory Pattern
-
-When a swarm of agents explores the same target, the fastest way to waste cycles is to let each agent re-derive the same mental model. The wiki-memory pattern enforces a single canonical note per entity (e.g. per repository, per service, per user flow) that every participating agent reads first and updates before finishing.
-
-## The Protocol
-
-1. **At task start** — every agent MUST call `list_notes(category="wiki")` and `get_note(note_id=...)` to load the canonical note for its scope. This is non-optional.
-2. **If no note exists** — the first agent to arrive creates it with `create_note(category="wiki")`. Subsequent arrivals find and reuse it.
-3. **During work** — agents extend the note with new findings via `update_note`. Never create a second note for the same entity.
-4. **Before finishing** — every agent appends a short delta update (what did I find, what still needs validation) before calling `agent_finish`.
-
-## Note Anatomy (per repository)
-
-Recommended sections, kept in this order so readers get oriented fast:
-
-- **Architecture overview** — high-level shape: modules, entry points, deployment model
-- **Entrypoints and routing** — how external traffic / invocations reach code
-- **AuthN/AuthZ model** — identity flows, session handling, access checks
-- **High-risk sinks and trust boundaries** — where untrusted data meets sensitive operations
-- **Static scanner summary** — semgrep/ast-grep/secrets/trivy output, deduplicated
-- **Dynamic validation follow-ups** — static findings that still need PoC
-
-## Why One Note Per Entity
-
-- **Convergence over divergence** — N agents produce one coherent story, not N conflicting ones.
-- **Fast onboarding for new workers** — a worker spawned 20 minutes into a run reads the current wiki note in seconds and skips rediscovery.
-- **Deduplication by construction** — if two agents are about to record the same finding, the second sees the first's entry and adapts.
-- **Auditability** — the note's revision history is the assessment's reasoning log.
-
-## Discipline Required
-
-- Resist the temptation to create a parallel note. If the existing note is wrong, *update* it.
-- Keep entries evidence-driven. A wiki bloated with speculation loses its value.
-- Prefer bounded, query-driven entries over whole-repo dumps. "Here are the 4 SQL sinks we found" beats "here is grep output for every call to `execute`."
-
-## When It Backfires
-
-- Without concurrency discipline, updates can clobber each other (last writer wins). Either serialize updates, use append-only semantics, or use a CRDT-ish merge.
-- If the note grows without compaction, it becomes context-poison for any agent that reads it. Periodically summarize and archive older sections.
-- If agents skip the read-first step, the pattern provides zero benefit. Enforce it in the orchestration skill / system prompt, not as a polite suggestion.
+---
+name: shared-wiki-memory-pattern
+description: Multi-agent systems need a shared, append-only memory — one canonical note per entity, updated by every agent that touches it
+source: Distilled from Strix (https://github.com/usestrix/strix, Apache-2.0) — rev 15c95718
+category: agent-architecture
+---
+
+# Shared Wiki Memory Pattern
+
+When a swarm of agents explores the same target, the fastest way to waste cycles is to let each agent re-derive the same mental model. The wiki-memory pattern enforces a single canonical note per entity (e.g. per repository, per service, per user flow) that every participating agent reads first and updates before finishing.
+
+## The Protocol
+
+1. **At task start** — every agent MUST call `list_notes(category="wiki")` and `get_note(note_id=...)` to load the canonical note for its scope. This is non-optional.
+2. **If no note exists** — the first agent to arrive creates it with `create_note(category="wiki")`. Subsequent arrivals find and reuse it.
+3. **During work** — agents extend the note with new findings via `update_note`. Never create a second note for the same entity.
+4. **Before finishing** — every agent appends a short delta update (what did I find, what still needs validation) before calling `agent_finish`.
+
+## Note Anatomy (per repository)
+
+Recommended sections, kept in this order so readers get oriented fast:
+
+- **Architecture overview** — high-level shape: modules, entry points, deployment model
+- **Entrypoints and routing** — how external traffic / invocations reach code
+- **AuthN/AuthZ model** — identity flows, session handling, access checks
+- **High-risk sinks and trust boundaries** — where untrusted data meets sensitive operations
+- **Static scanner summary** — semgrep/ast-grep/secrets/trivy output, deduplicated
+- **Dynamic validation follow-ups** — static findings that still need PoC
+
+## Why One Note Per Entity
+
+- **Convergence over divergence** — N agents produce one coherent story, not N conflicting ones.
+- **Fast onboarding for new workers** — a worker spawned 20 minutes into a run reads the current wiki note in seconds and skips rediscovery.
+- **Deduplication by construction** — if two agents are about to record the same finding, the second sees the first's entry and adapts.
+- **Auditability** — the note's revision history is the assessment's reasoning log.
+
+## Discipline Required
+
+- Resist the temptation to create a parallel note. If the existing note is wrong, *update* it.
+- Keep entries evidence-driven. A wiki bloated with speculation loses its value.
+- Prefer bounded, query-driven entries over whole-repo dumps. "Here are the 4 SQL sinks we found" beats "here is grep output for every call to `execute`."
+
+## When It Backfires
+
+- Without concurrency discipline, updates can clobber each other (last writer wins). Either serialize updates, use append-only semantics, or use a CRDT-ish merge.
+- If the note grows without compaction, it becomes context-poison for any agent that reads it. Periodically summarize and archive older sections.
+- If agents skip the read-first step, the pattern provides zero benefit. Enforce it in the orchestration skill / system prompt, not as a polite suggestion.
diff --git a/imported-skills/strix/agent-patterns/skill-injection-pattern.md b/imported-skills/strix/agent-patterns/skill-injection-pattern.md
index 8ab766dcd12cb76bbfa89a138b4bc3d6e3144eee..d9dcf4c4a1e116de5006410e3e3878a2205a7d2a 100644
--- a/imported-skills/strix/agent-patterns/skill-injection-pattern.md
+++ b/imported-skills/strix/agent-patterns/skill-injection-pattern.md
@@ -1,61 +1,61 @@
----
-name: skill-injection-pattern
-description: Load up to N specialized skills into an agent at spawn time — dynamically tailor expertise per subtask
-source: Distilled from Strix (https://github.com/usestrix/strix, Apache-2.0) — rev 15c95718
-category: agent-architecture
----
-
-# Skill Injection Pattern
-
-Skills are specialized knowledge packages (markdown with YAML frontmatter). They are selected at agent-spawn time based on the subtask, then dynamically injected into the agent's system prompt. This is how a generic agent runtime becomes a domain expert on demand.
-
-## Shape of a Skill
-
-- Markdown document with YAML frontmatter `name` + `description` (the description is what the router matches against)
-- Length budget: typically 150–250 lines (large enough for depth, small enough to combine several in one prompt)
-- Content: advanced techniques, practical payloads/commands, validation methods, context-specific edge cases
-- Self-contained — a skill should not require the agent to load other skills to understand it
-
-## Selection Protocol
-
-1. Orchestrator identifies the subtask (e.g. "test authentication mechanisms in API").
-2. A router scores each available skill's description against the subtask.
-3. Top N skills (Strix uses N=5) are selected — beyond that, prompt bloat degrades quality.
-4. Selected skill bodies are concatenated into the agent's system prompt at construction time.
-
-```python
-# Shape of the spawn call
-create_agent(
- task="Test authentication mechanisms in API",
- name="Auth Specialist",
- skills="authentication_jwt,business_logic",
-)
-```
-
-## Skill Categories (useful split for a large library)
-
-- **vulnerabilities/** — testing techniques for specific vuln classes (SQLi, XSS, IDOR, etc.)
-- **frameworks/** — framework-specific patterns (FastAPI, Next.js, Django)
-- **technologies/** — third-party platforms (Supabase, Firebase, payment gateways)
-- **protocols/** — communication standards (GraphQL, WebSocket, OAuth)
-- **tooling/** — CLI playbooks for specific tools (nmap, semgrep, sqlmap)
-- **cloud/** — AWS/Azure/GCP/K8s testing patterns
-- **reconnaissance/** — enumeration and mapping techniques
-- **coordination/** — orchestration playbooks (how to work with other agents)
-- **scan_modes/** — system-level mode definitions (quick/standard/deep)
-- **custom/** — community-contributed / domain-specific
-
-## Why This Beats Baking Knowledge into the Agent
-
-- **Extensibility without retraining** — new skills are plain markdown files added to a directory; no code changes, no fine-tuning.
-- **Context efficiency** — agents load only what they need; the same runtime handles wildly different domains.
-- **Community contribution** — non-engineers (pentesters, auditors, domain experts) can contribute via PRs.
-- **Version-controllable expertise** — skills are diffed, reviewed, and tested like any code artifact.
-
-## Design Rules for Writing Skills
-
-- Lead with the **YAML description** — it must be specific enough that the router can disambiguate.
-- Include **practical examples** (payloads, commands, code snippets), not abstract principles.
-- Include **validation methods** — how to confirm a finding and avoid false positives.
-- Keep context-specific nuance (version, configuration, edge cases) in a clearly-labeled section.
-- No external dependencies — if a skill references a tool, include the tool's invocation inline.
+---
+name: skill-injection-pattern
+description: Load up to N specialized skills into an agent at spawn time — dynamically tailor expertise per subtask
+source: Distilled from Strix (https://github.com/usestrix/strix, Apache-2.0) — rev 15c95718
+category: agent-architecture
+---
+
+# Skill Injection Pattern
+
+Skills are specialized knowledge packages (markdown with YAML frontmatter). They are selected at agent-spawn time based on the subtask, then dynamically injected into the agent's system prompt. This is how a generic agent runtime becomes a domain expert on demand.
+
+## Shape of a Skill
+
+- Markdown document with YAML frontmatter `name` + `description` (the description is what the router matches against)
+- Length budget: typically 150–250 lines (large enough for depth, small enough to combine several in one prompt)
+- Content: advanced techniques, practical payloads/commands, validation methods, context-specific edge cases
+- Self-contained — a skill should not require the agent to load other skills to understand it
+
+## Selection Protocol
+
+1. Orchestrator identifies the subtask (e.g. "test authentication mechanisms in API").
+2. A router scores each available skill's description against the subtask.
+3. Top N skills (Strix uses N=5) are selected — beyond that, prompt bloat degrades quality.
+4. Selected skill bodies are concatenated into the agent's system prompt at construction time.
+
+```python
+# Shape of the spawn call
+create_agent(
+ task="Test authentication mechanisms in API",
+ name="Auth Specialist",
+ skills="authentication_jwt,business_logic",
+)
+```
+
+## Skill Categories (useful split for a large library)
+
+- **vulnerabilities/** — testing techniques for specific vuln classes (SQLi, XSS, IDOR, etc.)
+- **frameworks/** — framework-specific patterns (FastAPI, Next.js, Django)
+- **technologies/** — third-party platforms (Supabase, Firebase, payment gateways)
+- **protocols/** — communication standards (GraphQL, WebSocket, OAuth)
+- **tooling/** — CLI playbooks for specific tools (nmap, semgrep, sqlmap)
+- **cloud/** — AWS/Azure/GCP/K8s testing patterns
+- **reconnaissance/** — enumeration and mapping techniques
+- **coordination/** — orchestration playbooks (how to work with other agents)
+- **scan_modes/** — system-level mode definitions (quick/standard/deep)
+- **custom/** — community-contributed / domain-specific
+
+## Why This Beats Baking Knowledge into the Agent
+
+- **Extensibility without retraining** — new skills are plain markdown files added to a directory; no code changes, no fine-tuning.
+- **Context efficiency** — agents load only what they need; the same runtime handles wildly different domains.
+- **Community contribution** — non-engineers (pentesters, auditors, domain experts) can contribute via PRs.
+- **Version-controllable expertise** — skills are diffed, reviewed, and tested like any code artifact.
+
+## Design Rules for Writing Skills
+
+- Lead with the **YAML description** — it must be specific enough that the router can disambiguate.
+- Include **practical examples** (payloads, commands, code snippets), not abstract principles.
+- Include **validation methods** — how to confirm a finding and avoid false positives.
+- Keep context-specific nuance (version, configuration, edge cases) in a clearly-labeled section.
+- No external dependencies — if a skill references a tool, include the tool's invocation inline.
diff --git a/imported-skills/strix/build_manifest.py b/imported-skills/strix/build_manifest.py
index 506ae4e252fb4bb8cda93d887a54b9b99d50a95c..f5b7b074a60ea795549b1275e949a338426d8f00 100644
--- a/imported-skills/strix/build_manifest.py
+++ b/imported-skills/strix/build_manifest.py
@@ -1,73 +1,73 @@
-#!/usr/bin/env python3
-"""Generate MANIFEST.json for the imported Strix skill set.
-
-Reads every *.md under skills/ and agent-patterns/, parses YAML frontmatter,
-emits a deterministic manifest the importer can consume.
-"""
-
-from __future__ import annotations
-
-import json
-import re
-from pathlib import Path
-
-ROOT = Path(__file__).parent
-SKILL_GLOBS = ["skills/**/*.md", "agent-patterns/*.md"]
-
-FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL)
-
-
-def parse_frontmatter(text: str) -> dict[str, str]:
- m = FRONTMATTER_RE.match(text)
- if not m:
- return {}
- out: dict[str, str] = {}
- for line in m.group(1).splitlines():
- if ":" not in line:
- continue
- k, _, v = line.partition(":")
- out[k.strip()] = v.strip().strip('"').strip("'")
- return out
-
-
-def build() -> dict:
- entries: list[dict] = []
- for glob in SKILL_GLOBS:
- for path in sorted(ROOT.glob(glob)):
- if path.name.upper() == "README.MD":
- continue
- text = path.read_text(encoding="utf-8")
- fm = parse_frontmatter(text)
- rel = path.relative_to(ROOT).as_posix()
- category = rel.split("/")[1] if rel.startswith("skills/") else "agent-patterns"
- entries.append({
- "name": fm.get("name", path.stem),
- "description": fm.get("description", ""),
- "category": category,
- "source_path": rel,
- "lines": len(text.splitlines()),
- })
- return {
- "upstream": "https://github.com/usestrix/strix",
- "upstream_revision": "15c95718e600897a2a532a613a1c8fa6b712b144",
- "upstream_date": "2026-04-13",
- "license": "Apache-2.0",
- "total_skills": sum(1 for e in entries if e["category"] != "agent-patterns"),
- "total_patterns": sum(1 for e in entries if e["category"] == "agent-patterns"),
- "total": len(entries),
- "entries": entries,
- }
-
-
-def main() -> None:
- manifest = build()
- out_path = ROOT / "MANIFEST.json"
- out_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
- print(
- f"Manifest written: {manifest['total']} entries "
- f"({manifest['total_skills']} skills + {manifest['total_patterns']} patterns)"
- )
-
-
-if __name__ == "__main__":
- main()
+#!/usr/bin/env python3
+"""Generate MANIFEST.json for the imported Strix skill set.
+
+Reads every *.md under skills/ and agent-patterns/, parses YAML frontmatter,
+emits a deterministic manifest the importer can consume.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+
+ROOT = Path(__file__).parent
+SKILL_GLOBS = ["skills/**/*.md", "agent-patterns/*.md"]
+
+FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL)
+
+
+def parse_frontmatter(text: str) -> dict[str, str]:
+ m = FRONTMATTER_RE.match(text)
+ if not m:
+ return {}
+ out: dict[str, str] = {}
+ for line in m.group(1).splitlines():
+ if ":" not in line:
+ continue
+ k, _, v = line.partition(":")
+ out[k.strip()] = v.strip().strip('"').strip("'")
+ return out
+
+
+def build() -> dict:
+ entries: list[dict] = []
+ for glob in SKILL_GLOBS:
+ for path in sorted(ROOT.glob(glob)):
+ if path.name.upper() == "README.MD":
+ continue
+ text = path.read_text(encoding="utf-8")
+ fm = parse_frontmatter(text)
+ rel = path.relative_to(ROOT).as_posix()
+ category = rel.split("/")[1] if rel.startswith("skills/") else "agent-patterns"
+ entries.append({
+ "name": fm.get("name", path.stem),
+ "description": fm.get("description", ""),
+ "category": category,
+ "source_path": rel,
+ "lines": len(text.splitlines()),
+ })
+ return {
+ "upstream": "https://github.com/usestrix/strix",
+ "upstream_revision": "15c95718e600897a2a532a613a1c8fa6b712b144",
+ "upstream_date": "2026-04-13",
+ "license": "Apache-2.0",
+ "total_skills": sum(1 for e in entries if e["category"] != "agent-patterns"),
+ "total_patterns": sum(1 for e in entries if e["category"] == "agent-patterns"),
+ "total": len(entries),
+ "entries": entries,
+ }
+
+
+def main() -> None:
+ manifest = build()
+ out_path = ROOT / "MANIFEST.json"
+ out_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
+ print(
+ f"Manifest written: {manifest['total']} entries "
+ f"({manifest['total_skills']} skills + {manifest['total_patterns']} patterns)"
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/install.ps1 b/install.ps1
index 4ca6a9c1ebcffcbf298cff0a458f707c27151ba9..f6eb1f67ceffcd647c99daf31c42cc0fceb67b83 100644
--- a/install.ps1
+++ b/install.ps1
@@ -1,42 +1,42 @@
-param(
- [Parameter(ValueFromRemainingArguments = $true)]
- [string[]]$RemainingArgs
-)
-
-$ErrorActionPreference = "Stop"
-
-$CtxDir = $PSScriptRoot
-$ForwardArgs = @()
-
-if ($RemainingArgs.Count -ge 2 -and $RemainingArgs[0] -eq "--ctx-dir") {
- $CtxDir = $RemainingArgs[1]
- if ($RemainingArgs.Count -gt 2) {
- $ForwardArgs = $RemainingArgs[2..($RemainingArgs.Count - 1)]
- }
-}
-elseif ($RemainingArgs.Count -ge 1 -and -not $RemainingArgs[0].StartsWith("--")) {
- $CtxDir = $RemainingArgs[0]
- if ($RemainingArgs.Count -gt 1) {
- $ForwardArgs = $RemainingArgs[1..($RemainingArgs.Count - 1)]
- }
-}
-else {
- $ForwardArgs = $RemainingArgs
-}
-
-$Python = $env:PYTHON
-if (-not $Python) {
- $Python = "python"
-}
-
-$SrcDir = Join-Path $CtxDir "src"
-$Separator = [System.IO.Path]::PathSeparator
-if ($env:PYTHONPATH) {
- $env:PYTHONPATH = "$SrcDir$Separator$env:PYTHONPATH"
-}
-else {
- $env:PYTHONPATH = $SrcDir
-}
-
-& $Python -m ctx_init @ForwardArgs
-exit $LASTEXITCODE
+param(
+ [Parameter(ValueFromRemainingArguments = $true)]
+ [string[]]$RemainingArgs
+)
+
+$ErrorActionPreference = "Stop"
+
+$CtxDir = $PSScriptRoot
+$ForwardArgs = @()
+
+if ($RemainingArgs.Count -ge 2 -and $RemainingArgs[0] -eq "--ctx-dir") {
+ $CtxDir = $RemainingArgs[1]
+ if ($RemainingArgs.Count -gt 2) {
+ $ForwardArgs = $RemainingArgs[2..($RemainingArgs.Count - 1)]
+ }
+}
+elseif ($RemainingArgs.Count -ge 1 -and -not $RemainingArgs[0].StartsWith("--")) {
+ $CtxDir = $RemainingArgs[0]
+ if ($RemainingArgs.Count -gt 1) {
+ $ForwardArgs = $RemainingArgs[1..($RemainingArgs.Count - 1)]
+ }
+}
+else {
+ $ForwardArgs = $RemainingArgs
+}
+
+$Python = $env:PYTHON
+if (-not $Python) {
+ $Python = "python"
+}
+
+$SrcDir = Join-Path $CtxDir "src"
+$Separator = [System.IO.Path]::PathSeparator
+if ($env:PYTHONPATH) {
+ $env:PYTHONPATH = "$SrcDir$Separator$env:PYTHONPATH"
+}
+else {
+ $env:PYTHONPATH = $SrcDir
+}
+
+& $Python -m ctx_init @ForwardArgs
+exit $LASTEXITCODE
diff --git a/install.sh b/install.sh
index 19f0f35b9e31acce2d9b7f7107cc87febe1df157..5e36704219c0812c61c72b38cc435c7297a0264e 100644
--- a/install.sh
+++ b/install.sh
@@ -1,36 +1,36 @@
-#!/usr/bin/env bash
-# Compatibility wrapper for source checkouts.
-#
-# The supported installer is ctx-init. This script exists only for users who
-# still run `bash install.sh` from a clone; it delegates to the packaged
-# bootstrap module instead of calling legacy flat scripts.
-
-set -euo pipefail
-
-SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-CTX_DIR="$SCRIPT_DIR"
-
-if [[ "${1:-}" == "--ctx-dir" ]]; then
- if [[ -z "${2:-}" ]]; then
- echo "install.sh: --ctx-dir requires a path" >&2
- exit 2
- fi
- CTX_DIR="$2"
- shift 2
-elif [[ -n "${1:-}" && "${1:-}" != --* ]]; then
- CTX_DIR="$1"
- shift
-fi
-
-PYTHON="${PYTHON:-python3}"
-if ! command -v "$PYTHON" >/dev/null 2>&1; then
- PYTHON="python"
-fi
-
-PYTHONPATH_SEP="$("$PYTHON" - <<'PY'
-import os
-print(os.pathsep)
-PY
-)"
-export PYTHONPATH="$CTX_DIR/src${PYTHONPATH:+$PYTHONPATH_SEP$PYTHONPATH}"
-exec "$PYTHON" -m ctx_init "$@"
+#!/usr/bin/env bash
+# Compatibility wrapper for source checkouts.
+#
+# The supported installer is ctx-init. This script exists only for users who
+# still run `bash install.sh` from a clone; it delegates to the packaged
+# bootstrap module instead of calling legacy flat scripts.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+CTX_DIR="$SCRIPT_DIR"
+
+if [[ "${1:-}" == "--ctx-dir" ]]; then
+ if [[ -z "${2:-}" ]]; then
+ echo "install.sh: --ctx-dir requires a path" >&2
+ exit 2
+ fi
+ CTX_DIR="$2"
+ shift 2
+elif [[ -n "${1:-}" && "${1:-}" != --* ]]; then
+ CTX_DIR="$1"
+ shift
+fi
+
+PYTHON="${PYTHON:-python3}"
+if ! command -v "$PYTHON" >/dev/null 2>&1; then
+ PYTHON="python"
+fi
+
+PYTHONPATH_SEP="$("$PYTHON" - <<'PY'
+import os
+print(os.pathsep)
+PY
+)"
+export PYTHONPATH="$CTX_DIR/src${PYTHONPATH:+$PYTHONPATH_SEP$PYTHONPATH}"
+exec "$PYTHON" -m ctx_init "$@"
diff --git a/mkdocs.yml b/mkdocs.yml
index 5d1ad910de801bd85c6e032ec7c3f3ca8e33093b..c8291bc50e4eff6a772e010bb229bc892ae38417 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -17,12 +17,12 @@ site_dir: site
strict: true
-# SKILL.md lives in docs/ for historical reasons but doesn't belong
-# in the rendered nav; the skill-router section summarizes it.
-not_in_nav: |
- SKILL.md
-
-theme:
+# SKILL.md lives in docs/ for historical reasons but doesn't belong
+# in the rendered nav; the skill-router section summarizes it.
+not_in_nav: |
+ SKILL.md
+
+theme:
name: material
features:
- navigation.instant
@@ -89,15 +89,15 @@ plugins:
nav:
- Home: index.md
- - Knowledge graph: knowledge-graph.md
- - Hugging Face publish: huggingface-publish.md
- - Entity onboarding: entity-onboarding.md
- - Dashboard: dashboard.md
- - Harness:
- - Attach to hosts: harness/attaching-to-hosts.md
- - Clean-host contract: harness/clean-host-contract.md
- - Toolbox:
- - Overview: toolbox/index.md
+ - Knowledge graph: knowledge-graph.md
+ - Hugging Face publish: huggingface-publish.md
+ - Entity onboarding: entity-onboarding.md
+ - Dashboard: dashboard.md
+ - Harness:
+ - Attach to hosts: harness/attaching-to-hosts.md
+ - Clean-host contract: harness/clean-host-contract.md
+ - Toolbox:
+ - Overview: toolbox/index.md
- Configuration: toolbox/configuration.md
- Starter toolboxes: toolbox/starters.md
- Council runner: toolbox/council-runner.md
diff --git a/pyproject.toml b/pyproject.toml
index 89dbee030f852534fee7ec85b54ba59db0224ab8..0cf844dea1983b3afe886ce20763caf9480520d9 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "claude-ctx"
-version = "0.7.3"
+version = "0.7.5"
description = "Skill and agent recommendation system for Claude Code — knowledge graph, wiki, and intake quality gates"
authors = [{ name = "Steve Solun" }]
license = "MIT"
diff --git a/requirements-docs.txt b/requirements-docs.txt
index 63b7ce2a16469893e7efb3ec4d49d7be8d29145f..71ce460670305def7cd2e321f01dc3a6d732baad 100644
--- a/requirements-docs.txt
+++ b/requirements-docs.txt
@@ -1,12 +1,12 @@
-# Pinned dependencies for the MkDocs Material documentation site.
-# Used by .github/workflows/docs.yml for the GitHub Pages deploy.
-# Keep this file minimal — runtime deps belong elsewhere.
-
-mkdocs==1.6.1
-mkdocs-material==9.5.44
-pymdown-extensions==10.12
-# Pin Pygments below 2.20 — 2.20.0 broke pymdownx.highlight by rejecting
-# filename=None inside pygments.formatters.html.HtmlFormatter, which causes
-# `mkdocs build --strict` to fail on any code fence. Lift this pin once
-# pymdown-extensions releases a version that passes filename='' explicitly.
-Pygments==2.19.2
+# Pinned dependencies for the MkDocs Material documentation site.
+# Used by .github/workflows/docs.yml for the GitHub Pages deploy.
+# Keep this file minimal — runtime deps belong elsewhere.
+
+mkdocs==1.6.1
+mkdocs-material==9.5.44
+pymdown-extensions==10.12
+# Pin Pygments below 2.20 — 2.20.0 broke pymdownx.highlight by rejecting
+# filename=None inside pygments.formatters.html.HtmlFormatter, which causes
+# `mkdocs build --strict` to fail on any code fence. Lift this pin once
+# pymdown-extensions releases a version that passes filename='' explicitly.
+Pygments==2.19.2
diff --git a/scripts/audit_backup.py b/scripts/audit_backup.py
index 262bee508a39e9a63b8d73f9e8d6475cc3e71779..79c1c3fc9eb92b4d24de38174b40008a31c2f962 100644
--- a/scripts/audit_backup.py
+++ b/scripts/audit_backup.py
@@ -1,74 +1,74 @@
-"""audit_backup.py -- Summarize a backup snapshot and flag what is missing."""
-
-from __future__ import annotations
-
-import json
-import os
-import sys
-from collections import Counter
-from pathlib import Path
-
-CLAUDE_HOME = Path(os.path.expanduser("~/.claude"))
-BACKUPS = CLAUDE_HOME / "backups"
-
-
-def latest_snapshot() -> Path:
- snaps = sorted(p for p in BACKUPS.iterdir() if p.is_dir())
- return snaps[-1]
-
-
-def main() -> int:
- snap = Path(sys.argv[1]) if len(sys.argv) > 1 else latest_snapshot()
- manifest = json.loads((snap / "manifest.json").read_text(encoding="utf-8"))
-
- print(f"snapshot: {snap}")
- print(f"entries: {len(manifest['entries'])}")
- total = sum((e.get("size") or 0) for e in manifest["entries"])
- print(f"bytes: {total:,}")
-
- print("\n--- Top-level files ---")
- for e in manifest["entries"]:
- d = e["dest"]
- if "/" not in d and "\\" not in d:
- print(f" {d:<32} {e['size']:>8}B")
-
- print("\n--- Tree coverage ---")
- roots: Counter[str] = Counter()
- for e in manifest["entries"]:
- head = e["dest"].replace("\\", "/").split("/", 1)[0]
- roots[head] += 1
- for r, c in roots.most_common():
- print(f" {r:<32} {c:>5} files")
-
- # Audit what's in ~/.claude but NOT in the backup.
- print("\n--- Candidate files in ~/.claude NOT backed up ---")
- backed_up_sources = {Path(e["source"]).resolve() for e in manifest["entries"]}
- candidates = [
- CLAUDE_HOME / "skill-system-config.json",
- CLAUDE_HOME / "intent-log.jsonl",
- CLAUDE_HOME / "skill-registry.json",
- CLAUDE_HOME / "CLAUDE.md",
- CLAUDE_HOME / "claude.json",
- CLAUDE_HOME / ".claude.json",
- ]
- for c in candidates:
- if c.is_file() and c.resolve() not in backed_up_sources:
- print(f" MISSING: {c} ({c.stat().st_size}B)")
- elif c.is_file():
- print(f" OK: {c}")
- else:
- print(f" absent: {c}")
-
- # Also check common config locations.
- cfg_glob = list((CLAUDE_HOME).glob("*.json")) + list((CLAUDE_HOME).glob("*.md"))
- print("\n--- All top-level files in ~/.claude ---")
- for p in sorted(cfg_glob):
- in_backup = p.resolve() in backed_up_sources
- tag = "OK" if in_backup else "MISSING"
- print(f" [{tag:<7}] {p.name} ({p.stat().st_size}B)")
-
- return 0
-
-
-if __name__ == "__main__":
- sys.exit(main())
+"""audit_backup.py -- Summarize a backup snapshot and flag what is missing."""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from collections import Counter
+from pathlib import Path
+
+CLAUDE_HOME = Path(os.path.expanduser("~/.claude"))
+BACKUPS = CLAUDE_HOME / "backups"
+
+
+def latest_snapshot() -> Path:
+ snaps = sorted(p for p in BACKUPS.iterdir() if p.is_dir())
+ return snaps[-1]
+
+
+def main() -> int:
+ snap = Path(sys.argv[1]) if len(sys.argv) > 1 else latest_snapshot()
+ manifest = json.loads((snap / "manifest.json").read_text(encoding="utf-8"))
+
+ print(f"snapshot: {snap}")
+ print(f"entries: {len(manifest['entries'])}")
+ total = sum((e.get("size") or 0) for e in manifest["entries"])
+ print(f"bytes: {total:,}")
+
+ print("\n--- Top-level files ---")
+ for e in manifest["entries"]:
+ d = e["dest"]
+ if "/" not in d and "\\" not in d:
+ print(f" {d:<32} {e['size']:>8}B")
+
+ print("\n--- Tree coverage ---")
+ roots: Counter[str] = Counter()
+ for e in manifest["entries"]:
+ head = e["dest"].replace("\\", "/").split("/", 1)[0]
+ roots[head] += 1
+ for r, c in roots.most_common():
+ print(f" {r:<32} {c:>5} files")
+
+ # Audit what's in ~/.claude but NOT in the backup.
+ print("\n--- Candidate files in ~/.claude NOT backed up ---")
+ backed_up_sources = {Path(e["source"]).resolve() for e in manifest["entries"]}
+ candidates = [
+ CLAUDE_HOME / "skill-system-config.json",
+ CLAUDE_HOME / "intent-log.jsonl",
+ CLAUDE_HOME / "skill-registry.json",
+ CLAUDE_HOME / "CLAUDE.md",
+ CLAUDE_HOME / "claude.json",
+ CLAUDE_HOME / ".claude.json",
+ ]
+ for c in candidates:
+ if c.is_file() and c.resolve() not in backed_up_sources:
+ print(f" MISSING: {c} ({c.stat().st_size}B)")
+ elif c.is_file():
+ print(f" OK: {c}")
+ else:
+ print(f" absent: {c}")
+
+ # Also check common config locations.
+ cfg_glob = list((CLAUDE_HOME).glob("*.json")) + list((CLAUDE_HOME).glob("*.md"))
+ print("\n--- All top-level files in ~/.claude ---")
+ for p in sorted(cfg_glob):
+ in_backup = p.resolve() in backed_up_sources
+ tag = "OK" if in_backup else "MISSING"
+ print(f" [{tag:<7}] {p.name} ({p.stat().st_size}B)")
+
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/ci_classifier.py b/scripts/ci_classifier.py
index 66af653a006721801d278d3ff11ccc800941abed..b0ec35de6c0dd6882ed3b5bd9b7d5eaeacc99155 100644
--- a/scripts/ci_classifier.py
+++ b/scripts/ci_classifier.py
@@ -15,6 +15,7 @@ OUTPUT_NAMES = (
"graph_changed",
"graph_only",
"package_changed",
+ "similarity_changed",
"source_changed",
)
@@ -48,6 +49,18 @@ SOURCE_PATTERNS = (
"scripts/**",
"src/**",
)
+SIMILARITY_PATTERNS = (
+ ".github/workflows/test.yml",
+ "pyproject.toml",
+ "src/config.json",
+ "src/ctx/adapters/claude_code/hooks/context_monitor.py",
+ "src/ctx/adapters/generic/ctx_core_tools.py",
+ "src/ctx/core/graph/**",
+ "src/ctx/core/resolve/**",
+ "src/ctx/core/wiki/wiki_graphify.py",
+ "src/ctx/embedding_backend.py",
+ "src/tests/test_similarity_precision_recall.py",
+)
def _matches(path: str, patterns: Iterable[str]) -> bool:
@@ -67,6 +80,8 @@ def classify_paths(paths: Iterable[str]) -> dict[str, bool]:
"graph_only": graph_only,
"package_changed": ci_changed
or any(_matches(path, PACKAGE_PATTERNS) for path in files),
+ "similarity_changed": ci_changed
+ or any(_matches(path, SIMILARITY_PATTERNS) for path in files),
"source_changed": ci_changed
or any(_matches(path, SOURCE_PATTERNS) for path in files),
}
diff --git a/scripts/ci_no_test_policy.py b/scripts/ci_no_test_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8615c9fb5e077fec8259e890febf9687a2b4f56
--- /dev/null
+++ b/scripts/ci_no_test_policy.py
@@ -0,0 +1,154 @@
+"""Enforce that product/CI contract changes include test changes."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import subprocess
+from dataclasses import dataclass
+from typing import Iterable
+
+RELEASE_METADATA_FILES = {
+ "CHANGELOG.md",
+ "pyproject.toml",
+ "src/__init__.py",
+ "src/ctx/__init__.py",
+}
+VERSION_LINE_RE = re.compile(r'version = "\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?"')
+INIT_VERSION_LINE_RE = re.compile(
+ r'__version__ = "\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?"'
+)
+
+
+@dataclass(frozen=True)
+class PolicyResult:
+ passed: bool
+ message: str
+ contract_files: tuple[str, ...] = ()
+ test_files: tuple[str, ...] = ()
+
+
+def is_contract_file(path: str) -> bool:
+ return (
+ (path.startswith("src/") and path.endswith((".py", ".json")))
+ or path.startswith("scripts/ci_")
+ or path == "scripts/clean_host_contract.py"
+ or path == "pyproject.toml"
+ or path == ".github/workflows/test.yml"
+ ) and not path.startswith("src/tests/")
+
+
+def is_test_file(path: str) -> bool:
+ return path.startswith("src/tests/") and path.endswith((".py", ".json"))
+
+
+def is_release_metadata_only(
+ changed_files: Iterable[str],
+ diffs_by_file: dict[str, str],
+) -> bool:
+ files = tuple(path.strip().replace("\\", "/") for path in changed_files if path)
+ if not files or any(path not in RELEASE_METADATA_FILES for path in files):
+ return False
+
+ for path in files:
+ if path == "CHANGELOG.md":
+ continue
+ expected = VERSION_LINE_RE if path == "pyproject.toml" else INIT_VERSION_LINE_RE
+ for line in diffs_by_file.get(path, "").splitlines():
+ if not line.startswith(("+", "-")) or line.startswith(("+++", "---")):
+ continue
+ if not expected.fullmatch(line[1:].strip()):
+ return False
+ return True
+
+
+def evaluate_policy(
+ changed_files: Iterable[str],
+ labels: Iterable[str],
+ diffs_by_file: dict[str, str],
+) -> PolicyResult:
+ files = tuple(path.strip().replace("\\", "/") for path in changed_files if path)
+ contract = tuple(path for path in files if is_contract_file(path))
+ tests = tuple(path for path in files if is_test_file(path))
+ if not contract:
+ return PolicyResult(True, "No product or CI/package contract changes.")
+ if tests:
+ return PolicyResult(True, "Policy satisfied.", contract, tests)
+ if "no-tests-needed" in set(labels):
+ return PolicyResult(True, "Policy exempted by no-tests-needed label.", contract)
+ if is_release_metadata_only(files, diffs_by_file):
+ return PolicyResult(True, "Policy exempted for release metadata-only changes.", contract)
+ return PolicyResult(False, "Contract files changed without accompanying tests.", contract)
+
+
+def _git_lines(*args: str) -> tuple[str, ...]:
+ proc = subprocess.run(
+ ["git", *args],
+ check=True,
+ text=True,
+ stdout=subprocess.PIPE,
+ )
+ return tuple(line.strip() for line in proc.stdout.splitlines() if line.strip())
+
+
+def _git_text(*args: str) -> str:
+ proc = subprocess.run(
+ ["git", *args],
+ check=True,
+ text=True,
+ stdout=subprocess.PIPE,
+ )
+ return proc.stdout
+
+
+def _changed_files(base: str, head: str) -> tuple[str, ...]:
+ return _git_lines("diff", "--name-only", base, head)
+
+
+def _diffs_by_file(base: str, head: str, files: Iterable[str]) -> dict[str, str]:
+ return {
+ path: _git_text("diff", "--unified=0", base, head, "--", path)
+ for path in files
+ }
+
+
+def _parse_labels(raw: str) -> tuple[str, ...]:
+ try:
+ labels = json.loads(raw)
+ except json.JSONDecodeError:
+ return ()
+ if not isinstance(labels, list):
+ return ()
+ return tuple(label for label in labels if isinstance(label, str))
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--base", required=True)
+ parser.add_argument("--head", required=True)
+ parser.add_argument("--labels-json", default="[]")
+ args = parser.parse_args(argv)
+
+ files = _changed_files(args.base, args.head)
+ result = evaluate_policy(
+ files,
+ _parse_labels(args.labels_json),
+ _diffs_by_file(args.base, args.head, files),
+ )
+ print(result.message)
+ if result.contract_files:
+ print("Contract files:")
+ print("\n".join(result.contract_files))
+ if result.test_files:
+ print("Test files:")
+ print("\n".join(result.test_files))
+ if not result.passed:
+ print("::error::Policy violation - contract files changed but no tests changed.")
+ print("Fix: add/update tests, or use release metadata-only changes.")
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/ci_required.py b/scripts/ci_required.py
index bdd2ef63281e2240c34a130ee437e4b924777ab5..a6d15db805ea882f7e8a5a8fe9bbae130d24c91d 100644
--- a/scripts/ci_required.py
+++ b/scripts/ci_required.py
@@ -8,13 +8,31 @@ from typing import Any
CHEAP_PR_SKIPPABLE_JOBS = {
"clean-host-contract",
+ "contract-compat",
"e2e-canary",
"no-test-no-merge",
"package-build",
"package-smoke",
+ "similarity-integration",
"static",
"unit-linux",
}
+REQUIRED_JOBS = {
+ "browser-security",
+ "classify",
+ "clean-host-contract",
+ "contract-compat",
+ "docs-check",
+ "e2e-canary",
+ "graph-check",
+ "no-test-no-merge",
+ "package-build",
+ "package-smoke",
+ "similarity-integration",
+ "static",
+ "test",
+ "unit-linux",
+}
def _job_output(
@@ -35,6 +53,8 @@ def failed_required_jobs(
event_name: str,
) -> dict[str, str | None]:
failures: dict[str, str | None] = {}
+ for name in sorted(REQUIRED_JOBS - set(needs)):
+ failures[name] = "missing"
docs_only_pr = (
event_name == "pull_request"
and _job_output(needs, "classify", "docs_only") == "true"
@@ -77,6 +97,13 @@ def failed_required_jobs(
and _job_output(needs, "classify", "browser_changed") == "false"
):
continue
+ if (
+ event_name == "pull_request"
+ and name == "similarity-integration"
+ and result == "skipped"
+ and _job_output(needs, "classify", "similarity_changed") == "false"
+ ):
+ continue
if event_name == "pull_request" and name == "test" and result == "skipped":
continue
failures[name] = result
diff --git a/scripts/clean_host_contract.py b/scripts/clean_host_contract.py
index a87b90ec57208b80c35844b0a0348b6ac0b9f786..14f4214ad8afdc21169cc49626462c9d75767e53 100644
--- a/scripts/clean_host_contract.py
+++ b/scripts/clean_host_contract.py
@@ -44,23 +44,23 @@ _LIVE_CLAUDE_AUTH_PREFIX_ENV = (
"VERTEXAI_",
"ANTHROPIC_",
)
-_LIVE_CLAUDE_PLATFORM_ENV = {
- "PATH",
- "Path",
- "PATHEXT",
- "SYSTEMROOT",
+_LIVE_CLAUDE_PLATFORM_ENV = {
+ "PATH",
+ "Path",
+ "PATHEXT",
+ "SYSTEMROOT",
"SystemRoot",
"WINDIR",
"COMSPEC",
- "TEMP",
- "TMP",
-}
-_CLEAN_HOST_PLATFORM_ENV = _LIVE_CLAUDE_PLATFORM_ENV | {
- "LANG",
- "LC_ALL",
- "TZ",
-}
-_EXPECTED_LIVE_CLAUDE_EVENTS = ("PostToolUse", "Stop")
+ "TEMP",
+ "TMP",
+}
+_CLEAN_HOST_PLATFORM_ENV = _LIVE_CLAUDE_PLATFORM_ENV | {
+ "LANG",
+ "LC_ALL",
+ "TZ",
+}
+_EXPECTED_LIVE_CLAUDE_EVENTS = ("PostToolUse", "Stop")
@dataclass(frozen=True)
@@ -165,25 +165,25 @@ def assert_inside(path: Path, root: Path) -> None:
raise AssertionError(f"path escaped temp root: {path} not under {root}")
-def isolated_env(paths: ContractPaths, *, extra_pythonpath: Path | None = None) -> dict[str, str]:
- env = {
- key: value
- for key, value in os.environ.items()
- if key in _CLEAN_HOST_PLATFORM_ENV
- }
- env.update({
- "HOME": str(paths.home),
- "USERPROFILE": str(paths.home),
- "APPDATA": str(paths.appdata),
+def isolated_env(paths: ContractPaths, *, extra_pythonpath: Path | None = None) -> dict[str, str]:
+ env = {
+ key: value
+ for key, value in os.environ.items()
+ if key in _CLEAN_HOST_PLATFORM_ENV
+ }
+ env.update({
+ "HOME": str(paths.home),
+ "USERPROFILE": str(paths.home),
+ "APPDATA": str(paths.appdata),
"LOCALAPPDATA": str(paths.localappdata),
"XDG_CONFIG_HOME": str(paths.xdg_config),
"XDG_CACHE_HOME": str(paths.xdg_cache),
- "PIP_CACHE_DIR": str(paths.pip_cache),
- "PYTHONUTF8": "1",
- })
- if extra_pythonpath is not None:
- env["PYTHONPATH"] = str(extra_pythonpath)
- return env
+ "PIP_CACHE_DIR": str(paths.pip_cache),
+ "PYTHONUTF8": "1",
+ })
+ if extra_pythonpath is not None:
+ env["PYTHONPATH"] = str(extra_pythonpath)
+ return env
def live_claude_env(paths: ContractPaths) -> dict[str, str]:
@@ -289,7 +289,7 @@ def write_fake_claude_cli(fake_modules: Path) -> Path:
"import json\n"
"import os\n"
"import re\n"
- "import subprocess\n"
+ "import subprocess\n"
"import sys\n"
"from pathlib import Path\n\n"
"PAYLOADS = {\n"
@@ -336,16 +336,16 @@ def write_fake_claude_cli(fake_modules: Path) -> Path:
" for event in ('PostToolUse', 'Stop'):\n"
" payload = json.dumps(PAYLOADS[event])\n"
" for command in _commands(settings, event):\n"
- " result = subprocess.run(\n"
- " command,\n"
- " cwd=cwd,\n"
- " env=os.environ.copy(),\n"
- " input=payload,\n"
- " text=True,\n"
- " capture_output=True,\n"
- " check=False,\n"
- " shell=True,\n"
- " )\n"
+ " result = subprocess.run(\n"
+ " command,\n"
+ " cwd=cwd,\n"
+ " env=os.environ.copy(),\n"
+ " input=payload,\n"
+ " text=True,\n"
+ " capture_output=True,\n"
+ " check=False,\n"
+ " shell=True,\n"
+ " )\n"
" records.append({\n"
" 'event': event,\n"
" 'command': command,\n"
@@ -436,11 +436,11 @@ def _assert_fake_claude_hook_output(stdout: str) -> None:
raise AssertionError(f"fake Claude hook smoke did not run {expected}")
-def _quote_command(parts: Sequence[str | Path]) -> str:
- values = [str(part) for part in parts]
- if os.name == "nt":
- return subprocess.list2cmdline(values)
- return " ".join(shlex.quote(part) for part in values)
+def _quote_command(parts: Sequence[str | Path]) -> str:
+ values = [str(part) for part in parts]
+ if os.name == "nt":
+ return subprocess.list2cmdline(values)
+ return " ".join(shlex.quote(part) for part in values)
def write_live_claude_sentinel_script(path: Path) -> None:
diff --git a/scripts/sync_huggingface.py b/scripts/sync_huggingface.py
index 99e23d39ad7ca1c440bb94ef32b2c70688180c8e..7478eda5790ee71ebc0ba0f96e09c7fc9af6a672 100644
--- a/scripts/sync_huggingface.py
+++ b/scripts/sync_huggingface.py
@@ -7,7 +7,6 @@ import argparse
import os
import shutil
import subprocess
-import tarfile
import tempfile
from pathlib import Path
@@ -31,6 +30,12 @@ tags:
"""
+LFS_POINTER_PREFIX = b"version https://git-lfs.github.com/spec/v1"
+HYDRATED_ARTIFACT_MIN_BYTES = {
+ Path("graph/wiki-graph.tar.gz"): 100_000_000,
+ Path("graph/skills-sh-catalog.json.gz"): 1_000_000,
+}
+
def with_hf_repo_card_metadata(readme_text: str) -> str:
"""Return README text with Hugging Face repo-card metadata prepended."""
@@ -50,34 +55,61 @@ def _git(repo: Path, *args: str) -> str:
return subprocess.check_output(["git", *args], cwd=repo, text=True).strip()
-def _export_git_tree(repo: Path, commit: str, export_dir: Path) -> None:
- tar_path = export_dir.parent / "ctx.tar"
- subprocess.run(
- ["git", "archive", "--format=tar", "-o", str(tar_path), commit],
- cwd=repo,
- check=True,
- )
- _extract_regular_members(tar_path, export_dir)
-
-
-def _extract_regular_members(tar_path: Path, export_dir: Path) -> None:
+def _git_bytes(repo: Path, *args: str) -> bytes:
+ return subprocess.check_output(["git", *args], cwd=repo)
+
+
+def _iter_tracked_files(repo: Path) -> list[Path]:
+ output = _git_bytes(repo, "ls-files", "-z")
+ files: list[Path] = []
+ for raw in output.split(b"\0"):
+ if not raw:
+ continue
+ rel = Path(raw.decode("utf-8"))
+ if rel.is_absolute() or ".." in rel.parts:
+ raise ValueError(f"unsafe git path: {rel}")
+ files.append(rel)
+ return files
+
+
+def _assert_hydrated_artifacts(repo: Path) -> None:
+ for rel, min_bytes in HYDRATED_ARTIFACT_MIN_BYTES.items():
+ artifact = repo / rel
+ if not artifact.is_file():
+ raise FileNotFoundError(
+ f"{rel.as_posix()} is required before Hugging Face sync"
+ )
+ size = artifact.stat().st_size
+ if size < min_bytes:
+ raise RuntimeError(
+ f"{rel.as_posix()} is {size:,} bytes; expected at least "
+ f"{min_bytes:,}. Run git lfs pull before publishing."
+ )
+ with artifact.open("rb") as fh:
+ prefix = fh.read(len(LFS_POINTER_PREFIX))
+ if prefix == LFS_POINTER_PREFIX:
+ raise RuntimeError(
+ f"{rel.as_posix()} is a Git LFS pointer, not the hydrated artifact"
+ )
+
+
+def _export_tracked_tree(repo: Path, export_dir: Path) -> None:
+ _assert_hydrated_artifacts(repo)
+ repo_root = repo.resolve()
export_root = export_dir.resolve()
- with tarfile.open(tar_path) as archive:
- for member in archive.getmembers():
- target = (export_root / member.name).resolve()
- if target != export_root and not target.is_relative_to(export_root):
- raise ValueError(f"unsafe tar member path: {member.name}")
- if member.isdir():
- target.mkdir(parents=True, exist_ok=True)
- continue
- if not member.isfile():
- continue
- target.parent.mkdir(parents=True, exist_ok=True)
- source = archive.extractfile(member)
- if source is None:
- continue
- with source, target.open("wb") as dest:
- shutil.copyfileobj(source, dest)
+ for rel in _iter_tracked_files(repo):
+ source = (repo_root / rel).resolve()
+ if source != repo_root and not source.is_relative_to(repo_root):
+ raise ValueError(f"unsafe source path: {rel}")
+ if source.is_symlink():
+ raise ValueError(f"refusing to follow symlink during HF sync: {rel}")
+ if not source.is_file():
+ continue
+ target = (export_root / rel).resolve()
+ if target != export_root and not target.is_relative_to(export_root):
+ raise ValueError(f"unsafe export path: {rel}")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(source, target)
def _patch_export_readme(export_dir: Path) -> None:
@@ -104,7 +136,7 @@ def sync_to_huggingface(
export_dir = workspace / "export"
try:
export_dir.mkdir()
- _export_git_tree(repo, head, export_dir)
+ _export_tracked_tree(repo, export_dir)
_patch_export_readme(export_dir)
api = HfApi(token=token)
api.create_repo(repo_id, repo_type=repo_type, exist_ok=True)
diff --git a/scripts/tune_similarity_thresholds.py b/scripts/tune_similarity_thresholds.py
index 132b3a328709a7ffbc3c01ec9473ce6deb53ac59..1e99bbfc847dd3adca877540933e28f176d2cc89 100644
--- a/scripts/tune_similarity_thresholds.py
+++ b/scripts/tune_similarity_thresholds.py
@@ -1,114 +1,114 @@
-"""
-tune_similarity_thresholds.py -- Sweep thresholds against the fixture corpus
-and print the precision/recall surface so we can pick sensible defaults.
-
-Run once after editing fixtures or changing the embedder; not part of CI.
-"""
-
-from __future__ import annotations
-
-import json
-import sys
-from dataclasses import dataclass
-from pathlib import Path
-
-SRC_DIR = Path(__file__).resolve().parents[1] / "src"
-if str(SRC_DIR) not in sys.path:
- sys.path.insert(0, str(SRC_DIR))
-
-from corpus_cache import CorpusCache # noqa: E402
-from cosine_ranker import CosineRanker # noqa: E402
-from ctx_config import cfg # noqa: E402
-from intake_gate import compose_corpus_text # noqa: E402
-
-FIXTURE_DIR = SRC_DIR / "tests" / "fixtures" / "similarity"
-
-
-@dataclass(frozen=True)
-class _Pair:
- id: str
- label: str
- a_md: str
- b_md: str
-
-
-def _compose_md(entry: dict) -> str:
- return (
- "---\n"
- f"name: {entry['name']}\n"
- f"description: {entry['description']}\n"
- "---\n"
- f"# {entry['name']}\n\n"
- f"{entry['body']}\n"
- )
-
-
-def _load(filename: str) -> list[_Pair]:
- pairs: list[_Pair] = []
- for raw in (FIXTURE_DIR / filename).read_text(encoding="utf-8").splitlines():
- raw = raw.strip()
- if not raw or raw.startswith("#"):
- continue
- e = json.loads(raw)
- pairs.append(_Pair(e["id"], e["label"], _compose_md(e["a"]), _compose_md(e["b"])))
- return pairs
-
-
-def _score(pair: _Pair, embedder, root: Path) -> float:
- cache = CorpusCache(f"tune-{pair.id}", root=root)
- a_text = compose_corpus_text(pair.a_md)
- a_vec = embedder.embed([a_text])[0]
- cache.put(f"{pair.id}-a", a_text, a_vec)
- ranker = CosineRanker.from_cache(cache)
- b_text = compose_corpus_text(pair.b_md)
- b_vec = embedder.embed([b_text])[0]
- top = ranker.topk(b_vec, k=1)
- return float(top[0].score) if top else 0.0
-
-
-def main() -> None:
- import tempfile
-
- embedder = cfg.build_intake_embedder()
- near = _load("near_duplicates.jsonl")
- distinct = _load("distinct_pairs.jsonl")
- adversarial = _load("adversarial.jsonl")
-
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- near_scores = [(p.id, _score(p, embedder, root)) for p in near]
- distinct_scores = [(p.id, _score(p, embedder, root)) for p in distinct]
- adv_scores = [(p.id, _score(p, embedder, root)) for p in adversarial]
-
- print("\n=== Near-duplicate scores (should be HIGH) ===")
- for pid, s in sorted(near_scores, key=lambda x: x[1]):
- print(f" {pid}: {s:.4f}")
- print(f" min={min(s for _, s in near_scores):.4f} "
- f"median={sorted(s for _, s in near_scores)[len(near_scores)//2]:.4f}")
-
- print("\n=== Distinct scores (should be LOW) ===")
- for pid, s in sorted(distinct_scores, key=lambda x: -x[1])[:10]:
- print(f" {pid}: {s:.4f}")
- print(f" max={max(s for _, s in distinct_scores):.4f} "
- f"median={sorted(s for _, s in distinct_scores)[len(distinct_scores)//2]:.4f}")
-
- print("\n=== Adversarial scores (should be LOW — precision traps) ===")
- for pid, s in sorted(adv_scores, key=lambda x: -x[1]):
- print(f" {pid}: {s:.4f}")
- print(f" max={max(s for _, s in adv_scores):.4f}")
-
- # Sweep: at each candidate near_dup threshold, compute P/R assuming a pair
- # is flagged iff top_score >= threshold.
- print("\n=== Threshold sweep (flag if score >= t) ===")
- print(f"{'threshold':>10} {'recall':>8} {'precision':>10} {'TP':>4} {'FN':>4} {'FP':>4}")
- for t in [0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.82, 0.85, 0.88, 0.90, 0.93]:
- tp = sum(1 for _, s in near_scores if s >= t)
- fn = len(near_scores) - tp
- fp = sum(1 for _, s in distinct_scores + adv_scores if s >= t)
- recall = tp / (tp + fn) if (tp + fn) else 0
- precision = tp / (tp + fp) if (tp + fp) else 0
- print(f"{t:>10.2f} {recall:>8.3f} {precision:>10.3f} {tp:>4} {fn:>4} {fp:>4}")
-
-
-if __name__ == "__main__":
- main()
+"""
+tune_similarity_thresholds.py -- Sweep thresholds against the fixture corpus
+and print the precision/recall surface so we can pick sensible defaults.
+
+Run once after editing fixtures or changing the embedder; not part of CI.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+
+SRC_DIR = Path(__file__).resolve().parents[1] / "src"
+if str(SRC_DIR) not in sys.path:
+ sys.path.insert(0, str(SRC_DIR))
+
+from corpus_cache import CorpusCache # noqa: E402
+from cosine_ranker import CosineRanker # noqa: E402
+from ctx_config import cfg # noqa: E402
+from intake_gate import compose_corpus_text # noqa: E402
+
+FIXTURE_DIR = SRC_DIR / "tests" / "fixtures" / "similarity"
+
+
+@dataclass(frozen=True)
+class _Pair:
+ id: str
+ label: str
+ a_md: str
+ b_md: str
+
+
+def _compose_md(entry: dict) -> str:
+ return (
+ "---\n"
+ f"name: {entry['name']}\n"
+ f"description: {entry['description']}\n"
+ "---\n"
+ f"# {entry['name']}\n\n"
+ f"{entry['body']}\n"
+ )
+
+
+def _load(filename: str) -> list[_Pair]:
+ pairs: list[_Pair] = []
+ for raw in (FIXTURE_DIR / filename).read_text(encoding="utf-8").splitlines():
+ raw = raw.strip()
+ if not raw or raw.startswith("#"):
+ continue
+ e = json.loads(raw)
+ pairs.append(_Pair(e["id"], e["label"], _compose_md(e["a"]), _compose_md(e["b"])))
+ return pairs
+
+
+def _score(pair: _Pair, embedder, root: Path) -> float:
+ cache = CorpusCache(f"tune-{pair.id}", root=root)
+ a_text = compose_corpus_text(pair.a_md)
+ a_vec = embedder.embed([a_text])[0]
+ cache.put(f"{pair.id}-a", a_text, a_vec)
+ ranker = CosineRanker.from_cache(cache)
+ b_text = compose_corpus_text(pair.b_md)
+ b_vec = embedder.embed([b_text])[0]
+ top = ranker.topk(b_vec, k=1)
+ return float(top[0].score) if top else 0.0
+
+
+def main() -> None:
+ import tempfile
+
+ embedder = cfg.build_intake_embedder()
+ near = _load("near_duplicates.jsonl")
+ distinct = _load("distinct_pairs.jsonl")
+ adversarial = _load("adversarial.jsonl")
+
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ near_scores = [(p.id, _score(p, embedder, root)) for p in near]
+ distinct_scores = [(p.id, _score(p, embedder, root)) for p in distinct]
+ adv_scores = [(p.id, _score(p, embedder, root)) for p in adversarial]
+
+ print("\n=== Near-duplicate scores (should be HIGH) ===")
+ for pid, s in sorted(near_scores, key=lambda x: x[1]):
+ print(f" {pid}: {s:.4f}")
+ print(f" min={min(s for _, s in near_scores):.4f} "
+ f"median={sorted(s for _, s in near_scores)[len(near_scores)//2]:.4f}")
+
+ print("\n=== Distinct scores (should be LOW) ===")
+ for pid, s in sorted(distinct_scores, key=lambda x: -x[1])[:10]:
+ print(f" {pid}: {s:.4f}")
+ print(f" max={max(s for _, s in distinct_scores):.4f} "
+ f"median={sorted(s for _, s in distinct_scores)[len(distinct_scores)//2]:.4f}")
+
+ print("\n=== Adversarial scores (should be LOW — precision traps) ===")
+ for pid, s in sorted(adv_scores, key=lambda x: -x[1]):
+ print(f" {pid}: {s:.4f}")
+ print(f" max={max(s for _, s in adv_scores):.4f}")
+
+ # Sweep: at each candidate near_dup threshold, compute P/R assuming a pair
+ # is flagged iff top_score >= threshold.
+ print("\n=== Threshold sweep (flag if score >= t) ===")
+ print(f"{'threshold':>10} {'recall':>8} {'precision':>10} {'TP':>4} {'FN':>4} {'FP':>4}")
+ for t in [0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.82, 0.85, 0.88, 0.90, 0.93]:
+ tp = sum(1 for _, s in near_scores if s >= t)
+ fn = len(near_scores) - tp
+ fp = sum(1 for _, s in distinct_scores + adv_scores if s >= t)
+ recall = tp / (tp + fn) if (tp + fn) else 0
+ precision = tp / (tp + fp) if (tp + fp) else 0
+ print(f"{t:>10.2f} {recall:>8.3f} {precision:>10.3f} {tp:>4} {fn:>4} {fp:>4}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/__init__.py b/src/__init__.py
index ac5808a9da4fedb17e48c85bce188effe49b1c53..1c8adcbb2f7ec3dbd678f435d6db91847a379083 100644
--- a/src/__init__.py
+++ b/src/__init__.py
@@ -1,3 +1,3 @@
"""ctx — skill and agent recommendation for Claude Code."""
-__version__ = "0.7.3"
+__version__ = "0.7.5"
diff --git a/src/agent_add.py b/src/agent_add.py
index 6ac25fc02ae72b3de3da0e180fe16d2ec79612b5..b1075010f05ca84a66933daceb0838a08390e2e8 100644
--- a/src/agent_add.py
+++ b/src/agent_add.py
@@ -24,17 +24,17 @@ import argparse
import os
import sys
from datetime import datetime, timezone
-from pathlib import Path
-
-from ctx.core.entity_update import build_update_review, render_update_review
-from ctx_config import cfg
-from ctx.adapters.claude_code.install.install_utils import safe_copy_file
-from intake_pipeline import IntakeRejected, check_intake, record_embedding
-from wiki_batch_entities import generate_agent_page
-from ctx.core.wiki.wiki_queue import enqueue_entity_upsert
-from ctx.core.wiki.wiki_sync import append_log, ensure_wiki, update_index
-from ctx.core.wiki.wiki_utils import validate_skill_name
-from ctx.utils._fs_utils import reject_symlink_path, safe_atomic_write_text
+from pathlib import Path
+
+from ctx.core.entity_update import build_update_review, render_update_review
+from ctx_config import cfg
+from ctx.adapters.claude_code.install.install_utils import safe_copy_file
+from intake_pipeline import IntakeRejected, check_intake, record_embedding
+from wiki_batch_entities import generate_agent_page
+from ctx.core.wiki.wiki_queue import enqueue_entity_upsert
+from ctx.core.wiki.wiki_sync import append_log, ensure_wiki, update_index
+from ctx.core.wiki.wiki_utils import validate_skill_name
+from ctx.utils._fs_utils import reject_symlink_path, safe_atomic_write_text
TODAY = datetime.now(timezone.utc).strftime("%Y-%m-%d")
@@ -53,24 +53,24 @@ def install_agent(source: Path, agents_dir: Path, name: str) -> Path:
return dest
-def write_entity_page(wiki_path: Path, name: str, content: str) -> bool:
- """Write agent entity page. Returns True if newly created."""
- page = wiki_path / "entities" / "agents" / f"{name}.md"
- reject_symlink_path(page)
- is_new = not page.exists()
- safe_atomic_write_text(page, content, encoding="utf-8")
- return is_new
-
-
-def add_agent(
- *,
- source_path: Path,
- name: str,
- wiki_path: Path,
- agents_dir: Path,
- review_existing: bool = False,
- update_existing: bool = False,
-) -> dict:
+def write_entity_page(wiki_path: Path, name: str, content: str) -> bool:
+ """Write agent entity page. Returns True if newly created."""
+ page = wiki_path / "entities" / "agents" / f"{name}.md"
+ reject_symlink_path(page)
+ is_new = not page.exists()
+ safe_atomic_write_text(page, content, encoding="utf-8")
+ return is_new
+
+
+def add_agent(
+ *,
+ source_path: Path,
+ name: str,
+ wiki_path: Path,
+ agents_dir: Path,
+ review_existing: bool = False,
+ update_existing: bool = False,
+) -> dict:
"""Add a single agent: validate, gate, install, ingest, log.
Returns a result dict with keys: name, installed, is_new_page.
@@ -83,48 +83,48 @@ def add_agent(
f"agent file too large ({file_size:,} bytes). Max "
f"{_MAX_AGENT_BYTES:,}. Trim before ingestion."
)
-
- content = source_path.read_text(encoding="utf-8", errors="replace")
- line_count = len(content.splitlines())
-
- installed_path = agents_dir / f"{name}.md"
- entity_page = wiki_path / "entities" / "agents" / f"{name}.md"
- existing_path = (
- installed_path
- if installed_path.exists()
- else entity_page if entity_page.exists() else None
- )
- has_existing = existing_path is not None
-
- if review_existing and has_existing and not update_existing:
- assert existing_path is not None
- existing_text = existing_path.read_text(encoding="utf-8", errors="replace")
- review = build_update_review(
- entity_type="agent",
- slug=name,
- existing_text=existing_text,
- proposed_text=content,
- )
- return {
- "name": name,
- "installed": str(installed_path),
- "is_new_page": False,
- "skipped": True,
- "update_required": True,
- "update_review": render_update_review(review),
- }
-
- decision = None
- if not has_existing:
- # Intake gate: reject broken/duplicate agents before we install.
- # Existing updates bypass similarity intake because they compare
- # against their own cached embedding.
- decision = check_intake(content, "agents")
- if not decision.allow:
- raise IntakeRejected(decision)
-
- # 1. Install into agents-dir.
- installed_path = install_agent(source_path, agents_dir, name)
+
+ content = source_path.read_text(encoding="utf-8", errors="replace")
+ line_count = len(content.splitlines())
+
+ installed_path = agents_dir / f"{name}.md"
+ entity_page = wiki_path / "entities" / "agents" / f"{name}.md"
+ existing_path = (
+ installed_path
+ if installed_path.exists()
+ else entity_page if entity_page.exists() else None
+ )
+ has_existing = existing_path is not None
+
+ if review_existing and has_existing and not update_existing:
+ assert existing_path is not None
+ existing_text = existing_path.read_text(encoding="utf-8", errors="replace")
+ review = build_update_review(
+ entity_type="agent",
+ slug=name,
+ existing_text=existing_text,
+ proposed_text=content,
+ )
+ return {
+ "name": name,
+ "installed": str(installed_path),
+ "is_new_page": False,
+ "skipped": True,
+ "update_required": True,
+ "update_review": render_update_review(review),
+ }
+
+ decision = None
+ if not has_existing:
+ # Intake gate: reject broken/duplicate agents before we install.
+ # Existing updates bypass similarity intake because they compare
+ # against their own cached embedding.
+ decision = check_intake(content, "agents")
+ if not decision.allow:
+ raise IntakeRejected(decision)
+
+ # 1. Install into agents-dir.
+ installed_path = install_agent(source_path, agents_dir, name)
# 2. Record embedding. Non-fatal on failure — install already
# succeeded and a missing vector only weakens the next check.
@@ -150,30 +150,30 @@ def add_agent(
f"Installed: {installed_path}",
f"Lines: {line_count}",
]
- warnings = decision.warnings if decision is not None else ()
- if warnings:
- log_details.append(
- "Warnings: " + "; ".join(f"{w.code}:{w.message}" for w in warnings)
- )
- append_log(str(wiki_path), "add-agent", name, log_details)
- queue_job = enqueue_entity_upsert(
- wiki_path,
- entity_type="agent",
- slug=name,
- entity_path=wiki_path / "entities" / "agents" / f"{name}.md",
- content=page_content,
- action="created" if is_new else "updated",
- source="agent_add",
- )
-
- return {
- "name": name,
- "installed": str(installed_path),
- "is_new_page": is_new,
- "skipped": False,
- "update_required": False,
- "queued_job_id": queue_job.id,
- }
+ warnings = decision.warnings if decision is not None else ()
+ if warnings:
+ log_details.append(
+ "Warnings: " + "; ".join(f"{w.code}:{w.message}" for w in warnings)
+ )
+ append_log(str(wiki_path), "add-agent", name, log_details)
+ queue_job = enqueue_entity_upsert(
+ wiki_path,
+ entity_type="agent",
+ slug=name,
+ entity_path=wiki_path / "entities" / "agents" / f"{name}.md",
+ content=page_content,
+ action="created" if is_new else "updated",
+ source="agent_add",
+ )
+
+ return {
+ "name": name,
+ "installed": str(installed_path),
+ "is_new_page": is_new,
+ "skipped": False,
+ "update_required": False,
+ "queued_job_id": queue_job.id,
+ }
# ── CLI ───────────────────────────────────────────────────────────────
@@ -186,16 +186,16 @@ def main() -> None:
"--scan-dir",
help="Directory of agent .md files to batch-add (non-recursive)",
)
- parser.add_argument(
- "--skip-existing",
- action="store_true",
- help="Skip agents already installed (prevents overwrites)",
- )
- parser.add_argument(
- "--update-existing",
- action="store_true",
- help="Apply the reviewed replacement when an agent already exists",
- )
+ parser.add_argument(
+ "--skip-existing",
+ action="store_true",
+ help="Skip agents already installed (prevents overwrites)",
+ )
+ parser.add_argument(
+ "--update-existing",
+ action="store_true",
+ help="Apply the reviewed replacement when an agent already exists",
+ )
parser.add_argument("--wiki", default=str(cfg.wiki_dir), help="Wiki path")
parser.add_argument(
"--agents-dir",
@@ -245,7 +245,7 @@ def main() -> None:
print(f"No agent .md files found under {scan_root}.", file=sys.stderr)
sys.exit(0)
- added = updated = skipped = rejected = errors = 0
+ added = updated = skipped = rejected = errors = 0
total = len(candidates)
for i, (source_path, name) in enumerate(candidates, 1):
if args.skip_existing and (agents_dir / f"{name}.md").exists():
@@ -254,27 +254,27 @@ def main() -> None:
print(f" [{i}/{total}] [skipped] {name}")
continue
try:
- result = add_agent(
- source_path=source_path,
- name=name,
- wiki_path=wiki_path,
- agents_dir=agents_dir,
- review_existing=True,
- update_existing=args.update_existing,
- )
- if result.get("skipped"):
- skipped += 1
- if result.get("update_review"):
- print(result["update_review"])
- print(f" [{i}/{total}] [update-review] {name}")
- continue
- if result["is_new_page"]:
- added += 1
- status = "installed"
- else:
- updated += 1
- status = "updated"
- print(f" [{i}/{total}] [{status}] {name}")
+ result = add_agent(
+ source_path=source_path,
+ name=name,
+ wiki_path=wiki_path,
+ agents_dir=agents_dir,
+ review_existing=True,
+ update_existing=args.update_existing,
+ )
+ if result.get("skipped"):
+ skipped += 1
+ if result.get("update_review"):
+ print(result["update_review"])
+ print(f" [{i}/{total}] [update-review] {name}")
+ continue
+ if result["is_new_page"]:
+ added += 1
+ status = "installed"
+ else:
+ updated += 1
+ status = "updated"
+ print(f" [{i}/{total}] [{status}] {name}")
except IntakeRejected as exc:
rejected += 1
codes = ", ".join(f.code for f in exc.decision.failures) or "unknown"
@@ -283,10 +283,10 @@ def main() -> None:
errors += 1
print(f" [{i}/{total}] ERROR: {name}: {exc}", file=sys.stderr)
- print(
- f"\nDone: {added} added, {updated} updated, {skipped} skipped, "
- f"{rejected} rejected, {errors} errors"
- )
+ print(
+ f"\nDone: {added} added, {updated} updated, {skipped} skipped, "
+ f"{rejected} rejected, {errors} errors"
+ )
if __name__ == "__main__":
diff --git a/src/backup_config.py b/src/backup_config.py
index e6305023976b0e5e161811224d32f3ab05c316b0..e022a1165ed6b68211db6d63a407bd075dc575a4 100644
--- a/src/backup_config.py
+++ b/src/backup_config.py
@@ -1,295 +1,295 @@
-"""
-backup_config.py -- Schema + loader for the backup mirror system.
-
-Defines what gets backed up, where snapshots go, how they're named, and
-retention policy. The schema is loaded from two sources (deep-merged):
-
- 1. src/config.json::backup — repo default (checked in)
- 2. ~/.claude/backup-config.json — user override (optional)
-
-User values take precedence. Missing keys fall back to dataclass defaults
-so the backup system works out-of-the-box even with zero configuration.
-
-ALWAYS_EXCLUDE is a hard-coded safety net: any name in this set is
-dropped from ``top_files`` regardless of what the config says. This is
-how we prevent ``.credentials.json`` or auth caches from ever ending up
-in a snapshot even if a user's config accidentally lists them.
-"""
-
-from __future__ import annotations
-
-import json
-import os
-from dataclasses import dataclass, field
-from pathlib import Path
-from typing import Any
-
-
-# Files we refuse to ever copy, even if the user lists them. These
-# contain live auth tokens or ephemeral machine state that would either
-# leak credentials or become stale the moment a snapshot is taken.
-ALWAYS_EXCLUDE: frozenset[str] = frozenset({
- ".credentials.json",
- "mcp-needs-auth-cache.json",
- "stats-cache.json",
- "claude.json",
- ".claude.json",
-})
-
-_ALLOWED_SCOPES: frozenset[str] = frozenset({"full", "incremental", "hybrid"})
-
-
-# ── Schema ──────────────────────────────────────────────────────────────────
-
-
-@dataclass(frozen=True)
-class BackupTree:
- """A directory tree to mirror into each snapshot."""
-
- src: str # relative to claude_home, e.g. "agents"
- dest: str # relative to snapshot root, e.g. "agents"
-
-
-@dataclass(frozen=True)
-class BackupRetention:
- """How many snapshots survive automatic pruning."""
-
- keep_latest: int = 50
- keep_daily: int = 14
-
-
-@dataclass(frozen=True)
-class BackupConfig:
- """Full backup system configuration.
-
- Path fields store the raw string (``~`` and ``$VARS`` unexpanded) so
- the config round-trips through JSON without mutation. Use
- :meth:`snapshot_dir_resolved` to get a materialized ``Path``.
- """
-
- snapshot_dir: str = "~/.claude/backups"
- # Two placeholders: ``{timestamp}`` required, ``{reason}`` optional.
- # The Phase 2 CLI will format reason from ``--reason
"
"
"
# Left sidebar
"
"
@@ -2390,6 +2449,53 @@ class _MonitorHandler(BaseHTTPRequestHandler):
and secrets.compare_digest(token, _MONITOR_TOKEN)
)
+ def _content_length(self) -> int | None:
+ raw = self.headers.get("Content-Length")
+ if raw is None:
+ return 0
+ try:
+ length = int(raw)
+ except ValueError:
+ self._send_json_status(400, {"detail": "invalid Content-Length"})
+ return None
+ if length < 0:
+ self._send_json_status(400, {"detail": "invalid Content-Length"})
+ return None
+ if length > _MAX_POST_BODY_BYTES:
+ self._send_json_status(413, {"detail": "JSON body too large"})
+ return None
+ return length
+
+ def _read_json_body(self) -> dict[str, Any] | None:
+ content_type = self.headers.get("Content-Type", "").split(";", 1)[0]
+ if content_type.lower() != "application/json":
+ self._send_json_status(415, {"detail": "JSON body required"})
+ return None
+ length = self._content_length()
+ if length is None:
+ return None
+ raw = self.rfile.read(length) if length else b""
+ try:
+ body = json.loads(raw.decode("utf-8")) if raw else {}
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ self._send_json_status(400, {"detail": "invalid JSON body"})
+ return None
+ if not isinstance(body, dict):
+ self._send_json_status(400, {"detail": "JSON object body required"})
+ return None
+ return body
+
+ def _discard_small_body(self) -> None:
+ raw = self.headers.get("Content-Length")
+ if raw is None:
+ return
+ try:
+ length = int(raw)
+ except ValueError:
+ return
+ if 0 < length <= _MAX_POST_BODY_BYTES:
+ self.rfile.read(length)
+
def do_GET(self) -> None: # noqa: N802 — stdlib signature
# Parse once so we can reuse the query string for /graph?slug=…
raw_path, _, raw_query = self.path.partition("?")
@@ -2476,31 +2582,26 @@ class _MonitorHandler(BaseHTTPRequestHandler):
"""Mutation endpoints. Same-origin only; JSON body required."""
path = self.path.split("?", 1)[0]
try:
- length = int(self.headers.get("Content-Length") or 0)
- raw = self.rfile.read(length) if length else b""
if not self._mutations_enabled():
+ self._discard_small_body()
self._send_json_status(
403, {"detail": "monitor mutations disabled on non-loopback bind"},
)
return
if not self._same_origin():
+ self._discard_small_body()
self._send_json_status(
403, {"detail": "cross-origin POST denied"},
)
return
if not self._mutation_authorized():
+ self._discard_small_body()
self._send_json_status(
403, {"detail": "monitor token required"},
)
return
- content_type = self.headers.get("Content-Type", "").split(";", 1)[0]
- if content_type.lower() != "application/json":
- self._send_json_status(415, {"detail": "JSON body required"})
- return
- try:
- body = json.loads(raw.decode("utf-8")) if raw else {}
- except (UnicodeDecodeError, json.JSONDecodeError):
- self._send_json_status(400, {"detail": "invalid JSON body"})
+ body = self._read_json_body()
+ if body is None:
return
if path == "/api/load":
diff --git a/src/embedding_backend.py b/src/embedding_backend.py
index 2f633914ba14164c31bf9a69740aa051f59a85f0..86f30eb5947a94a2e9410978ba3d494284bbc570 100644
--- a/src/embedding_backend.py
+++ b/src/embedding_backend.py
@@ -1,233 +1,233 @@
-#!/usr/bin/env python3
-"""
-embedding_backend.py -- Pluggable embedding backends for the intake gate.
-
-Two backends ship in Phase 2:
-
- - SentenceTransformerEmbedder default, zero external daemon.
- Uses sentence-transformers/all-MiniLM-L6-v2.
- - OllamaEmbedder opt-in, requires a local ollama daemon with
- `nomic-embed-text` pulled.
-
-The ``Embedder`` Protocol lets the rest of the intake gate stay
-backend-agnostic. Both implementations return L2-normalised float32 vectors
-so downstream cosine similarity is a single dot product.
-
-Backend selection is centralised in ``get_embedder(name)``; callers pass the
-string from ``ctx_config.intake.embedding.backend``. Heavy imports
-(``sentence_transformers``, ``requests``) happen lazily inside the concrete
-class to keep the module cheap to import.
-
-Security:
-
- ``OllamaEmbedder`` only talks to a locally-bound host (localhost /
- 127.0.0.1 / ::1) to prevent SSRF via a poisoned config pointing the
- embedder at internal metadata endpoints. Non-http(s) schemes are
- rejected. To reach a non-local ollama deployment, callers must opt in
- explicitly by passing ``allow_remote=True`` — this is a deliberate
- friction surface.
-"""
-
-from __future__ import annotations
-
-import os
-from dataclasses import dataclass, field
-from typing import Any, Protocol, Sequence, runtime_checkable
-from urllib.parse import urlparse
-
-import numpy as np
-
-
-DEFAULT_ST_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
-DEFAULT_OLLAMA_MODEL = "nomic-embed-text"
-DEFAULT_OLLAMA_URL = "http://localhost:11434"
-_ST_ENCODE_BATCH_SIZE = 512
-
-# Output dim of nomic-embed-text at the version tested against. Kept as
-# a named constant so a future upstream dim change only needs one edit.
-_NOMIC_EMBED_TEXT_DIM = 768
-_LOCAL_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
-
-
-@runtime_checkable
-class Embedder(Protocol):
- """One method: embed a batch of texts to a 2-D float32 matrix.
-
- ``dim`` and ``name`` are declared as ``@property`` so implementations are
- free to compute them lazily — important because models can be expensive
- to load and callers shouldn't pay that cost just to introspect metadata.
- """
-
- @property
- def dim(self) -> int: ...
-
- @property
- def name(self) -> str: ...
-
- def embed(self, texts: Sequence[str]) -> np.ndarray: ...
-
-
-def _l2_normalize(mat: np.ndarray) -> np.ndarray:
- """Row-wise L2 normalisation with zero-vector safety."""
- norms = np.linalg.norm(mat, axis=1, keepdims=True)
- norms = np.where(norms == 0.0, 1.0, norms)
- return (mat / norms).astype(np.float32, copy=False)
-
-
-@dataclass
-class SentenceTransformerEmbedder:
- """Local-only embedder; loads the model on first ``embed`` call."""
-
- model_name: str = DEFAULT_ST_MODEL
- # ``init=False`` keeps the lazy model out of the generated __init__
- # so callers can't inject a fake model via the constructor.
- _model: Any = field(init=False, default=None, repr=False, compare=False)
-
- @property
- def name(self) -> str:
- return f"sentence-transformers:{self.model_name}"
-
- @property
- def dim(self) -> int:
- # Returns -1 until the model has been loaded (first ``embed`` call).
- # This keeps the attribute cheap to touch — important for
- # ``runtime_checkable`` ``Protocol`` ``isinstance`` checks, which call
- # ``hasattr`` on every declared attribute.
- if self._model is None:
- return -1
- return int(self._model.get_sentence_embedding_dimension())
-
- def _ensure_loaded(self) -> None:
- if self._model is not None:
- return
- try:
- from sentence_transformers import SentenceTransformer # type: ignore[import-not-found]
- except ImportError as exc:
- raise RuntimeError(
- "sentence-transformers is not installed; "
- "pip install sentence-transformers or switch intake.embedding.backend "
- "to 'ollama'"
- ) from exc
- self._model = SentenceTransformer(self.model_name)
-
- def embed(self, texts: Sequence[str]) -> np.ndarray:
- if not texts:
- return np.zeros((0, 0), dtype=np.float32)
- self._ensure_loaded()
- vecs = self._model.encode(
- list(texts),
- batch_size=min(len(texts), _ST_ENCODE_BATCH_SIZE),
- convert_to_numpy=True,
- normalize_embeddings=False,
- show_progress_bar=False,
- )
- return _l2_normalize(np.asarray(vecs, dtype=np.float32))
-
-
-class OllamaEmbedderError(RuntimeError):
- """Raised when an Ollama request fails. Carries the failing text index."""
-
- def __init__(self, index: int, message: str) -> None:
- super().__init__(f"[text #{index}] {message}")
- self.index = index
-
-
-@dataclass
-class OllamaEmbedder:
- """HTTP-backed embedder for a local ollama daemon. Opt-in.
-
- Partial failures fail fast: if text *k* of *N* errors, an
- ``OllamaEmbedderError`` is raised with ``.index == k`` and no
- partial batch is returned. Callers who want best-effort behaviour
- must wrap single-text calls themselves.
- """
-
- model_name: str = DEFAULT_OLLAMA_MODEL
- base_url: str = DEFAULT_OLLAMA_URL
- timeout: float = 30.0
- allow_remote: bool = False
-
- def __post_init__(self) -> None:
- parsed = urlparse(self.base_url)
- if parsed.scheme not in ("http", "https"):
- raise ValueError(
- f"base_url scheme must be http or https: {self.base_url!r}"
- )
- host = (parsed.hostname or "").lower()
- if not host:
- raise ValueError(f"base_url has no host: {self.base_url!r}")
- if not self.allow_remote and host not in _LOCAL_HOSTS:
- raise ValueError(
- f"base_url host {host!r} is not local; pass allow_remote=True "
- f"to explicitly allow a remote ollama instance"
- )
-
- @property
- def name(self) -> str:
- return f"ollama:{self.model_name}"
-
- @property
- def dim(self) -> int:
- # Only known after the first successful call; nomic-embed-text's
- # output dim is stable at the version we test against. Callers
- # that need dim up front should do a one-token warmup embed.
- return _NOMIC_EMBED_TEXT_DIM if self.model_name == DEFAULT_OLLAMA_MODEL else -1
-
- def embed(self, texts: Sequence[str]) -> np.ndarray:
- if not texts:
- return np.zeros((0, 0), dtype=np.float32)
- try:
- import requests # type: ignore[import-untyped]
- except ImportError as exc:
- raise RuntimeError(
- "requests is required for the ollama backend; pip install requests"
- ) from exc
-
- url = f"{self.base_url.rstrip('/')}/api/embeddings"
- rows: list[list[float]] = []
- for idx, text in enumerate(texts):
- try:
- resp = requests.post(
- url,
- json={"model": self.model_name, "prompt": text},
- timeout=self.timeout,
- )
- resp.raise_for_status()
- payload = resp.json()
- except Exception as exc:
- raise OllamaEmbedderError(idx, str(exc)) from exc
- if "embedding" not in payload:
- raise OllamaEmbedderError(
- idx, f"response missing 'embedding' key: {payload!r}"
- )
- rows.append(payload["embedding"])
- return _l2_normalize(np.asarray(rows, dtype=np.float32))
-
-
-def get_embedder(
- backend: str = "sentence-transformers",
- *,
- model: str | None = None,
- base_url: str | None = None,
- allow_remote: bool = False,
-) -> Embedder:
- """Factory: map a backend name to a concrete ``Embedder``.
-
- The default is ``sentence-transformers`` (no external daemon required).
- ``ollama`` is opt-in and requires the user to have ollama running with the
- chosen model pulled. ``allow_remote`` must be set explicitly to reach a
- non-local ollama host.
- """
- key = (backend or "").strip().lower()
- if key in ("", "sentence-transformers", "st", "sbert"):
- return SentenceTransformerEmbedder(model_name=model or DEFAULT_ST_MODEL)
- if key in ("ollama", "ol"):
- return OllamaEmbedder(
- model_name=model or DEFAULT_OLLAMA_MODEL,
- base_url=base_url or os.environ.get("OLLAMA_URL", DEFAULT_OLLAMA_URL),
- allow_remote=allow_remote,
- )
- raise ValueError(
- f"unknown embedding backend {backend!r}; expected "
- f"'sentence-transformers' or 'ollama'"
- )
+#!/usr/bin/env python3
+"""
+embedding_backend.py -- Pluggable embedding backends for the intake gate.
+
+Two backends ship in Phase 2:
+
+ - SentenceTransformerEmbedder default, zero external daemon.
+ Uses sentence-transformers/all-MiniLM-L6-v2.
+ - OllamaEmbedder opt-in, requires a local ollama daemon with
+ `nomic-embed-text` pulled.
+
+The ``Embedder`` Protocol lets the rest of the intake gate stay
+backend-agnostic. Both implementations return L2-normalised float32 vectors
+so downstream cosine similarity is a single dot product.
+
+Backend selection is centralised in ``get_embedder(name)``; callers pass the
+string from ``ctx_config.intake.embedding.backend``. Heavy imports
+(``sentence_transformers``, ``requests``) happen lazily inside the concrete
+class to keep the module cheap to import.
+
+Security:
+
+ ``OllamaEmbedder`` only talks to a locally-bound host (localhost /
+ 127.0.0.1 / ::1) to prevent SSRF via a poisoned config pointing the
+ embedder at internal metadata endpoints. Non-http(s) schemes are
+ rejected. To reach a non-local ollama deployment, callers must opt in
+ explicitly by passing ``allow_remote=True`` — this is a deliberate
+ friction surface.
+"""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass, field
+from typing import Any, Protocol, Sequence, runtime_checkable
+from urllib.parse import urlparse
+
+import numpy as np
+
+
+DEFAULT_ST_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
+DEFAULT_OLLAMA_MODEL = "nomic-embed-text"
+DEFAULT_OLLAMA_URL = "http://localhost:11434"
+_ST_ENCODE_BATCH_SIZE = 512
+
+# Output dim of nomic-embed-text at the version tested against. Kept as
+# a named constant so a future upstream dim change only needs one edit.
+_NOMIC_EMBED_TEXT_DIM = 768
+_LOCAL_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
+
+
+@runtime_checkable
+class Embedder(Protocol):
+ """One method: embed a batch of texts to a 2-D float32 matrix.
+
+ ``dim`` and ``name`` are declared as ``@property`` so implementations are
+ free to compute them lazily — important because models can be expensive
+ to load and callers shouldn't pay that cost just to introspect metadata.
+ """
+
+ @property
+ def dim(self) -> int: ...
+
+ @property
+ def name(self) -> str: ...
+
+ def embed(self, texts: Sequence[str]) -> np.ndarray: ...
+
+
+def _l2_normalize(mat: np.ndarray) -> np.ndarray:
+ """Row-wise L2 normalisation with zero-vector safety."""
+ norms = np.linalg.norm(mat, axis=1, keepdims=True)
+ norms = np.where(norms == 0.0, 1.0, norms)
+ return (mat / norms).astype(np.float32, copy=False)
+
+
+@dataclass
+class SentenceTransformerEmbedder:
+ """Local-only embedder; loads the model on first ``embed`` call."""
+
+ model_name: str = DEFAULT_ST_MODEL
+ # ``init=False`` keeps the lazy model out of the generated __init__
+ # so callers can't inject a fake model via the constructor.
+ _model: Any = field(init=False, default=None, repr=False, compare=False)
+
+ @property
+ def name(self) -> str:
+ return f"sentence-transformers:{self.model_name}"
+
+ @property
+ def dim(self) -> int:
+ # Returns -1 until the model has been loaded (first ``embed`` call).
+ # This keeps the attribute cheap to touch — important for
+ # ``runtime_checkable`` ``Protocol`` ``isinstance`` checks, which call
+ # ``hasattr`` on every declared attribute.
+ if self._model is None:
+ return -1
+ return int(self._model.get_sentence_embedding_dimension())
+
+ def _ensure_loaded(self) -> None:
+ if self._model is not None:
+ return
+ try:
+ from sentence_transformers import SentenceTransformer # type: ignore[import-not-found]
+ except ImportError as exc:
+ raise RuntimeError(
+ "sentence-transformers is not installed; "
+ "pip install sentence-transformers or switch intake.embedding.backend "
+ "to 'ollama'"
+ ) from exc
+ self._model = SentenceTransformer(self.model_name)
+
+ def embed(self, texts: Sequence[str]) -> np.ndarray:
+ if not texts:
+ return np.zeros((0, 0), dtype=np.float32)
+ self._ensure_loaded()
+ vecs = self._model.encode(
+ list(texts),
+ batch_size=min(len(texts), _ST_ENCODE_BATCH_SIZE),
+ convert_to_numpy=True,
+ normalize_embeddings=False,
+ show_progress_bar=False,
+ )
+ return _l2_normalize(np.asarray(vecs, dtype=np.float32))
+
+
+class OllamaEmbedderError(RuntimeError):
+ """Raised when an Ollama request fails. Carries the failing text index."""
+
+ def __init__(self, index: int, message: str) -> None:
+ super().__init__(f"[text #{index}] {message}")
+ self.index = index
+
+
+@dataclass
+class OllamaEmbedder:
+ """HTTP-backed embedder for a local ollama daemon. Opt-in.
+
+ Partial failures fail fast: if text *k* of *N* errors, an
+ ``OllamaEmbedderError`` is raised with ``.index == k`` and no
+ partial batch is returned. Callers who want best-effort behaviour
+ must wrap single-text calls themselves.
+ """
+
+ model_name: str = DEFAULT_OLLAMA_MODEL
+ base_url: str = DEFAULT_OLLAMA_URL
+ timeout: float = 30.0
+ allow_remote: bool = False
+
+ def __post_init__(self) -> None:
+ parsed = urlparse(self.base_url)
+ if parsed.scheme not in ("http", "https"):
+ raise ValueError(
+ f"base_url scheme must be http or https: {self.base_url!r}"
+ )
+ host = (parsed.hostname or "").lower()
+ if not host:
+ raise ValueError(f"base_url has no host: {self.base_url!r}")
+ if not self.allow_remote and host not in _LOCAL_HOSTS:
+ raise ValueError(
+ f"base_url host {host!r} is not local; pass allow_remote=True "
+ f"to explicitly allow a remote ollama instance"
+ )
+
+ @property
+ def name(self) -> str:
+ return f"ollama:{self.model_name}"
+
+ @property
+ def dim(self) -> int:
+ # Only known after the first successful call; nomic-embed-text's
+ # output dim is stable at the version we test against. Callers
+ # that need dim up front should do a one-token warmup embed.
+ return _NOMIC_EMBED_TEXT_DIM if self.model_name == DEFAULT_OLLAMA_MODEL else -1
+
+ def embed(self, texts: Sequence[str]) -> np.ndarray:
+ if not texts:
+ return np.zeros((0, 0), dtype=np.float32)
+ try:
+ import requests # type: ignore[import-untyped]
+ except ImportError as exc:
+ raise RuntimeError(
+ "requests is required for the ollama backend; pip install requests"
+ ) from exc
+
+ url = f"{self.base_url.rstrip('/')}/api/embeddings"
+ rows: list[list[float]] = []
+ for idx, text in enumerate(texts):
+ try:
+ resp = requests.post(
+ url,
+ json={"model": self.model_name, "prompt": text},
+ timeout=self.timeout,
+ )
+ resp.raise_for_status()
+ payload = resp.json()
+ except Exception as exc:
+ raise OllamaEmbedderError(idx, str(exc)) from exc
+ if "embedding" not in payload:
+ raise OllamaEmbedderError(
+ idx, f"response missing 'embedding' key: {payload!r}"
+ )
+ rows.append(payload["embedding"])
+ return _l2_normalize(np.asarray(rows, dtype=np.float32))
+
+
+def get_embedder(
+ backend: str = "sentence-transformers",
+ *,
+ model: str | None = None,
+ base_url: str | None = None,
+ allow_remote: bool = False,
+) -> Embedder:
+ """Factory: map a backend name to a concrete ``Embedder``.
+
+ The default is ``sentence-transformers`` (no external daemon required).
+ ``ollama`` is opt-in and requires the user to have ollama running with the
+ chosen model pulled. ``allow_remote`` must be set explicitly to reach a
+ non-local ollama host.
+ """
+ key = (backend or "").strip().lower()
+ if key in ("", "sentence-transformers", "st", "sbert"):
+ return SentenceTransformerEmbedder(model_name=model or DEFAULT_ST_MODEL)
+ if key in ("ollama", "ol"):
+ return OllamaEmbedder(
+ model_name=model or DEFAULT_OLLAMA_MODEL,
+ base_url=base_url or os.environ.get("OLLAMA_URL", DEFAULT_OLLAMA_URL),
+ allow_remote=allow_remote,
+ )
+ raise ValueError(
+ f"unknown embedding backend {backend!r}; expected "
+ f"'sentence-transformers' or 'ollama'"
+ )
diff --git a/src/flatten_agents.py b/src/flatten_agents.py
index b7e71a75f6100ef7043a60e1254f0bed1118273d..893b3a7c2e1bbc05211e57d8c3125e95db7331e2 100644
--- a/src/flatten_agents.py
+++ b/src/flatten_agents.py
@@ -1,125 +1,125 @@
-#!/usr/bin/env python3
-"""
-flatten_agents.py -- Promote every nested agent to a top-level sibling.
-
-Claude Code's /agents Library tab auto-discovers ONLY top-level .md files in
-~/.claude/agents/. Agents living in category subdirs (design/, engineering/,
-game-development/, etc.) are invisible to the Library — there are 169 such
-orphans across 15 folders.
-
-This script walks ~/.claude/agents/ and for every nested .md file with YAML
-frontmatter containing a `name:` field (i.e. a real agent, not a reference
-note), it writes a sibling copy at the top level. The original nested file is
-left untouched so existing references still resolve.
-
-Safety:
-- Skips files with no frontmatter (reference notes, includes).
-- Skips if a sibling with the same basename already exists (no collision risk
- — verified at time of writing, but re-checked here).
-- Dry-run by default; pass --apply to actually write.
-
-Usage:
- python src/flatten_agents.py # dry run, print plan
- python src/flatten_agents.py --apply # perform the flatten
- python src/flatten_agents.py --apply -v # verbose
-"""
-
-from __future__ import annotations
-
-import argparse
-import shutil
-import sys
-from pathlib import Path
-
-AGENTS_DIR = Path.home() / ".claude" / "agents"
-
-
-def has_name_frontmatter(path: Path) -> bool:
- """Return True if the file opens with YAML frontmatter containing `name:`."""
- try:
- with path.open(encoding="utf-8", errors="replace") as fh:
- first = fh.readline().rstrip("\r\n")
- if first != "---":
- return False
- for line in fh:
- stripped = line.rstrip("\r\n")
- if stripped == "---":
- return False
- if stripped.startswith("name:"):
- return True
- return False
- except OSError:
- return False
-
-
-def plan_flatten(agents_dir: Path) -> tuple[list[tuple[Path, Path]], list[str]]:
- """Return (copy_plan, warnings). copy_plan is list of (src, dst) pairs."""
- copy_plan: list[tuple[Path, Path]] = []
- warnings: list[str] = []
-
- if not agents_dir.exists():
- warnings.append(f"agents_dir does not exist: {agents_dir}")
- return copy_plan, warnings
-
- for md in agents_dir.rglob("*.md"):
- # Top-level files are already discoverable.
- if md.parent == agents_dir:
- continue
- if not has_name_frontmatter(md):
- continue
- dst = agents_dir / md.name
- if dst.exists():
- # Don't clobber — flag so humans can resolve.
- if dst.read_bytes() != md.read_bytes():
- warnings.append(f"collision (different content): {md} -> {dst}")
- continue
- copy_plan.append((md, dst))
-
- return copy_plan, warnings
-
-
-def apply_plan(plan: list[tuple[Path, Path]], verbose: bool) -> int:
- copied = 0
- for src, dst in plan:
- try:
- shutil.copy2(src, dst)
- copied += 1
- if verbose:
- print(f" copied {src.relative_to(AGENTS_DIR)} -> {dst.name}")
- except OSError as e:
- print(f" FAILED {src}: {e}", file=sys.stderr)
- return copied
-
-
-def main() -> None:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--apply", action="store_true", help="actually copy files (default: dry run)")
- parser.add_argument("-v", "--verbose", action="store_true", help="print each action")
- parser.add_argument(
- "--agents-dir",
- type=Path,
- default=AGENTS_DIR,
- help="override agents dir (default: ~/.claude/agents)",
- )
- args = parser.parse_args()
-
- plan, warnings = plan_flatten(args.agents_dir)
-
- print(f"flatten_agents: {len(plan)} files to promote, {len(warnings)} warnings")
- for w in warnings:
- print(f" warn: {w}", file=sys.stderr)
-
- if not args.apply:
- if args.verbose:
- for src, dst in plan:
- print(f" would copy {src.relative_to(args.agents_dir)} -> {dst.name}")
- print("dry run — pass --apply to perform the flatten")
- sys.exit(0)
-
- copied = apply_plan(plan, args.verbose)
- print(f"done: {copied} agents promoted to top-level siblings")
- sys.exit(0 if copied == len(plan) else 1)
-
-
-if __name__ == "__main__":
- main()
+#!/usr/bin/env python3
+"""
+flatten_agents.py -- Promote every nested agent to a top-level sibling.
+
+Claude Code's /agents Library tab auto-discovers ONLY top-level .md files in
+~/.claude/agents/. Agents living in category subdirs (design/, engineering/,
+game-development/, etc.) are invisible to the Library — there are 169 such
+orphans across 15 folders.
+
+This script walks ~/.claude/agents/ and for every nested .md file with YAML
+frontmatter containing a `name:` field (i.e. a real agent, not a reference
+note), it writes a sibling copy at the top level. The original nested file is
+left untouched so existing references still resolve.
+
+Safety:
+- Skips files with no frontmatter (reference notes, includes).
+- Skips if a sibling with the same basename already exists (no collision risk
+ — verified at time of writing, but re-checked here).
+- Dry-run by default; pass --apply to actually write.
+
+Usage:
+ python src/flatten_agents.py # dry run, print plan
+ python src/flatten_agents.py --apply # perform the flatten
+ python src/flatten_agents.py --apply -v # verbose
+"""
+
+from __future__ import annotations
+
+import argparse
+import shutil
+import sys
+from pathlib import Path
+
+AGENTS_DIR = Path.home() / ".claude" / "agents"
+
+
+def has_name_frontmatter(path: Path) -> bool:
+ """Return True if the file opens with YAML frontmatter containing `name:`."""
+ try:
+ with path.open(encoding="utf-8", errors="replace") as fh:
+ first = fh.readline().rstrip("\r\n")
+ if first != "---":
+ return False
+ for line in fh:
+ stripped = line.rstrip("\r\n")
+ if stripped == "---":
+ return False
+ if stripped.startswith("name:"):
+ return True
+ return False
+ except OSError:
+ return False
+
+
+def plan_flatten(agents_dir: Path) -> tuple[list[tuple[Path, Path]], list[str]]:
+ """Return (copy_plan, warnings). copy_plan is list of (src, dst) pairs."""
+ copy_plan: list[tuple[Path, Path]] = []
+ warnings: list[str] = []
+
+ if not agents_dir.exists():
+ warnings.append(f"agents_dir does not exist: {agents_dir}")
+ return copy_plan, warnings
+
+ for md in agents_dir.rglob("*.md"):
+ # Top-level files are already discoverable.
+ if md.parent == agents_dir:
+ continue
+ if not has_name_frontmatter(md):
+ continue
+ dst = agents_dir / md.name
+ if dst.exists():
+ # Don't clobber — flag so humans can resolve.
+ if dst.read_bytes() != md.read_bytes():
+ warnings.append(f"collision (different content): {md} -> {dst}")
+ continue
+ copy_plan.append((md, dst))
+
+ return copy_plan, warnings
+
+
+def apply_plan(plan: list[tuple[Path, Path]], verbose: bool) -> int:
+ copied = 0
+ for src, dst in plan:
+ try:
+ shutil.copy2(src, dst)
+ copied += 1
+ if verbose:
+ print(f" copied {src.relative_to(AGENTS_DIR)} -> {dst.name}")
+ except OSError as e:
+ print(f" FAILED {src}: {e}", file=sys.stderr)
+ return copied
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--apply", action="store_true", help="actually copy files (default: dry run)")
+ parser.add_argument("-v", "--verbose", action="store_true", help="print each action")
+ parser.add_argument(
+ "--agents-dir",
+ type=Path,
+ default=AGENTS_DIR,
+ help="override agents dir (default: ~/.claude/agents)",
+ )
+ args = parser.parse_args()
+
+ plan, warnings = plan_flatten(args.agents_dir)
+
+ print(f"flatten_agents: {len(plan)} files to promote, {len(warnings)} warnings")
+ for w in warnings:
+ print(f" warn: {w}", file=sys.stderr)
+
+ if not args.apply:
+ if args.verbose:
+ for src, dst in plan:
+ print(f" would copy {src.relative_to(args.agents_dir)} -> {dst.name}")
+ print("dry run — pass --apply to perform the flatten")
+ sys.exit(0)
+
+ copied = apply_plan(plan, args.verbose)
+ print(f"done: {copied} agents promoted to top-level siblings")
+ sys.exit(0 if copied == len(plan) else 1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/harness_add.py b/src/harness_add.py
index 6df5341429e9203ea2d55038429342ac58d0be74..3b2da7961aece70aaf8acf0841a69c38d4a9ed37 100644
--- a/src/harness_add.py
+++ b/src/harness_add.py
@@ -173,7 +173,7 @@ class HarnessRecord:
def _parse_frontmatter(text: str) -> dict[str, Any]:
- match = re.match(r"^---\n(.*?\n)---\n", text, re.DOTALL)
+ match = re.match(r"^---\r?\n(.*?\r?\n)---\r?\n", text, re.DOTALL)
if not match:
return {}
try:
diff --git a/src/harness_install.py b/src/harness_install.py
index 119688d924c66bb7e3953941e9d869adbc531051..247b6872429a8c6a80486eb40ecaa0a67b2ad55f 100644
--- a/src/harness_install.py
+++ b/src/harness_install.py
@@ -25,7 +25,7 @@ from urllib.request import url2pathname
from ctx.core.entity_types import entity_page_path
from ctx.core.wiki.wiki_utils import parse_frontmatter_and_body, validate_skill_name
-from ctx.utils._fs_utils import atomic_write_json, reject_symlink_path
+from ctx.utils._fs_utils import atomic_write_json, atomic_write_text, reject_symlink_path
from ctx_config import cfg
_COMMAND_ENV_ALLOWLIST = {
@@ -59,6 +59,7 @@ class HarnessRecord:
runtimes: tuple[str, ...]
model_providers: tuple[str, ...]
capabilities: tuple[str, ...]
+ attach_modes: tuple[str, ...]
setup_commands: tuple[str, ...]
verify_commands: tuple[str, ...]
@@ -98,11 +99,33 @@ def _load_page(path: Path, slug: str) -> HarnessRecord:
runtimes=_as_tuple(fm.get("runtimes")),
model_providers=_as_tuple(fm.get("model_providers")),
capabilities=_as_tuple(fm.get("capabilities")),
+ attach_modes=_normalize_attach_modes(fm.get("attach_modes")),
setup_commands=_as_tuple(fm.get("setup_commands")),
verify_commands=_as_tuple(fm.get("verify_commands")),
)
+def _normalize_attach_modes(raw: object) -> tuple[str, ...]:
+ aliases = {
+ "mcp": "mcp",
+ "mcp-server": "mcp",
+ "python": "python-library",
+ "python-library": "python-library",
+ "library": "python-library",
+ "ctx": "ctx-run",
+ "ctx-run": "ctx-run",
+ "cli": "ctx-run",
+ "manual": "manual",
+ }
+ values = _as_tuple(raw) or ("mcp", "python-library", "ctx-run")
+ modes: list[str] = []
+ for value in values:
+ mode = aliases.get(value.strip().lower())
+ if mode and mode not in modes:
+ modes.append(mode)
+ return tuple(modes) or ("manual",)
+
+
def _repo_key(raw: str) -> str:
value = raw.strip().removesuffix(".git").rstrip("/")
parsed = urlparse(value)
@@ -186,6 +209,10 @@ def render_plan(record: HarnessRecord, *, target: Path) -> str:
lines.append(f"Runtimes: {', '.join(record.runtimes)}")
if record.model_providers:
lines.append(f"Model providers: {', '.join(record.model_providers)}")
+ if record.capabilities:
+ lines.append(f"Capabilities: {', '.join(record.capabilities)}")
+ if record.attach_modes:
+ lines.append(f"Attach modes: {', '.join(record.attach_modes)}")
if record.setup_commands:
lines.append("Setup commands:")
lines.extend(f" - {cmd}" for cmd in record.setup_commands)
@@ -252,19 +279,30 @@ def _materialize_source(
def _run_command(command: str, *, cwd: Path) -> dict[str, Any]:
- tokens = shlex.split(command)
+ tokens = _split_command(command)
if not tokens:
raise ValueError("empty harness command")
+ env = _command_env()
+ tokens[0] = _resolve_command_executable(tokens[0], env)
started = time.time()
- proc = subprocess.run(
- tokens,
- cwd=str(cwd),
- env=_command_env(),
- capture_output=True,
- text=True,
- check=False,
- timeout=600,
- )
+ try:
+ proc = subprocess.run(
+ tokens,
+ cwd=str(cwd),
+ env=env,
+ capture_output=True,
+ text=True,
+ check=False,
+ timeout=600,
+ )
+ except OSError as exc:
+ return {
+ "command": command,
+ "returncode": 127,
+ "stdout": "",
+ "stderr": _redact_output(str(exc))[-4000:],
+ "duration_seconds": round(time.time() - started, 3),
+ }
return {
"command": command,
"returncode": proc.returncode,
@@ -274,6 +312,31 @@ def _run_command(command: str, *, cwd: Path) -> dict[str, Any]:
}
+def _split_command(command: str) -> list[str]:
+ parts = shlex.split(command, posix=os.name != "nt")
+ if os.name == "nt":
+ parts = [_strip_surrounding_quotes(part) for part in parts]
+ return parts
+
+
+def _strip_surrounding_quotes(value: str) -> str:
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
+ return value[1:-1]
+ return value
+
+
+def _resolve_command_executable(command: str, env: dict[str, str]) -> str:
+ if os.path.isabs(command) or any(sep in command for sep in ("/", "\\")):
+ return command
+ return shutil.which(command, path=env.get("PATH")) or command
+
+
+def _failed_run_message(kind: str, command: str, run: dict[str, Any]) -> str:
+ tail = str(run.get("stderr") or run.get("stdout") or "").strip()
+ suffix = f": {tail[-1000:]}" if tail else ""
+ return f"{kind} command failed: {command}{suffix}"
+
+
def _command_env() -> dict[str, str]:
"""Return a minimal environment for cataloged harness commands."""
env: dict[str, str] = {}
@@ -321,13 +384,13 @@ def _stage_harness(
run = _run_command(command, cwd=stage_path)
setup_runs.append(run)
if run["returncode"] != 0:
- raise RuntimeError(f"setup command failed: {command}")
+ raise RuntimeError(_failed_run_message("setup", command, run))
if run_verify:
for command in record.verify_commands:
run = _run_command(command, cwd=stage_path)
verify_runs.append(run)
if run["returncode"] != 0:
- raise RuntimeError(f"verify command failed: {command}")
+ raise RuntimeError(_failed_run_message("verify", command, run))
return setup_runs, verify_runs
@@ -388,6 +451,7 @@ def _write_manifest(
manifest_dir: Path,
setup_runs: list[dict[str, Any]],
verify_runs: list[dict[str, Any]],
+ attach_files: list[Path] | None = None,
) -> Path:
path = manifest_dir / f"{record.slug}.json"
reject_symlink_path(path)
@@ -399,6 +463,9 @@ def _write_manifest(
"repo_url": record.repo_url,
"target": str(target),
"installed_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
+ "attach_files": [
+ str(path.relative_to(target)) for path in (attach_files or [])
+ ],
"setup_commands_run": setup_runs,
"verify_commands_run": verify_runs,
}
@@ -460,6 +527,7 @@ def install_harness(
if dry_run:
return InstallResult(record.slug, "dry-run", target=target_path)
+ target_preexisting = target_path.exists()
try:
setup_runs, verify_runs = _install_to_target(
record=record,
@@ -470,12 +538,14 @@ def install_harness(
run_verify=run_verify,
allow_local_sources=allow_local_sources,
)
+ attach_files = _write_attach_files(record, target=target_path)
manifest_path = _write_manifest(
record=record,
target=target_path,
manifest_dir=manifest_dir,
setup_runs=setup_runs,
verify_runs=verify_runs,
+ attach_files=attach_files,
)
except FileExistsError as exc:
return InstallResult(
@@ -485,6 +555,11 @@ def install_harness(
message=str(exc),
)
except Exception as exc: # noqa: BLE001
+ if not target_preexisting and target_path.exists():
+ try:
+ _remove_path(target_path)
+ except Exception: # noqa: BLE001
+ pass
return InstallResult(
record.slug,
"install-failed",
@@ -500,6 +575,89 @@ def install_harness(
)
+def _write_attach_files(record: HarnessRecord, *, target: Path) -> list[Path]:
+ attach_dir = target / ".ctx" / "attach"
+ attach_dir.mkdir(parents=True, exist_ok=True)
+ written: list[Path] = []
+
+ readme = attach_dir / "README.md"
+ reject_symlink_path(readme)
+ atomic_write_text(readme, _render_attach_readme(record))
+ written.append(readme)
+
+ if "mcp" in record.attach_modes:
+ path = attach_dir / "mcp.json"
+ reject_symlink_path(path)
+ atomic_write_text(path, _render_mcp_attach_config())
+ written.append(path)
+ if "python-library" in record.attach_modes:
+ path = attach_dir / "python.py"
+ reject_symlink_path(path)
+ atomic_write_text(path, _render_python_attach_snippet())
+ written.append(path)
+ if "ctx-run" in record.attach_modes:
+ path = attach_dir / "ctx-run.txt"
+ reject_symlink_path(path)
+ atomic_write_text(path, _render_ctx_run_attach_template(record))
+ written.append(path)
+ return written
+
+
+def _render_attach_readme(record: HarnessRecord) -> str:
+ modes = ", ".join(record.attach_modes)
+ return f"""# ctx Attachment for {record.title}
+
+This harness was installed by `ctx-harness-install`.
+
+Supported attach modes: {modes}
+
+Use the files in this directory to connect the harness to ctx:
+
+- `mcp.json`: start `ctx-mcp-server` from any MCP-speaking host.
+- `python.py`: call ctx recommendation/wiki APIs from a Python loop.
+- `ctx-run.txt`: run the built-in ctx generic harness with your model.
+
+The attachment files do not run setup commands and do not contain secrets.
+"""
+
+
+def _render_mcp_attach_config() -> str:
+ return json.dumps(
+ {
+ "mcpServers": {
+ "ctx-wiki": {
+ "command": "ctx-mcp-server",
+ "args": [],
+ }
+ }
+ },
+ indent=2,
+ ) + "\n"
+
+
+def _render_python_attach_snippet() -> str:
+ return """from ctx import graph_query, recommend_bundle, wiki_get, wiki_search
+
+
+def recommend_for_turn(goal: str) -> list[dict]:
+ return recommend_bundle(goal, top_k=5)
+
+
+def load_entity(slug: str) -> dict | None:
+ return wiki_get(slug)
+
+"""
+
+
+def _render_ctx_run_attach_template(record: HarnessRecord) -> str:
+ task = record.capabilities[0] if record.capabilities else f"use {record.title}"
+ return (
+ "ctx run --model "
+ f"--task {json.dumps(task)} "
+ "--mcp ctx-wiki:ctx-mcp-server\n"
+ )
+
+
def uninstall_harness(
identifier: str,
*,
@@ -537,6 +695,9 @@ def uninstall_harness(
return InstallResult(slug, "dry-run", target=target, manifest_path=manifest_path)
try:
+ if not keep_files:
+ manifest["status"] = "uninstalling"
+ atomic_write_json(manifest_path, manifest, indent=2)
if not keep_files and target.exists():
if target.is_dir():
shutil.rmtree(target)
@@ -635,6 +796,91 @@ def recommend_harnesses_for_cli(
)
+def render_no_fit_harness_plan(
+ *,
+ goal: str,
+ model_provider: str | None,
+ model: str | None,
+) -> str:
+ """Render a build handoff when no catalog harness fits the user's setup."""
+ provider = model_provider or "unknown provider"
+ model_name = model or "unspecified model"
+ goal_text = goal.strip() or "unspecified development goal"
+ return "\n".join([
+ "# Custom Harness PRD",
+ "",
+ "ctx did not find a catalog harness above the configured fit score.",
+ "Use this handoff to build an attachable harness for your local/API model.",
+ "",
+ "## Inputs",
+ "",
+ f"- Goal: {goal_text}",
+ f"- Model provider: {provider}",
+ f"- Model: {model_name}",
+ "- Target operating systems: Windows, macOS, and Linux unless narrowed by the user",
+ "",
+ "## Required Interview Before Building",
+ "",
+ "- Confirm the exact model, API base URL or local runtime, context window, and tool-call support.",
+ "- Confirm the user's goal, repository type, stack, expected autonomy, and time horizon.",
+ "- Confirm filesystem, shell, browser, network, secret, and package-manager access.",
+ "- Confirm verification commands: tests, lint, type check, build, smoke, and dashboard/browser checks.",
+ "- Confirm approval policy for destructive commands, network calls, dependency installs, and secret use.",
+ "",
+ "## Harness Architecture",
+ "",
+ "- Instructions: short root instructions plus deeper task, quality, safety, and verification docs.",
+ "- State: durable session file, active task summary, loaded ctx entities, and handoff/progress log.",
+ "- Scope: explicit allow/deny tool registry, cwd boundaries, environment allowlist, and secret redaction.",
+ "- Verification: every completion requires runnable evidence captured in the session log.",
+ "- Lifecycle: start session, observe dev events, request ctx recommendations, mark use, propose unload, end session.",
+ "",
+ "## ctx Attachment Contract",
+ "",
+ "- MCP mode: start `ctx-mcp-server` and expose ctx tools to the host.",
+ "- Python mode: call `ctx.recommend_bundle`, `ctx.wiki_get`, `ctx.wiki_search`, and `ctx.graph_query`.",
+ "- CLI mode: use `ctx run --model --task ` when the user wants ctx to own the loop.",
+ "- Each dev window sends the current goal, stack, touched files, errors, and verification state to ctx.",
+ "- ctx returns at most five skills/agents/MCPs. The harness asks before loading or unloading anything.",
+ "",
+ "## Acceptance Tests",
+ "",
+ "- Fresh install on Windows, macOS, and Linux can start the harness without secrets printed in logs.",
+ "- A sample task triggers no more than five ctx skill/agent/MCP recommendations.",
+ "- A selected recommendation is recorded as used with evidence.",
+ "- An unused loaded entity produces an unload proposal and respects a user skip.",
+ "- A failing verification command prevents the harness from reporting completion.",
+ "",
+ "## Prompt For A Strong LLM",
+ "",
+ "Build the harness described above. Keep ctx integration attachable through MCP or Python. "
+ "Do not hard-code secrets. Implement cross-platform startup and verification commands. "
+ "Produce a minimal working harness first, then add durable state and unload lifecycle.",
+ "",
+ "Design reference: https://github.com/walkinglabs/learn-harness-engineering",
+ ]) + "\n"
+
+
+def write_no_fit_harness_plan(
+ path: Path,
+ *,
+ goal: str,
+ model_provider: str | None,
+ model: str | None,
+) -> Path:
+ target = path.expanduser()
+ reject_symlink_path(target)
+ atomic_write_text(
+ target,
+ render_no_fit_harness_plan(
+ goal=goal,
+ model_provider=model_provider,
+ model=model,
+ ),
+ )
+ return target
+
+
def print_recommendations(results: list[dict[str, Any]]) -> None:
if not results:
print("No harness recommendations matched.")
@@ -642,9 +888,9 @@ def print_recommendations(results: list[dict[str, Any]]) -> None:
print("Recommended harnesses:")
for row in results:
slug = str(row.get("name") or "")
- score = float(row.get("normalized_score") or 0.0)
- reason = str(row.get("reason") or "").strip()
- print(f"- {slug} (match {score:.2f})")
+ score = float(row.get("fit_score") or row.get("normalized_score") or 0.0)
+ reason = str(row.get("fit_reason") or row.get("reason") or "").strip()
+ print(f"- {slug} (fit {score:.2f})")
if reason:
print(f" reason: {reason}")
print(f" install: ctx-harness-install {slug} --dry-run")
@@ -677,6 +923,15 @@ def main(argv: list[str] | None = None) -> int:
parser.add_argument("--model-provider", help="Model provider prefix, e.g. openai or ollama")
parser.add_argument("--model", help="Model slug, e.g. openrouter/openai/gpt-5.5")
parser.add_argument("--top-k", type=int, default=5, help="Maximum recommendations to print")
+ parser.add_argument(
+ "--plan-on-no-fit",
+ action="store_true",
+ help="When --recommend finds no harness, print a custom harness PRD",
+ )
+ parser.add_argument(
+ "--plan-output",
+ help="Write the no-fit custom harness PRD to this markdown file",
+ )
parser.add_argument("--force", action="store_true", help="Replace target if it exists")
parser.add_argument(
"--update",
@@ -739,6 +994,24 @@ def main(argv: list[str] | None = None) -> int:
top_k=max(1, min(int(args.top_k), 5)),
)
print_recommendations(results)
+ if not results and args.plan_on_no_fit:
+ if args.plan_output:
+ path = write_no_fit_harness_plan(
+ Path(os.path.expanduser(args.plan_output)),
+ goal=goal,
+ model_provider=args.model_provider,
+ model=args.model,
+ )
+ print(f"Custom harness plan: {path}")
+ else:
+ print()
+ print(render_no_fit_harness_plan(
+ goal=goal,
+ model_provider=args.model_provider,
+ model=args.model,
+ ), end="")
+ elif not results:
+ print("Use --plan-on-no-fit to generate a custom harness PRD.")
return 0
if not args.identifier:
parser.error("identifier is required unless --recommend is used")
diff --git a/src/import_mattpocock_skills.py b/src/import_mattpocock_skills.py
index f912a5ed9c2740c329b3f9c6e1ade37000be4d4c..2b7062c305077a426e090f3a090e83287112dea6 100644
--- a/src/import_mattpocock_skills.py
+++ b/src/import_mattpocock_skills.py
@@ -1,166 +1,166 @@
-#!/usr/bin/env python3
-"""import_mattpocock_skills.py -- Deploy mattpocock/skills into ~/.claude/skills.
-
-Reads imported-skills/mattpocock/MANIFEST.json. Each entry creates a directory
-named ``mattpocock-``, copies SKILL.md (with attribution header
-prepended), and copies any support files (ADR-FORMAT.md, deep-modules.md,
-scripts/, etc.) verbatim.
-
-Idempotent. Safe to re-run.
-
-Usage:
- python src/import_mattpocock_skills.py --dry-run
- python src/import_mattpocock_skills.py --install
- python src/import_mattpocock_skills.py --install --target ./custom-skills-dir
-"""
-
-from __future__ import annotations
-
-import argparse
-import json
-import re
-import shutil
-import sys
-from pathlib import Path
-
-from ctx_config import cfg
-
-REPO_ROOT = Path(__file__).resolve().parent.parent
-IMPORT_ROOT = REPO_ROOT / "imported-skills" / "mattpocock"
-MANIFEST_PATH = IMPORT_ROOT / "MANIFEST.json"
-
-_SAFE_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")
-
-
-def load_manifest() -> dict:
- if not MANIFEST_PATH.exists():
- print(f"Manifest not found: {MANIFEST_PATH}", file=sys.stderr)
- print("Run: python imported-skills/mattpocock/build_manifest.py", file=sys.stderr)
- sys.exit(1)
- return json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
-
-
-def _validate(field: str, value: object, *, regex: re.Pattern[str] | None = None) -> str:
- if not isinstance(value, str) or not value:
- raise ValueError(f"{field}: expected non-empty string, got {type(value).__name__}")
- if regex is not None and not regex.match(value):
- raise ValueError(f"{field}: {value!r} failed strict format check")
- return value
-
-
-def _resolve_within(root: Path, candidate_rel: str, *, field: str) -> Path:
- if ".." in Path(candidate_rel).parts or candidate_rel.startswith(("/", "\\")):
- raise ValueError(f"{field}: path traversal denied in {candidate_rel!r}")
- resolved = (root / candidate_rel).resolve()
- root_resolved = root.resolve()
- try:
- resolved.relative_to(root_resolved)
- except ValueError as exc:
- raise ValueError(f"{field}: {candidate_rel!r} resolves outside import root") from exc
- return resolved
-
-
-def render_attribution_header(manifest: dict) -> str:
- return (
- f"\n"
- )
-
-
-def deploy_entry(entry: dict, manifest: dict, target_dir: Path, dry_run: bool) -> tuple[Path, bool, list[Path]]:
- slug = _validate("slug", entry.get("slug"), regex=_SAFE_SLUG_RE)
- source_path_raw = _validate("source_path", entry.get("source_path"))
- source = _resolve_within(IMPORT_ROOT, source_path_raw, field="source_path")
- if not source.exists():
- raise FileNotFoundError(f"Source skill missing: {source}")
- source_dir = source.parent
-
- skill_dir = target_dir / f"mattpocock-{slug}"
- dest_resolved = skill_dir.resolve()
- target_resolved = target_dir.resolve()
- try:
- dest_resolved.relative_to(target_resolved)
- except ValueError as exc:
- raise ValueError(f"skill dir {skill_dir} resolves outside target_dir") from exc
-
- dest_skill = skill_dir / "SKILL.md"
- header = render_attribution_header(manifest)
- body = source.read_text(encoding="utf-8")
- if body.startswith("", 1)[1].lstrip("\n")
- content = header + body
-
- changed = True
- if dest_skill.exists():
- existing = dest_skill.read_text(encoding="utf-8")
- changed = existing != content
-
- support_paths: list[Path] = []
- for rel in entry.get("support_files", []):
- # Validate each support file rel-path against the source dir.
- sp = _resolve_within(source_dir, rel, field="support_files")
- if sp.is_file():
- support_paths.append(sp)
-
- if not dry_run:
- if changed:
- skill_dir.mkdir(parents=True, exist_ok=True)
- dest_skill.write_text(content, encoding="utf-8")
- for sp in support_paths:
- rel = sp.relative_to(source_dir)
- dest_support = skill_dir / rel
- dest_support.parent.mkdir(parents=True, exist_ok=True)
- if not dest_support.exists() or dest_support.read_bytes() != sp.read_bytes():
- shutil.copy2(sp, dest_support)
- changed = True
-
- return dest_skill, changed, support_paths
-
-
-def main() -> None:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--install", action="store_true")
- parser.add_argument("--dry-run", action="store_true")
- parser.add_argument(
- "--target",
- default=str(cfg.skills_dir),
- help=f"Target skills dir (default: {cfg.skills_dir})",
- )
- args = parser.parse_args()
- if not args.install and not args.dry_run:
- parser.error("Pass either --install or --dry-run")
-
- manifest = load_manifest()
- target_dir = Path(args.target).expanduser()
- if args.install and not target_dir.exists():
- print(f"Creating target dir: {target_dir}")
- target_dir.mkdir(parents=True, exist_ok=True)
-
- new_or_updated = 0
- unchanged = 0
- for entry in manifest["entries"]:
- dest, changed, support = deploy_entry(entry, manifest, target_dir, dry_run=args.dry_run)
- marker = "UPD" if changed else " "
- if changed:
- new_or_updated += 1
- else:
- unchanged += 1
- suffix = f" (+{len(support)} support)" if support else ""
- print(f" [{marker}] {dest.relative_to(target_dir.parent)}{suffix}")
-
- mode = "dry-run" if args.dry_run else "install"
- print()
- print(f"Mode: {mode} target: {target_dir}")
- print(f"Entries: {len(manifest['entries'])} new/updated: {new_or_updated} unchanged: {unchanged}")
- if args.install:
- print()
- print("Next steps:")
- print(f" ctx-catalog-builder --wiki {cfg.wiki_dir} --skills-dir {target_dir} \\")
- print(f" --agents-dir {cfg.agents_dir}")
- print(" ctx-wiki-batch-entities --all")
- print(" ctx-wiki-graphify")
-
-
-if __name__ == "__main__":
- main()
+#!/usr/bin/env python3
+"""import_mattpocock_skills.py -- Deploy mattpocock/skills into ~/.claude/skills.
+
+Reads imported-skills/mattpocock/MANIFEST.json. Each entry creates a directory
+named ``mattpocock-``, copies SKILL.md (with attribution header
+prepended), and copies any support files (ADR-FORMAT.md, deep-modules.md,
+scripts/, etc.) verbatim.
+
+Idempotent. Safe to re-run.
+
+Usage:
+ python src/import_mattpocock_skills.py --dry-run
+ python src/import_mattpocock_skills.py --install
+ python src/import_mattpocock_skills.py --install --target ./custom-skills-dir
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import shutil
+import sys
+from pathlib import Path
+
+from ctx_config import cfg
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+IMPORT_ROOT = REPO_ROOT / "imported-skills" / "mattpocock"
+MANIFEST_PATH = IMPORT_ROOT / "MANIFEST.json"
+
+_SAFE_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")
+
+
+def load_manifest() -> dict:
+ if not MANIFEST_PATH.exists():
+ print(f"Manifest not found: {MANIFEST_PATH}", file=sys.stderr)
+ print("Run: python imported-skills/mattpocock/build_manifest.py", file=sys.stderr)
+ sys.exit(1)
+ return json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
+
+
+def _validate(field: str, value: object, *, regex: re.Pattern[str] | None = None) -> str:
+ if not isinstance(value, str) or not value:
+ raise ValueError(f"{field}: expected non-empty string, got {type(value).__name__}")
+ if regex is not None and not regex.match(value):
+ raise ValueError(f"{field}: {value!r} failed strict format check")
+ return value
+
+
+def _resolve_within(root: Path, candidate_rel: str, *, field: str) -> Path:
+ if ".." in Path(candidate_rel).parts or candidate_rel.startswith(("/", "\\")):
+ raise ValueError(f"{field}: path traversal denied in {candidate_rel!r}")
+ resolved = (root / candidate_rel).resolve()
+ root_resolved = root.resolve()
+ try:
+ resolved.relative_to(root_resolved)
+ except ValueError as exc:
+ raise ValueError(f"{field}: {candidate_rel!r} resolves outside import root") from exc
+ return resolved
+
+
+def render_attribution_header(manifest: dict) -> str:
+ return (
+ f"\n"
+ )
+
+
+def deploy_entry(entry: dict, manifest: dict, target_dir: Path, dry_run: bool) -> tuple[Path, bool, list[Path]]:
+ slug = _validate("slug", entry.get("slug"), regex=_SAFE_SLUG_RE)
+ source_path_raw = _validate("source_path", entry.get("source_path"))
+ source = _resolve_within(IMPORT_ROOT, source_path_raw, field="source_path")
+ if not source.exists():
+ raise FileNotFoundError(f"Source skill missing: {source}")
+ source_dir = source.parent
+
+ skill_dir = target_dir / f"mattpocock-{slug}"
+ dest_resolved = skill_dir.resolve()
+ target_resolved = target_dir.resolve()
+ try:
+ dest_resolved.relative_to(target_resolved)
+ except ValueError as exc:
+ raise ValueError(f"skill dir {skill_dir} resolves outside target_dir") from exc
+
+ dest_skill = skill_dir / "SKILL.md"
+ header = render_attribution_header(manifest)
+ body = source.read_text(encoding="utf-8")
+ if body.startswith("", 1)[1].lstrip("\n")
+ content = header + body
+
+ changed = True
+ if dest_skill.exists():
+ existing = dest_skill.read_text(encoding="utf-8")
+ changed = existing != content
+
+ support_paths: list[Path] = []
+ for rel in entry.get("support_files", []):
+ # Validate each support file rel-path against the source dir.
+ sp = _resolve_within(source_dir, rel, field="support_files")
+ if sp.is_file():
+ support_paths.append(sp)
+
+ if not dry_run:
+ if changed:
+ skill_dir.mkdir(parents=True, exist_ok=True)
+ dest_skill.write_text(content, encoding="utf-8")
+ for sp in support_paths:
+ rel = sp.relative_to(source_dir)
+ dest_support = skill_dir / rel
+ dest_support.parent.mkdir(parents=True, exist_ok=True)
+ if not dest_support.exists() or dest_support.read_bytes() != sp.read_bytes():
+ shutil.copy2(sp, dest_support)
+ changed = True
+
+ return dest_skill, changed, support_paths
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--install", action="store_true")
+ parser.add_argument("--dry-run", action="store_true")
+ parser.add_argument(
+ "--target",
+ default=str(cfg.skills_dir),
+ help=f"Target skills dir (default: {cfg.skills_dir})",
+ )
+ args = parser.parse_args()
+ if not args.install and not args.dry_run:
+ parser.error("Pass either --install or --dry-run")
+
+ manifest = load_manifest()
+ target_dir = Path(args.target).expanduser()
+ if args.install and not target_dir.exists():
+ print(f"Creating target dir: {target_dir}")
+ target_dir.mkdir(parents=True, exist_ok=True)
+
+ new_or_updated = 0
+ unchanged = 0
+ for entry in manifest["entries"]:
+ dest, changed, support = deploy_entry(entry, manifest, target_dir, dry_run=args.dry_run)
+ marker = "UPD" if changed else " "
+ if changed:
+ new_or_updated += 1
+ else:
+ unchanged += 1
+ suffix = f" (+{len(support)} support)" if support else ""
+ print(f" [{marker}] {dest.relative_to(target_dir.parent)}{suffix}")
+
+ mode = "dry-run" if args.dry_run else "install"
+ print()
+ print(f"Mode: {mode} target: {target_dir}")
+ print(f"Entries: {len(manifest['entries'])} new/updated: {new_or_updated} unchanged: {unchanged}")
+ if args.install:
+ print()
+ print("Next steps:")
+ print(f" ctx-catalog-builder --wiki {cfg.wiki_dir} --skills-dir {target_dir} \\")
+ print(f" --agents-dir {cfg.agents_dir}")
+ print(" ctx-wiki-batch-entities --all")
+ print(" ctx-wiki-graphify")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/import_skills_sh_catalog.py b/src/import_skills_sh_catalog.py
index ae3abeafaeb0ebcd93ec83a956fa8bacc5fa61a1..9e3618a5a74c05ef13ae791d72c7ba78219a83c6 100644
--- a/src/import_skills_sh_catalog.py
+++ b/src/import_skills_sh_catalog.py
@@ -1560,6 +1560,7 @@ def update_wiki_tarball(tarball: Path, catalog: dict[str, Any]) -> None:
and parts[1] in replacement_slugs
)
or safe_name.endswith(".original")
+ or safe_name.endswith(".lock")
):
continue
if safe_name == "graphify-out/graph-report.md":
@@ -1700,6 +1701,8 @@ def _validate_wiki_tarball_candidate(candidate: Path) -> None:
raise ValueError(f"unsafe tar member in candidate: {member.name!r}")
if safe_name.endswith(".original"):
raise ValueError(f"raw backup member leaked into candidate: {safe_name}")
+ if safe_name.endswith(".lock"):
+ raise ValueError(f"lock member leaked into candidate: {safe_name}")
seen.add(safe_name)
if safe_name == "graphify-out/graph.json":
graph = _read_tar_json(tf, member, "graph.json")
diff --git a/src/import_strix_skills.py b/src/import_strix_skills.py
index 9ad4acf645b4a16d1820adc48920819e15accefa..01b35eaed4f8c413aaaea6f319b679e2088f596c 100644
--- a/src/import_strix_skills.py
+++ b/src/import_strix_skills.py
@@ -1,187 +1,187 @@
-#!/usr/bin/env python3
-"""import_strix_skills.py -- Deploy imported Strix skills into ~/.claude/skills.
-
-Reads imported-skills/strix/MANIFEST.json and creates one skill directory per
-entry in `cfg.skills_dir`, following the naming convention:
-
- /strix--/SKILL.md
-
-Each deployed SKILL.md prepends an attribution header so provenance remains
-visible inline when the skill is loaded.
-
-This script is idempotent. Re-running updates existing deployments in place.
-
-Usage:
- python src/import_strix_skills.py --dry-run # preview
- python src/import_strix_skills.py --install # deploy to ~/.claude/skills
- python src/import_strix_skills.py --install \\
- --target ./custom-skills-dir # deploy elsewhere
-"""
-
-from __future__ import annotations
-
-import argparse
-import json
-import re
-import sys
-from pathlib import Path
-
-from ctx_config import cfg
-
-REPO_ROOT = Path(__file__).resolve().parent.parent
-IMPORT_ROOT = REPO_ROOT / "imported-skills" / "strix"
-MANIFEST_PATH = IMPORT_ROOT / "MANIFEST.json"
-
-SLUG_RE = re.compile(r"[^a-z0-9]+")
-
-
-def slugify(name: str) -> str:
- return SLUG_RE.sub("-", name.lower()).strip("-")
-
-
-def load_manifest() -> dict:
- if not MANIFEST_PATH.exists():
- print(f"Manifest not found: {MANIFEST_PATH}", file=sys.stderr)
- print("Run: python imported-skills/strix/build_manifest.py", file=sys.stderr)
- sys.exit(1)
- return json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
-
-
-def render_attribution_header(entry: dict, manifest: dict) -> str:
- return (
- f"\n"
- )
-
-
-_SAFE_CATEGORY_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
-
-
-def _validate_manifest_field(field: str, value: object, *, regex: re.Pattern[str] | None = None) -> str:
- """Reject manifest values that could escape the intended trust boundary."""
- if not isinstance(value, str) or not value:
- raise ValueError(f"{field}: expected non-empty string, got {type(value).__name__}")
- if regex is not None and not regex.match(value):
- raise ValueError(f"{field}: {value!r} failed strict format check")
- return value
-
-
-def _resolve_within(root: Path, candidate_rel: str, *, field: str) -> Path:
- """Join ``candidate_rel`` onto ``root`` and fail hard if the result escapes root.
-
- Strix finding vuln-0001 (Path Traversal in Strix Skill Import): the
- manifest's ``source_path`` was concatenated directly onto IMPORT_ROOT,
- so a crafted value like ``../../etc/passwd`` would be happily read
- and re-written into the target skills tree. Resolve both sides and
- enforce ``relative_to`` containment before we touch the filesystem.
- """
- if ".." in Path(candidate_rel).parts or candidate_rel.startswith(("/", "\\")):
- raise ValueError(f"{field}: path traversal denied in {candidate_rel!r}")
- resolved = (root / candidate_rel).resolve()
- root_resolved = root.resolve()
- try:
- resolved.relative_to(root_resolved)
- except ValueError as exc:
- raise ValueError(
- f"{field}: {candidate_rel!r} resolves outside import root"
- ) from exc
- return resolved
-
-
-def deploy_entry(entry: dict, manifest: dict, target_dir: Path, dry_run: bool) -> tuple[Path, bool]:
- # Manifest fields are untrusted input (the repo's imported-skills/
- # MANIFEST.json is checked-in today, but the path from parsing to
- # filesystem write must still be defensible). Validate category
- # against a strict allowlist, contain source_path inside IMPORT_ROOT.
- category = _validate_manifest_field("category", entry.get("category"), regex=_SAFE_CATEGORY_RE)
- source_path_raw = _validate_manifest_field("source_path", entry.get("source_path"))
- source = _resolve_within(IMPORT_ROOT, source_path_raw, field="source_path")
-
- if not source.exists():
- raise FileNotFoundError(f"Source skill missing: {source}")
-
- dir_name = f"strix-{category}-{slugify(entry['name'])}"
- skill_dir = target_dir / dir_name
- # Same containment check on the destination — dir_name is built from
- # validated inputs but slugify() on entry['name'] is defensive too.
- dest_resolved = skill_dir.resolve()
- target_resolved = target_dir.resolve()
- try:
- dest_resolved.relative_to(target_resolved)
- except ValueError as exc:
- raise ValueError(
- f"skill dir {skill_dir} resolves outside target_dir"
- ) from exc
- dest = skill_dir / "SKILL.md"
-
- header = render_attribution_header(entry, manifest)
- body = source.read_text(encoding="utf-8")
- if body.startswith("", 1)[1].lstrip("\n")
- content = header + body
-
- changed = True
- if dest.exists():
- existing = dest.read_text(encoding="utf-8")
- changed = existing != content
-
- if not dry_run and changed:
- skill_dir.mkdir(parents=True, exist_ok=True)
- dest.write_text(content, encoding="utf-8")
-
- return dest, changed
-
-
-def main() -> None:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--install", action="store_true", help="Write to target dir")
- parser.add_argument("--dry-run", action="store_true", help="Preview without writing")
- parser.add_argument(
- "--target",
- default=str(cfg.skills_dir),
- help=f"Target skills dir (default: {cfg.skills_dir})",
- )
- args = parser.parse_args()
-
- if not args.install and not args.dry_run:
- parser.error("Pass either --install or --dry-run")
-
- manifest = load_manifest()
- target_dir = Path(args.target).expanduser()
-
- if args.install and not target_dir.exists():
- print(f"Creating target dir: {target_dir}")
- target_dir.mkdir(parents=True, exist_ok=True)
-
- created = updated = unchanged = 0
- for entry in manifest["entries"]:
- dest, changed = deploy_entry(entry, manifest, target_dir, dry_run=args.dry_run)
- if changed:
- if dest.exists() and not args.dry_run:
- updated += 1
- marker = "UPD"
- else:
- created += 1
- marker = "NEW"
- else:
- unchanged += 1
- marker = " "
- print(f" [{marker}] {dest.relative_to(target_dir.parent)}")
-
- mode = "dry-run" if args.dry_run else "install"
- print()
- print(f"Mode: {mode} target: {target_dir}")
- print(f"Entries: {len(manifest['entries'])} new/updated: {created + updated} unchanged: {unchanged}")
-
- if args.install:
- print()
- print("Next steps:")
- print(f" python src/catalog_builder.py --wiki {cfg.wiki_dir} --skills-dir {target_dir} \\")
- print(f" --agents-dir {cfg.agents_dir}")
- print(" python src/wiki_batch_entities.py --all")
- print(" python -m ctx.core.wiki.wiki_graphify")
-
-
-if __name__ == "__main__":
- main()
+#!/usr/bin/env python3
+"""import_strix_skills.py -- Deploy imported Strix skills into ~/.claude/skills.
+
+Reads imported-skills/strix/MANIFEST.json and creates one skill directory per
+entry in `cfg.skills_dir`, following the naming convention:
+
+ /strix--/SKILL.md
+
+Each deployed SKILL.md prepends an attribution header so provenance remains
+visible inline when the skill is loaded.
+
+This script is idempotent. Re-running updates existing deployments in place.
+
+Usage:
+ python src/import_strix_skills.py --dry-run # preview
+ python src/import_strix_skills.py --install # deploy to ~/.claude/skills
+ python src/import_strix_skills.py --install \\
+ --target ./custom-skills-dir # deploy elsewhere
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+from pathlib import Path
+
+from ctx_config import cfg
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+IMPORT_ROOT = REPO_ROOT / "imported-skills" / "strix"
+MANIFEST_PATH = IMPORT_ROOT / "MANIFEST.json"
+
+SLUG_RE = re.compile(r"[^a-z0-9]+")
+
+
+def slugify(name: str) -> str:
+ return SLUG_RE.sub("-", name.lower()).strip("-")
+
+
+def load_manifest() -> dict:
+ if not MANIFEST_PATH.exists():
+ print(f"Manifest not found: {MANIFEST_PATH}", file=sys.stderr)
+ print("Run: python imported-skills/strix/build_manifest.py", file=sys.stderr)
+ sys.exit(1)
+ return json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
+
+
+def render_attribution_header(entry: dict, manifest: dict) -> str:
+ return (
+ f"\n"
+ )
+
+
+_SAFE_CATEGORY_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
+
+
+def _validate_manifest_field(field: str, value: object, *, regex: re.Pattern[str] | None = None) -> str:
+ """Reject manifest values that could escape the intended trust boundary."""
+ if not isinstance(value, str) or not value:
+ raise ValueError(f"{field}: expected non-empty string, got {type(value).__name__}")
+ if regex is not None and not regex.match(value):
+ raise ValueError(f"{field}: {value!r} failed strict format check")
+ return value
+
+
+def _resolve_within(root: Path, candidate_rel: str, *, field: str) -> Path:
+ """Join ``candidate_rel`` onto ``root`` and fail hard if the result escapes root.
+
+ Strix finding vuln-0001 (Path Traversal in Strix Skill Import): the
+ manifest's ``source_path`` was concatenated directly onto IMPORT_ROOT,
+ so a crafted value like ``../../etc/passwd`` would be happily read
+ and re-written into the target skills tree. Resolve both sides and
+ enforce ``relative_to`` containment before we touch the filesystem.
+ """
+ if ".." in Path(candidate_rel).parts or candidate_rel.startswith(("/", "\\")):
+ raise ValueError(f"{field}: path traversal denied in {candidate_rel!r}")
+ resolved = (root / candidate_rel).resolve()
+ root_resolved = root.resolve()
+ try:
+ resolved.relative_to(root_resolved)
+ except ValueError as exc:
+ raise ValueError(
+ f"{field}: {candidate_rel!r} resolves outside import root"
+ ) from exc
+ return resolved
+
+
+def deploy_entry(entry: dict, manifest: dict, target_dir: Path, dry_run: bool) -> tuple[Path, bool]:
+ # Manifest fields are untrusted input (the repo's imported-skills/
+ # MANIFEST.json is checked-in today, but the path from parsing to
+ # filesystem write must still be defensible). Validate category
+ # against a strict allowlist, contain source_path inside IMPORT_ROOT.
+ category = _validate_manifest_field("category", entry.get("category"), regex=_SAFE_CATEGORY_RE)
+ source_path_raw = _validate_manifest_field("source_path", entry.get("source_path"))
+ source = _resolve_within(IMPORT_ROOT, source_path_raw, field="source_path")
+
+ if not source.exists():
+ raise FileNotFoundError(f"Source skill missing: {source}")
+
+ dir_name = f"strix-{category}-{slugify(entry['name'])}"
+ skill_dir = target_dir / dir_name
+ # Same containment check on the destination — dir_name is built from
+ # validated inputs but slugify() on entry['name'] is defensive too.
+ dest_resolved = skill_dir.resolve()
+ target_resolved = target_dir.resolve()
+ try:
+ dest_resolved.relative_to(target_resolved)
+ except ValueError as exc:
+ raise ValueError(
+ f"skill dir {skill_dir} resolves outside target_dir"
+ ) from exc
+ dest = skill_dir / "SKILL.md"
+
+ header = render_attribution_header(entry, manifest)
+ body = source.read_text(encoding="utf-8")
+ if body.startswith("", 1)[1].lstrip("\n")
+ content = header + body
+
+ changed = True
+ if dest.exists():
+ existing = dest.read_text(encoding="utf-8")
+ changed = existing != content
+
+ if not dry_run and changed:
+ skill_dir.mkdir(parents=True, exist_ok=True)
+ dest.write_text(content, encoding="utf-8")
+
+ return dest, changed
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--install", action="store_true", help="Write to target dir")
+ parser.add_argument("--dry-run", action="store_true", help="Preview without writing")
+ parser.add_argument(
+ "--target",
+ default=str(cfg.skills_dir),
+ help=f"Target skills dir (default: {cfg.skills_dir})",
+ )
+ args = parser.parse_args()
+
+ if not args.install and not args.dry_run:
+ parser.error("Pass either --install or --dry-run")
+
+ manifest = load_manifest()
+ target_dir = Path(args.target).expanduser()
+
+ if args.install and not target_dir.exists():
+ print(f"Creating target dir: {target_dir}")
+ target_dir.mkdir(parents=True, exist_ok=True)
+
+ created = updated = unchanged = 0
+ for entry in manifest["entries"]:
+ dest, changed = deploy_entry(entry, manifest, target_dir, dry_run=args.dry_run)
+ if changed:
+ if dest.exists() and not args.dry_run:
+ updated += 1
+ marker = "UPD"
+ else:
+ created += 1
+ marker = "NEW"
+ else:
+ unchanged += 1
+ marker = " "
+ print(f" [{marker}] {dest.relative_to(target_dir.parent)}")
+
+ mode = "dry-run" if args.dry_run else "install"
+ print()
+ print(f"Mode: {mode} target: {target_dir}")
+ print(f"Entries: {len(manifest['entries'])} new/updated: {created + updated} unchanged: {unchanged}")
+
+ if args.install:
+ print()
+ print("Next steps:")
+ print(f" python src/catalog_builder.py --wiki {cfg.wiki_dir} --skills-dir {target_dir} \\")
+ print(f" --agents-dir {cfg.agents_dir}")
+ print(" python src/wiki_batch_entities.py --all")
+ print(" python -m ctx.core.wiki.wiki_graphify")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/kpi_dashboard.py b/src/kpi_dashboard.py
index 296f14cccc94e188791ad5bab378d82eb86433ac..bf9e07c6c0eaf987824eaade04adfd966bef2880 100644
--- a/src/kpi_dashboard.py
+++ b/src/kpi_dashboard.py
@@ -147,9 +147,9 @@ def _resolve_category(slug: str, sources: LifecycleSources) -> str:
# ────────────────────────────────────────────────────────────────────
-def _iter_quality_slugs(sidecar_dir: Path) -> list[str]:
- if not sidecar_dir.is_dir():
- return []
+def _iter_quality_slugs(sidecar_dir: Path) -> list[str]:
+ if not sidecar_dir.is_dir():
+ return []
out: list[str] = []
for path in sorted(sidecar_dir.glob("*.json")):
name = path.name
@@ -161,22 +161,22 @@ def _iter_quality_slugs(sidecar_dir: Path) -> list[str]:
if name.startswith("."):
continue
out.append(path.stem)
- return out
-
-
-def _quality_sources(sidecar_dir: Path) -> dict[str, Path]:
- out: dict[str, Path] = {
- slug: sidecar_dir
- for slug in _iter_quality_slugs(sidecar_dir)
- }
- mcp_dir = sidecar_dir / "mcp"
- if mcp_dir.is_dir():
- for slug in _iter_quality_slugs(mcp_dir):
- out.setdefault(slug, mcp_dir)
- return out
-
-
-def _iter_lifecycle_slugs(sidecar_dir: Path) -> list[str]:
+ return out
+
+
+def _quality_sources(sidecar_dir: Path) -> dict[str, Path]:
+ out: dict[str, Path] = {
+ slug: sidecar_dir
+ for slug in _iter_quality_slugs(sidecar_dir)
+ }
+ mcp_dir = sidecar_dir / "mcp"
+ if mcp_dir.is_dir():
+ for slug in _iter_quality_slugs(mcp_dir):
+ out.setdefault(slug, mcp_dir)
+ return out
+
+
+def _iter_lifecycle_slugs(sidecar_dir: Path) -> list[str]:
if not sidecar_dir.is_dir():
return []
suffix = ".lifecycle.json"
@@ -214,21 +214,21 @@ def _guess_subject(slug: str, sources: LifecycleSources) -> str:
return "skill"
-def collect_rows(
- *, sources: LifecycleSources,
-) -> list[EntityRow]:
- """Walk both sinks and return one row per known slug (union)."""
- quality_sources = _quality_sources(sources.sidecar_dir)
- quality_slugs = set(quality_sources)
+def collect_rows(
+ *, sources: LifecycleSources,
+) -> list[EntityRow]:
+ """Walk both sinks and return one row per known slug (union)."""
+ quality_sources = _quality_sources(sources.sidecar_dir)
+ quality_slugs = set(quality_sources)
lifecycle_slugs = set(_iter_lifecycle_slugs(sources.sidecar_dir))
all_slugs = sorted(quality_slugs | lifecycle_slugs)
rows: list[EntityRow] = []
for slug in all_slugs:
- try:
- score = load_quality(
- slug,
- sidecar_dir=quality_sources.get(slug, sources.sidecar_dir),
- )
+ try:
+ score = load_quality(
+ slug,
+ sidecar_dir=quality_sources.get(slug, sources.sidecar_dir),
+ )
except (json.JSONDecodeError, ValueError, OSError) as exc:
_logger.warning("kpi_dashboard: skipping %s: %s", slug, exc)
score = None
diff --git a/src/mcp_add.py b/src/mcp_add.py
index a5f90375e91bb2cd5669b20f72e843d6e42011f6..dac2887deeeb4d273c2c80bedb55c7758f223c3c 100644
--- a/src/mcp_add.py
+++ b/src/mcp_add.py
@@ -29,18 +29,18 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any
-import yaml # type: ignore[import-untyped]
-
-from ctx.core.entity_update import build_update_review, render_update_review
-from ctx_config import cfg
-from intake_pipeline import IntakeRejected, check_intake, record_embedding
-import mcp_canonical_index
+import yaml # type: ignore[import-untyped]
+
+from ctx.core.entity_update import build_update_review, render_update_review
+from ctx_config import cfg
+from intake_pipeline import IntakeRejected, check_intake, record_embedding
+import mcp_canonical_index
from mcp_entity import McpRecord
-from wiki_batch_entities import generate_mcp_page
-from ctx.core.wiki.wiki_sync import append_log, ensure_wiki, update_index
-from ctx.core.wiki.wiki_queue import enqueue_entity_upsert
-from ctx.core.wiki.wiki_utils import validate_skill_name
-from ctx.utils._fs_utils import reject_symlink_path, safe_atomic_write_text
+from wiki_batch_entities import generate_mcp_page
+from ctx.core.wiki.wiki_sync import append_log, ensure_wiki, update_index
+from ctx.core.wiki.wiki_queue import enqueue_entity_upsert
+from ctx.core.wiki.wiki_utils import validate_skill_name
+from ctx.utils._fs_utils import reject_symlink_path, safe_atomic_write_text
TODAY = datetime.now(timezone.utc).strftime("%Y-%m-%d")
@@ -237,14 +237,14 @@ def _find_existing_by_github_url(
return None
-def add_mcp(
- *,
- record: McpRecord,
- wiki_path: Path,
- dry_run: bool = False,
- review_existing: bool = False,
- update_existing: bool = False,
-) -> dict[str, Any]:
+def add_mcp(
+ *,
+ record: McpRecord,
+ wiki_path: Path,
+ dry_run: bool = False,
+ review_existing: bool = False,
+ update_existing: bool = False,
+) -> dict[str, Any]:
"""Add (or merge sources for) one MCP record into the wiki catalog.
Flow:
@@ -265,11 +265,11 @@ def add_mcp(
6. update_index + append_log (only when is_new_page).
Args:
- record: Populated McpRecord dataclass instance.
- wiki_path: Absolute path to the wiki root directory.
- dry_run: Compute everything but skip writes and embeddings.
- review_existing: Return an update review instead of mutating existing pages.
- update_existing: Apply an existing-page update after review.
+ record: Populated McpRecord dataclass instance.
+ wiki_path: Absolute path to the wiki root directory.
+ dry_run: Compute everything but skip writes and embeddings.
+ review_existing: Return an update review instead of mutating existing pages.
+ update_existing: Apply an existing-page update after review.
Returns:
dict with keys: slug, is_new_page, merged_sources, path
@@ -288,12 +288,12 @@ def add_mcp(
# listing-page records currently have only homepage_url (Phase 6
# detail-page enrichment will populate github_url so this dedup
# path becomes meaningful for them too).
- canonical_match = _find_existing_by_github_url(mcp_dir, record.github_url)
- if canonical_match is not None and canonical_match != target_path:
- target_path = canonical_match
-
- reject_symlink_path(target_path)
- target_path.parent.mkdir(parents=True, exist_ok=True)
+ canonical_match = _find_existing_by_github_url(mcp_dir, record.github_url)
+ if canonical_match is not None and canonical_match != target_path:
+ target_path = canonical_match
+
+ reject_symlink_path(target_path)
+ target_path.parent.mkdir(parents=True, exist_ok=True)
is_new_page: bool
merged_sources: list[str]
@@ -329,52 +329,52 @@ def add_mcp(
merged_sources = sorted(record.sources)
kept_description = record.description
- if is_new_page:
- final_text = generate_mcp_page(record)
- else:
- updated_fm = {
- **existing_fm,
- "sources": merged_sources,
- "description": kept_description,
- "updated": TODAY,
- }
- final_text = _rewrite_frontmatter(existing_text, updated_fm)
-
- if review_existing and not is_new_page and not update_existing:
- review = build_update_review(
- entity_type="mcp-server",
- slug=record.slug,
- existing_text=existing_text,
- proposed_text=final_text,
- )
- return {
- "slug": record.slug,
- "is_new_page": False,
- "merged_sources": merged_sources,
- "path": str(target_path),
- "skipped": True,
- "update_required": True,
- "update_review": render_update_review(review),
- "queued_job_id": None,
- }
-
- queue_job = None
- if not dry_run:
- # Phase 2 of branching: render and write. Any YAML serialization
- # failure now is a real error, not a dry-run side-effect.
- safe_atomic_write_text(target_path, final_text, encoding="utf-8")
- queue_job = enqueue_entity_upsert(
- wiki_path=wiki_path,
- entity_type="mcp-server",
- slug=record.slug,
- entity_path=target_path,
- content=final_text,
- action="created" if is_new_page else "updated",
- source="mcp_add",
- )
-
- # Phase 6b: keep the canonical sidecar index hot. Upsert on
- # every successful write so the first cross-source dedup after
+ if is_new_page:
+ final_text = generate_mcp_page(record)
+ else:
+ updated_fm = {
+ **existing_fm,
+ "sources": merged_sources,
+ "description": kept_description,
+ "updated": TODAY,
+ }
+ final_text = _rewrite_frontmatter(existing_text, updated_fm)
+
+ if review_existing and not is_new_page and not update_existing:
+ review = build_update_review(
+ entity_type="mcp-server",
+ slug=record.slug,
+ existing_text=existing_text,
+ proposed_text=final_text,
+ )
+ return {
+ "slug": record.slug,
+ "is_new_page": False,
+ "merged_sources": merged_sources,
+ "path": str(target_path),
+ "skipped": True,
+ "update_required": True,
+ "update_review": render_update_review(review),
+ "queued_job_id": None,
+ }
+
+ queue_job = None
+ if not dry_run:
+ # Phase 2 of branching: render and write. Any YAML serialization
+ # failure now is a real error, not a dry-run side-effect.
+ safe_atomic_write_text(target_path, final_text, encoding="utf-8")
+ queue_job = enqueue_entity_upsert(
+ wiki_path=wiki_path,
+ entity_type="mcp-server",
+ slug=record.slug,
+ entity_path=target_path,
+ content=final_text,
+ action="created" if is_new_page else "updated",
+ source="mcp_add",
+ )
+
+ # Phase 6b: keep the canonical sidecar index hot. Upsert on
+ # every successful write so the first cross-source dedup after
# this add is O(1) without needing a rebuild. Applies to both
# new pages AND source merges — a merge can land a github_url
# from the second source when the first source lacked one.
@@ -434,29 +434,29 @@ def add_mcp(
append_log(str(wiki_path), "add-mcp", record.slug, log_details)
return {
- "slug": record.slug,
- "is_new_page": is_new_page,
- "merged_sources": merged_sources,
- "path": str(target_path),
- "skipped": False,
- "update_required": False,
- "queued_job_id": queue_job.id if queue_job is not None else None,
- }
+ "slug": record.slug,
+ "is_new_page": is_new_page,
+ "merged_sources": merged_sources,
+ "path": str(target_path),
+ "skipped": False,
+ "update_required": False,
+ "queued_job_id": queue_job.id if queue_job is not None else None,
+ }
# ── CLI ───────────────────────────────────────────────────────────────────────
-def _process_batch(
- records: list[dict[str, Any]],
- wiki_path: Path,
- dry_run: bool,
- skip_existing: bool,
- update_existing: bool,
- mcp_entity_dir: Path,
-) -> tuple[int, int, int, int, int]:
- """Process records. Returns (added, merged, reviewed, rejected, errors)."""
- added = merged = reviewed = rejected = errors = 0
+def _process_batch(
+ records: list[dict[str, Any]],
+ wiki_path: Path,
+ dry_run: bool,
+ skip_existing: bool,
+ update_existing: bool,
+ mcp_entity_dir: Path,
+) -> tuple[int, int, int, int, int]:
+ """Process records. Returns (added, merged, reviewed, rejected, errors)."""
+ added = merged = reviewed = rejected = errors = 0
total = len(records)
for i, raw in enumerate(records, 1):
@@ -476,26 +476,26 @@ def _process_batch(
print(f" [{i}/{total}] [skipped] {record.slug}")
continue
- try:
- result = add_mcp(
- record=record,
- wiki_path=wiki_path,
- dry_run=dry_run,
- review_existing=True,
- update_existing=update_existing,
- )
- if result["is_new_page"]:
- added += 1
- status = "added"
- elif result.get("update_required"):
- reviewed += 1
- status = "update-review"
- if result.get("update_review"):
- print(result["update_review"])
- else:
- merged += 1
- status = "updated" if update_existing else "merged"
- print(f" [{i}/{total}] [{status}] {record.slug}")
+ try:
+ result = add_mcp(
+ record=record,
+ wiki_path=wiki_path,
+ dry_run=dry_run,
+ review_existing=True,
+ update_existing=update_existing,
+ )
+ if result["is_new_page"]:
+ added += 1
+ status = "added"
+ elif result.get("update_required"):
+ reviewed += 1
+ status = "update-review"
+ if result.get("update_review"):
+ print(result["update_review"])
+ else:
+ merged += 1
+ status = "updated" if update_existing else "merged"
+ print(f" [{i}/{total}] [{status}] {record.slug}")
except IntakeRejected as exc:
rejected += 1
codes = ", ".join(f.code for f in exc.decision.failures) or "unknown"
@@ -504,7 +504,7 @@ def _process_batch(
errors += 1
print(f" [{i}/{total}] ERROR: {record.slug}: {exc}", file=sys.stderr)
- return added, merged, reviewed, rejected, errors
+ return added, merged, reviewed, rejected, errors
def main() -> None:
@@ -532,16 +532,16 @@ def main() -> None:
parser.add_argument("--dry-run", action="store_true", help="Parse and validate but skip writes")
parser.add_argument("--wiki", default=str(cfg.wiki_dir), help="Wiki root path")
- parser.add_argument(
- "--skip-existing",
- action="store_true",
- help="Skip records whose entity page already exists (no source merge)",
- )
- parser.add_argument(
- "--update-existing",
- action="store_true",
- help="Apply the reviewed replacement when an MCP entity already exists",
- )
+ parser.add_argument(
+ "--skip-existing",
+ action="store_true",
+ help="Skip records whose entity page already exists (no source merge)",
+ )
+ parser.add_argument(
+ "--update-existing",
+ action="store_true",
+ help="Apply the reviewed replacement when an MCP entity already exists",
+ )
args = parser.parse_args()
wiki_path = Path(os.path.expanduser(args.wiki))
@@ -591,20 +591,20 @@ def main() -> None:
print("No records to process.", file=sys.stderr)
sys.exit(0)
- added, merged, reviewed, rejected, errors = _process_batch(
- records=raw_records,
- wiki_path=wiki_path,
- dry_run=args.dry_run,
- skip_existing=args.skip_existing,
- update_existing=args.update_existing,
- mcp_entity_dir=mcp_entity_dir,
- )
-
- dry_label = " (dry-run)" if args.dry_run else ""
- print(
- f"\nDone{dry_label}: {added} added, {merged} updated, "
- f"{reviewed} reviewed, {rejected} rejected, {errors} errors"
- )
+ added, merged, reviewed, rejected, errors = _process_batch(
+ records=raw_records,
+ wiki_path=wiki_path,
+ dry_run=args.dry_run,
+ skip_existing=args.skip_existing,
+ update_existing=args.update_existing,
+ mcp_entity_dir=mcp_entity_dir,
+ )
+
+ dry_label = " (dry-run)" if args.dry_run else ""
+ print(
+ f"\nDone{dry_label}: {added} added, {merged} updated, "
+ f"{reviewed} reviewed, {rejected} rejected, {errors} errors"
+ )
if __name__ == "__main__":
diff --git a/src/mcp_enrich.py b/src/mcp_enrich.py
index 8f5622251d28312ed034f9cde1bf5a83d4e34411..cd365a9740114c1fdeac0995d6de312173eb557b 100644
--- a/src/mcp_enrich.py
+++ b/src/mcp_enrich.py
@@ -318,10 +318,10 @@ def _render_scalar(value: Any) -> str:
# Conservative: quote on the full YAML 1.1 reserved-indicator set,
# leading block indicators, or leading/trailing whitespace. The
# unquoted path is reserved for simple alphanumeric-style values
- # that YAML's plain-scalar scanner parses unambiguously. ``<`` is
- # included so bare ``<<`` is never resolved as YAML's merge tag.
- # Mirrors install_utils._render_scalar — the two must stay aligned.
- yaml_structural = set(",[]{}:?#&*!|>%@`=\"'\\<")
+ # that YAML's plain-scalar scanner parses unambiguously. ``<`` is
+ # included so bare ``<<`` is never resolved as YAML's merge tag.
+ # Mirrors install_utils._render_scalar — the two must stay aligned.
+ yaml_structural = set(",[]{}:?#&*!|>%@`=\"'\\<")
needs_quote = (
any(ch in sanitised for ch in yaml_structural)
or (
diff --git a/src/mcp_entity.py b/src/mcp_entity.py
index d07dd07435ec792e3bb964efea92e4f5432262ea..06d5d7f982313313c8b239775294a459ab7ad18c 100644
--- a/src/mcp_entity.py
+++ b/src/mcp_entity.py
@@ -1,388 +1,388 @@
-#!/usr/bin/env python3
-"""
-mcp_entity.py -- Frozen ``McpRecord`` dataclass for the MCP-server catalog.
-
-``ctx`` already indexes skills and agents as first-class entities in the
-knowledge graph. MCP servers are the third subject type; this module is
-the Phase-1 schema they are normalised into before they ever touch disk.
-
-Design notes
-------------
-* The record is ``frozen=True`` with ``tuple`` collections so the same
- instance can be safely shared across the fetcher, the dedup layer, and
- the graph builder without defensive copies at every hop.
-* ``from_dict`` is the sole entry point for raw fetcher payloads. It is
- tolerant of garbage (unknown transports, messy slugs, short-ref GitHub
- URLs) and fails loudly only when the slug is unrecoverable — that is
- the one field downstream code cannot repair.
-* No I/O. The module is pure so it can be unit-tested without a network,
- a filesystem, or the rest of the ``ctx`` runtime wiring.
-
-See ``src/wiki_utils.SAFE_NAME_RE`` for the legacy skill-name pattern;
-MCP slugs enforce the stricter Tier-2 contract (lowercase + hyphens
-only) used by ``skill_add_detector.validate_user_supplied_slug``.
-"""
-
-from __future__ import annotations
-
-import copy
-import re
-from dataclasses import dataclass, field
-from pathlib import Path
-from typing import Any
-
-__all__ = [
- "ALLOWED_TRANSPORTS",
- "MCP_SLUG_RE",
- "McpRecord",
- "canonicalize_github_url",
- "normalize_slug",
-]
-
-# Tier-2 slug contract: lowercase, hyphens only, no leading/trailing
-# hyphen, no consecutive hyphens. Mirrors the wiki's stricter hook-side
-# validator so MCP entries are safe to use as filesystem paths and
-# graph node ids without further escaping.
-MCP_SLUG_RE = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$")
-
-# Subset of the MCP spec's transport tags we consider meaningful. Any
-# fetcher input outside this set is silently dropped — see
-# ``_normalize_transports``.
-ALLOWED_TRANSPORTS: frozenset[str] = frozenset(
- {"stdio", "http", "sse", "websocket"}
-)
-
-# GitHub URL matcher. Accepts http/https, optional ``www.``, trailing
-# ``.git`` / slash, and captures org + repo for canonical reassembly.
-# Host + scheme are matched case-insensitively (RFC 3986 §3.1 / §3.2.2);
-# the org/repo path is preserved verbatim so display case round-trips.
-_GITHUB_URL_RE = re.compile(
- r"^(?:https?://)?(?:www\.)?github\.com/"
- r"(?P[A-Za-z0-9][A-Za-z0-9._-]*)/"
- r"(?P[A-Za-z0-9][A-Za-z0-9._-]*?)"
- r"(?:\.git)?/?$",
- re.IGNORECASE,
-)
-
-# Short-ref matcher (``Org/Repo``) — only considered when the input
-# contains no scheme and exactly one ``/``. Kept separate from the URL
-# matcher so a stray ``/`` in free-text URLs doesn't falsely match.
-_GITHUB_SHORT_REF_RE = re.compile(
- r"^(?P[A-Za-z0-9][A-Za-z0-9._-]*)/"
- r"(?P[A-Za-z0-9][A-Za-z0-9._-]*?)"
- r"(?:\.git)?/?$"
-)
-
-_DESCRIPTION_MAX = 300
-_DESCRIPTION_TRUNCATE_AT = 297
-_DESCRIPTION_FALLBACK = "No description available."
-
-
-def normalize_slug(raw: str) -> str:
- """Normalize a free-text name/slug to ``[a-z0-9]+(-[a-z0-9]+)*``.
-
- Lowercases, collapses any run of non-alphanumeric characters to a
- single hyphen, and strips leading/trailing hyphens. Raises
- ``ValueError`` if nothing usable survives — downstream code cannot
- invent a slug, so failing here is the correct behaviour.
- """
- if not isinstance(raw, str):
- raise ValueError(f"slug must be str, got {type(raw).__name__}")
- lowered = raw.strip().lower()
- collapsed = re.sub(r"[^a-z0-9]+", "-", lowered).strip("-")
- if not collapsed:
- raise ValueError(f"slug normalization produced empty string from {raw!r}")
- # The collapse already guarantees the pattern, but re-assert so any
- # future regex change fails loudly rather than silently accepting
- # malformed output.
- if not MCP_SLUG_RE.match(collapsed):
- raise ValueError(f"slug {collapsed!r} does not match {MCP_SLUG_RE.pattern}")
- return collapsed
-
-
-def canonicalize_github_url(raw: str | None) -> str | None:
- """Canonicalize a GitHub URL to ``https://github.com//``.
-
- Accepts full URLs (``https://github.com/Org/Repo``), scheme-less
- variants (``github.com/Org/Repo.git``), and short refs
- (``Org/Repo``). Returns ``None`` when the input is ``None``, empty,
- or not recognisable as a GitHub reference.
-
- Case in the org/repo path is preserved — GitHub is case-insensitive
- for routing but users expect display case to round-trip. Dedup is
- handled separately by :meth:`McpRecord.canonical_dedup_key`.
- """
- if raw is None:
- return None
- candidate = raw.strip()
- if not candidate:
- return None
-
- m = _GITHUB_URL_RE.match(candidate)
- if m is None and "://" not in candidate and candidate.count("/") == 1:
- m = _GITHUB_SHORT_REF_RE.match(candidate)
- if m is None:
- return None
-
- return f"https://github.com/{m.group('org')}/{m.group('repo')}"
-
-
-def _normalize_tags(raw: object) -> tuple[str, ...]:
- """Dedupe, lowercase, sort. Fall back to ``('uncategorized',)`` if empty."""
- if not raw:
- return ("uncategorized",)
- if isinstance(raw, str):
- # Tolerate a single comma-separated string from scruffier fetchers.
- items: list[str] = [p for p in (s.strip() for s in raw.split(",")) if p]
- elif isinstance(raw, (list, tuple, set, frozenset)):
- items = [str(t).strip() for t in raw if str(t).strip()]
- else:
- return ("uncategorized",)
- cleaned = {t.lower() for t in items if t}
- if not cleaned:
- return ("uncategorized",)
- return tuple(sorted(cleaned))
-
-
-def _normalize_transports(raw: object) -> tuple[str, ...]:
- """Filter to ``ALLOWED_TRANSPORTS``, lowercase, dedupe, sort."""
- if not raw:
- return ()
- if isinstance(raw, str):
- items: list[str] = [p for p in (s.strip() for s in raw.split(",")) if p]
- elif isinstance(raw, (list, tuple, set, frozenset)):
- items = [str(t).strip() for t in raw if str(t).strip()]
- else:
- return ()
- kept = {t.lower() for t in items if t.lower() in ALLOWED_TRANSPORTS}
- return tuple(sorted(kept))
-
-
-def _normalize_description(raw: object) -> str:
- """Trim, fall back to placeholder when empty, truncate to 300 chars."""
- if not isinstance(raw, str):
- return _DESCRIPTION_FALLBACK
- trimmed = raw.strip()
- if not trimmed:
- return _DESCRIPTION_FALLBACK
- if len(trimmed) > _DESCRIPTION_MAX:
- return trimmed[:_DESCRIPTION_TRUNCATE_AT] + "..."
- return trimmed
-
-
-def _normalize_sources(raw: object) -> tuple[str, ...]:
- """Dedupe + sort sources. Empty input yields an empty tuple."""
- if not raw:
- return ()
- if isinstance(raw, str):
- items: list[str] = [p for p in (s.strip() for s in raw.split(",")) if p]
- elif isinstance(raw, (list, tuple, set, frozenset)):
- items = [str(s).strip() for s in raw if str(s).strip()]
- else:
- return ()
- cleaned = {s for s in items if s}
- return tuple(sorted(cleaned))
-
-
-def _optional_lower(raw: object) -> str | None:
- if raw is None:
- return None
- if not isinstance(raw, str):
- return None
- trimmed = raw.strip().lower()
- return trimmed or None
-
-
-def _optional_str(raw: object) -> str | None:
- if raw is None:
- return None
- if not isinstance(raw, str):
- return None
- trimmed = raw.strip()
- return trimmed or None
-
-
-def _optional_author_type(raw: object) -> str | None:
- val = _optional_lower(raw)
- if val in {"org", "user"}:
- return val
- return None
-
-
-def _optional_int(raw: object) -> int | None:
- if raw is None:
- return None
- if isinstance(raw, bool):
- # ``bool`` is an ``int`` subclass; treat it as not-a-count.
- return None
- if isinstance(raw, int):
- return raw
- if isinstance(raw, str):
- stripped = raw.strip()
- if stripped.isdigit() or (stripped.startswith("-") and stripped[1:].isdigit()):
- try:
- return int(stripped)
- except ValueError: # pragma: no cover — isdigit() guarded
- return None
- return None
-
-
-@dataclass(frozen=True)
-class McpRecord:
- """Normalized MCP-server record built from a fetcher payload.
-
- All collection fields are ``tuple`` to preserve the ``frozen=True``
- contract. ``raw`` is retained for debugging and is deep-copied on
- construction so callers cannot mutate the stored payload after the
- fact; it is never written to the entity page frontmatter.
- """
-
- # Required
- slug: str
- name: str
- description: str
- sources: tuple[str, ...]
- # Provenance
- github_url: str | None
- homepage_url: str | None
- # Classification
- tags: tuple[str, ...]
- transports: tuple[str, ...]
- language: str | None
- license: str | None
- # Authorship
- author: str | None
- author_type: str | None
- # Metrics — enriched later; None at initial fetch.
- stars: int | None
- last_commit_at: str | None
- # Raw payload — kept for debugging, never serialized to entity body.
- raw: dict[str, Any] = field(default_factory=dict)
-
- @classmethod
- def from_dict(cls, data: dict[str, Any]) -> McpRecord:
- """Build an ``McpRecord`` from a fetcher's raw dict.
-
- Normalizes slug (required), description, sources, tags, and
- transports; canonicalizes the GitHub URL; coerces optional
- string fields. Raises ``ValueError`` if the slug cannot be
- recovered from either ``slug`` or ``name``.
- """
- if not isinstance(data, dict):
- raise ValueError(f"from_dict expected dict, got {type(data).__name__}")
-
- # Prefer an explicit slug; fall back to name. Both are fed
- # through the same normalizer so the canonical form is
- # identical regardless of which field the fetcher populated.
- raw_slug = data.get("slug") or data.get("name") or ""
- if not isinstance(raw_slug, str) or not raw_slug.strip():
- raise ValueError("McpRecord requires non-empty 'slug' or 'name'")
- slug = normalize_slug(raw_slug)
-
- raw_name = data.get("name")
- if isinstance(raw_name, str) and raw_name.strip():
- name = raw_name.strip()
- else:
- # Fetcher didn't supply a display name — use the slug so the
- # record is still renderable.
- name = slug
-
- description = _normalize_description(data.get("description"))
- sources = _normalize_sources(data.get("sources"))
-
- github_url = canonicalize_github_url(
- data.get("github_url") if isinstance(data.get("github_url"), str) else None
- )
- homepage_url = _optional_str(data.get("homepage_url"))
-
- tags = _normalize_tags(data.get("tags"))
- transports = _normalize_transports(data.get("transports"))
- language = _optional_lower(data.get("language"))
- license_ = _optional_str(data.get("license"))
-
- author = _optional_str(data.get("author"))
- author_type = _optional_author_type(data.get("author_type"))
-
- stars = _optional_int(data.get("stars"))
- last_commit_at = _optional_str(data.get("last_commit_at"))
-
- raw_payload = data.get("raw")
- if isinstance(raw_payload, dict):
- raw_copy: dict[str, Any] = copy.deepcopy(raw_payload)
- else:
- # No explicit ``raw`` key: snapshot the entire input so
- # debugging has the original fetcher output available.
- raw_copy = copy.deepcopy(data)
-
- return cls(
- slug=slug,
- name=name,
- description=description,
- sources=sources,
- github_url=github_url,
- homepage_url=homepage_url,
- tags=tags,
- transports=transports,
- language=language,
- license=license_,
- author=author,
- author_type=author_type,
- stars=stars,
- last_commit_at=last_commit_at,
- raw=raw_copy,
- )
-
- def to_frontmatter(self) -> dict[str, Any]:
- """Return a dict ready for YAML frontmatter serialization.
-
- Excludes ``raw``. Includes ``type: mcp-server`` and ``created`` /
- ``updated`` placeholders (both ``None``) so the caller — which
- owns wall-clock time — can fill them without re-shaping the
- dict. Lists are emitted as ``list`` (YAML-friendly) rather than
- the internal ``tuple`` representation.
- """
- return {
- "type": "mcp-server",
- "slug": self.slug,
- "name": self.name,
- "description": self.description,
- "sources": list(self.sources),
- "github_url": self.github_url,
- "homepage_url": self.homepage_url,
- "tags": list(self.tags),
- "transports": list(self.transports),
- "language": self.language,
- "license": self.license,
- "author": self.author,
- "author_type": self.author_type,
- "stars": self.stars,
- "last_commit_at": self.last_commit_at,
- "created": None,
- "updated": None,
- }
-
- def entity_relpath(self) -> Path:
- """Return ``Path('/.md')``.
-
- ``shard`` is ``slug[0]`` for alphabetic slugs and the literal
- ``'0-9'`` when the slug starts with a digit. Sharding keeps the
- entity directory from growing into a single multi-thousand-file
- mess as the MCP catalog fills in.
- """
- first = self.slug[0]
- shard = "0-9" if first.isdigit() else first
- return Path(shard) / f"{self.slug}.md"
-
- def canonical_dedup_key(self) -> str:
- """Return the key used to detect duplicates across sources.
-
- When a GitHub URL is present we strip trailing slashes and
- lowercase the entire URL so ``https://github.com/Org/Repo`` and
- ``https://GitHub.com/org/repo/`` collapse to the same key.
- Otherwise we fall back to ``'slug:' + self.slug`` so records
- without a repo can still be deduplicated by their normalized
- slug.
- """
- if self.github_url:
- return self.github_url.rstrip("/").lower()
- return f"slug:{self.slug}"
+#!/usr/bin/env python3
+"""
+mcp_entity.py -- Frozen ``McpRecord`` dataclass for the MCP-server catalog.
+
+``ctx`` already indexes skills and agents as first-class entities in the
+knowledge graph. MCP servers are the third subject type; this module is
+the Phase-1 schema they are normalised into before they ever touch disk.
+
+Design notes
+------------
+* The record is ``frozen=True`` with ``tuple`` collections so the same
+ instance can be safely shared across the fetcher, the dedup layer, and
+ the graph builder without defensive copies at every hop.
+* ``from_dict`` is the sole entry point for raw fetcher payloads. It is
+ tolerant of garbage (unknown transports, messy slugs, short-ref GitHub
+ URLs) and fails loudly only when the slug is unrecoverable — that is
+ the one field downstream code cannot repair.
+* No I/O. The module is pure so it can be unit-tested without a network,
+ a filesystem, or the rest of the ``ctx`` runtime wiring.
+
+See ``src/wiki_utils.SAFE_NAME_RE`` for the legacy skill-name pattern;
+MCP slugs enforce the stricter Tier-2 contract (lowercase + hyphens
+only) used by ``skill_add_detector.validate_user_supplied_slug``.
+"""
+
+from __future__ import annotations
+
+import copy
+import re
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+__all__ = [
+ "ALLOWED_TRANSPORTS",
+ "MCP_SLUG_RE",
+ "McpRecord",
+ "canonicalize_github_url",
+ "normalize_slug",
+]
+
+# Tier-2 slug contract: lowercase, hyphens only, no leading/trailing
+# hyphen, no consecutive hyphens. Mirrors the wiki's stricter hook-side
+# validator so MCP entries are safe to use as filesystem paths and
+# graph node ids without further escaping.
+MCP_SLUG_RE = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$")
+
+# Subset of the MCP spec's transport tags we consider meaningful. Any
+# fetcher input outside this set is silently dropped — see
+# ``_normalize_transports``.
+ALLOWED_TRANSPORTS: frozenset[str] = frozenset(
+ {"stdio", "http", "sse", "websocket"}
+)
+
+# GitHub URL matcher. Accepts http/https, optional ``www.``, trailing
+# ``.git`` / slash, and captures org + repo for canonical reassembly.
+# Host + scheme are matched case-insensitively (RFC 3986 §3.1 / §3.2.2);
+# the org/repo path is preserved verbatim so display case round-trips.
+_GITHUB_URL_RE = re.compile(
+ r"^(?:https?://)?(?:www\.)?github\.com/"
+ r"(?P[A-Za-z0-9][A-Za-z0-9._-]*)/"
+ r"(?P[A-Za-z0-9][A-Za-z0-9._-]*?)"
+ r"(?:\.git)?/?$",
+ re.IGNORECASE,
+)
+
+# Short-ref matcher (``Org/Repo``) — only considered when the input
+# contains no scheme and exactly one ``/``. Kept separate from the URL
+# matcher so a stray ``/`` in free-text URLs doesn't falsely match.
+_GITHUB_SHORT_REF_RE = re.compile(
+ r"^(?P[A-Za-z0-9][A-Za-z0-9._-]*)/"
+ r"(?P[A-Za-z0-9][A-Za-z0-9._-]*?)"
+ r"(?:\.git)?/?$"
+)
+
+_DESCRIPTION_MAX = 300
+_DESCRIPTION_TRUNCATE_AT = 297
+_DESCRIPTION_FALLBACK = "No description available."
+
+
+def normalize_slug(raw: str) -> str:
+ """Normalize a free-text name/slug to ``[a-z0-9]+(-[a-z0-9]+)*``.
+
+ Lowercases, collapses any run of non-alphanumeric characters to a
+ single hyphen, and strips leading/trailing hyphens. Raises
+ ``ValueError`` if nothing usable survives — downstream code cannot
+ invent a slug, so failing here is the correct behaviour.
+ """
+ if not isinstance(raw, str):
+ raise ValueError(f"slug must be str, got {type(raw).__name__}")
+ lowered = raw.strip().lower()
+ collapsed = re.sub(r"[^a-z0-9]+", "-", lowered).strip("-")
+ if not collapsed:
+ raise ValueError(f"slug normalization produced empty string from {raw!r}")
+ # The collapse already guarantees the pattern, but re-assert so any
+ # future regex change fails loudly rather than silently accepting
+ # malformed output.
+ if not MCP_SLUG_RE.match(collapsed):
+ raise ValueError(f"slug {collapsed!r} does not match {MCP_SLUG_RE.pattern}")
+ return collapsed
+
+
+def canonicalize_github_url(raw: str | None) -> str | None:
+ """Canonicalize a GitHub URL to ``https://github.com//``.
+
+ Accepts full URLs (``https://github.com/Org/Repo``), scheme-less
+ variants (``github.com/Org/Repo.git``), and short refs
+ (``Org/Repo``). Returns ``None`` when the input is ``None``, empty,
+ or not recognisable as a GitHub reference.
+
+ Case in the org/repo path is preserved — GitHub is case-insensitive
+ for routing but users expect display case to round-trip. Dedup is
+ handled separately by :meth:`McpRecord.canonical_dedup_key`.
+ """
+ if raw is None:
+ return None
+ candidate = raw.strip()
+ if not candidate:
+ return None
+
+ m = _GITHUB_URL_RE.match(candidate)
+ if m is None and "://" not in candidate and candidate.count("/") == 1:
+ m = _GITHUB_SHORT_REF_RE.match(candidate)
+ if m is None:
+ return None
+
+ return f"https://github.com/{m.group('org')}/{m.group('repo')}"
+
+
+def _normalize_tags(raw: object) -> tuple[str, ...]:
+ """Dedupe, lowercase, sort. Fall back to ``('uncategorized',)`` if empty."""
+ if not raw:
+ return ("uncategorized",)
+ if isinstance(raw, str):
+ # Tolerate a single comma-separated string from scruffier fetchers.
+ items: list[str] = [p for p in (s.strip() for s in raw.split(",")) if p]
+ elif isinstance(raw, (list, tuple, set, frozenset)):
+ items = [str(t).strip() for t in raw if str(t).strip()]
+ else:
+ return ("uncategorized",)
+ cleaned = {t.lower() for t in items if t}
+ if not cleaned:
+ return ("uncategorized",)
+ return tuple(sorted(cleaned))
+
+
+def _normalize_transports(raw: object) -> tuple[str, ...]:
+ """Filter to ``ALLOWED_TRANSPORTS``, lowercase, dedupe, sort."""
+ if not raw:
+ return ()
+ if isinstance(raw, str):
+ items: list[str] = [p for p in (s.strip() for s in raw.split(",")) if p]
+ elif isinstance(raw, (list, tuple, set, frozenset)):
+ items = [str(t).strip() for t in raw if str(t).strip()]
+ else:
+ return ()
+ kept = {t.lower() for t in items if t.lower() in ALLOWED_TRANSPORTS}
+ return tuple(sorted(kept))
+
+
+def _normalize_description(raw: object) -> str:
+ """Trim, fall back to placeholder when empty, truncate to 300 chars."""
+ if not isinstance(raw, str):
+ return _DESCRIPTION_FALLBACK
+ trimmed = raw.strip()
+ if not trimmed:
+ return _DESCRIPTION_FALLBACK
+ if len(trimmed) > _DESCRIPTION_MAX:
+ return trimmed[:_DESCRIPTION_TRUNCATE_AT] + "..."
+ return trimmed
+
+
+def _normalize_sources(raw: object) -> tuple[str, ...]:
+ """Dedupe + sort sources. Empty input yields an empty tuple."""
+ if not raw:
+ return ()
+ if isinstance(raw, str):
+ items: list[str] = [p for p in (s.strip() for s in raw.split(",")) if p]
+ elif isinstance(raw, (list, tuple, set, frozenset)):
+ items = [str(s).strip() for s in raw if str(s).strip()]
+ else:
+ return ()
+ cleaned = {s for s in items if s}
+ return tuple(sorted(cleaned))
+
+
+def _optional_lower(raw: object) -> str | None:
+ if raw is None:
+ return None
+ if not isinstance(raw, str):
+ return None
+ trimmed = raw.strip().lower()
+ return trimmed or None
+
+
+def _optional_str(raw: object) -> str | None:
+ if raw is None:
+ return None
+ if not isinstance(raw, str):
+ return None
+ trimmed = raw.strip()
+ return trimmed or None
+
+
+def _optional_author_type(raw: object) -> str | None:
+ val = _optional_lower(raw)
+ if val in {"org", "user"}:
+ return val
+ return None
+
+
+def _optional_int(raw: object) -> int | None:
+ if raw is None:
+ return None
+ if isinstance(raw, bool):
+ # ``bool`` is an ``int`` subclass; treat it as not-a-count.
+ return None
+ if isinstance(raw, int):
+ return raw
+ if isinstance(raw, str):
+ stripped = raw.strip()
+ if stripped.isdigit() or (stripped.startswith("-") and stripped[1:].isdigit()):
+ try:
+ return int(stripped)
+ except ValueError: # pragma: no cover — isdigit() guarded
+ return None
+ return None
+
+
+@dataclass(frozen=True)
+class McpRecord:
+ """Normalized MCP-server record built from a fetcher payload.
+
+ All collection fields are ``tuple`` to preserve the ``frozen=True``
+ contract. ``raw`` is retained for debugging and is deep-copied on
+ construction so callers cannot mutate the stored payload after the
+ fact; it is never written to the entity page frontmatter.
+ """
+
+ # Required
+ slug: str
+ name: str
+ description: str
+ sources: tuple[str, ...]
+ # Provenance
+ github_url: str | None
+ homepage_url: str | None
+ # Classification
+ tags: tuple[str, ...]
+ transports: tuple[str, ...]
+ language: str | None
+ license: str | None
+ # Authorship
+ author: str | None
+ author_type: str | None
+ # Metrics — enriched later; None at initial fetch.
+ stars: int | None
+ last_commit_at: str | None
+ # Raw payload — kept for debugging, never serialized to entity body.
+ raw: dict[str, Any] = field(default_factory=dict)
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> McpRecord:
+ """Build an ``McpRecord`` from a fetcher's raw dict.
+
+ Normalizes slug (required), description, sources, tags, and
+ transports; canonicalizes the GitHub URL; coerces optional
+ string fields. Raises ``ValueError`` if the slug cannot be
+ recovered from either ``slug`` or ``name``.
+ """
+ if not isinstance(data, dict):
+ raise ValueError(f"from_dict expected dict, got {type(data).__name__}")
+
+ # Prefer an explicit slug; fall back to name. Both are fed
+ # through the same normalizer so the canonical form is
+ # identical regardless of which field the fetcher populated.
+ raw_slug = data.get("slug") or data.get("name") or ""
+ if not isinstance(raw_slug, str) or not raw_slug.strip():
+ raise ValueError("McpRecord requires non-empty 'slug' or 'name'")
+ slug = normalize_slug(raw_slug)
+
+ raw_name = data.get("name")
+ if isinstance(raw_name, str) and raw_name.strip():
+ name = raw_name.strip()
+ else:
+ # Fetcher didn't supply a display name — use the slug so the
+ # record is still renderable.
+ name = slug
+
+ description = _normalize_description(data.get("description"))
+ sources = _normalize_sources(data.get("sources"))
+
+ github_url = canonicalize_github_url(
+ data.get("github_url") if isinstance(data.get("github_url"), str) else None
+ )
+ homepage_url = _optional_str(data.get("homepage_url"))
+
+ tags = _normalize_tags(data.get("tags"))
+ transports = _normalize_transports(data.get("transports"))
+ language = _optional_lower(data.get("language"))
+ license_ = _optional_str(data.get("license"))
+
+ author = _optional_str(data.get("author"))
+ author_type = _optional_author_type(data.get("author_type"))
+
+ stars = _optional_int(data.get("stars"))
+ last_commit_at = _optional_str(data.get("last_commit_at"))
+
+ raw_payload = data.get("raw")
+ if isinstance(raw_payload, dict):
+ raw_copy: dict[str, Any] = copy.deepcopy(raw_payload)
+ else:
+ # No explicit ``raw`` key: snapshot the entire input so
+ # debugging has the original fetcher output available.
+ raw_copy = copy.deepcopy(data)
+
+ return cls(
+ slug=slug,
+ name=name,
+ description=description,
+ sources=sources,
+ github_url=github_url,
+ homepage_url=homepage_url,
+ tags=tags,
+ transports=transports,
+ language=language,
+ license=license_,
+ author=author,
+ author_type=author_type,
+ stars=stars,
+ last_commit_at=last_commit_at,
+ raw=raw_copy,
+ )
+
+ def to_frontmatter(self) -> dict[str, Any]:
+ """Return a dict ready for YAML frontmatter serialization.
+
+ Excludes ``raw``. Includes ``type: mcp-server`` and ``created`` /
+ ``updated`` placeholders (both ``None``) so the caller — which
+ owns wall-clock time — can fill them without re-shaping the
+ dict. Lists are emitted as ``list`` (YAML-friendly) rather than
+ the internal ``tuple`` representation.
+ """
+ return {
+ "type": "mcp-server",
+ "slug": self.slug,
+ "name": self.name,
+ "description": self.description,
+ "sources": list(self.sources),
+ "github_url": self.github_url,
+ "homepage_url": self.homepage_url,
+ "tags": list(self.tags),
+ "transports": list(self.transports),
+ "language": self.language,
+ "license": self.license,
+ "author": self.author,
+ "author_type": self.author_type,
+ "stars": self.stars,
+ "last_commit_at": self.last_commit_at,
+ "created": None,
+ "updated": None,
+ }
+
+ def entity_relpath(self) -> Path:
+ """Return ``Path('/.md')``.
+
+ ``shard`` is ``slug[0]`` for alphabetic slugs and the literal
+ ``'0-9'`` when the slug starts with a digit. Sharding keeps the
+ entity directory from growing into a single multi-thousand-file
+ mess as the MCP catalog fills in.
+ """
+ first = self.slug[0]
+ shard = "0-9" if first.isdigit() else first
+ return Path(shard) / f"{self.slug}.md"
+
+ def canonical_dedup_key(self) -> str:
+ """Return the key used to detect duplicates across sources.
+
+ When a GitHub URL is present we strip trailing slashes and
+ lowercase the entire URL so ``https://github.com/Org/Repo`` and
+ ``https://GitHub.com/org/repo/`` collapse to the same key.
+ Otherwise we fall back to ``'slug:' + self.slug`` so records
+ without a repo can still be deduplicated by their normalized
+ slug.
+ """
+ if self.github_url:
+ return self.github_url.rstrip("/").lower()
+ return f"slug:{self.slug}"
diff --git a/src/mcp_fetch.py b/src/mcp_fetch.py
index f3bdb8e5cf318a2612fe2defe31541f7430b9cd1..14706631a111f1186573ce77ba8dda8d0b85013d 100644
--- a/src/mcp_fetch.py
+++ b/src/mcp_fetch.py
@@ -44,7 +44,7 @@ def _emit(records: Iterator[dict]) -> int:
def _run_one(
- source_name: str, *, limit: int | None, refresh: bool
+ source_name: str, *, limit: int | None, refresh: bool, verbosity: int = 0
) -> tuple[int, int]:
"""Fetch from a single named source. Return ``(emitted, errors)``."""
try:
@@ -63,14 +63,15 @@ def _run_one(
print(f"Error: source {source_name!r} failed: {exc}", file=sys.stderr)
return 0, 1
- print(
- f"[{source_name}] emitted {emitted} record(s)",
- file=sys.stderr,
- )
+ if verbosity > 0:
+ print(
+ f"[{source_name}] emitted {emitted} record(s)",
+ file=sys.stderr,
+ )
return emitted, 0
-def _run_all(*, limit: int | None) -> tuple[int, int]:
+def _run_all(*, limit: int | None, verbosity: int = 0) -> tuple[int, int]:
"""Fetch from every registered source, summing emissions and errors.
``--limit`` applies *per source*. Applying a single global cap would
@@ -80,7 +81,7 @@ def _run_all(*, limit: int | None) -> tuple[int, int]:
total_emitted = 0
total_errors = 0
for name in sorted(SOURCES):
- emitted, errors = _run_one(name, limit=limit, refresh=False)
+ emitted, errors = _run_one(name, limit=limit, refresh=False, verbosity=verbosity)
total_emitted += emitted
total_errors += errors
return total_emitted, total_errors
@@ -211,9 +212,14 @@ def main() -> None:
file=sys.stderr,
)
sys.exit(2)
- _, errors = _run_all(limit=args.limit)
+ _, errors = _run_all(limit=args.limit, verbosity=args.verbose)
else:
- _, errors = _run_one(args.source, limit=args.limit, refresh=args.refresh)
+ _, errors = _run_one(
+ args.source,
+ limit=args.limit,
+ refresh=args.refresh,
+ verbosity=args.verbose,
+ )
sys.exit(1 if errors else 0)
diff --git a/src/mcp_quality.py b/src/mcp_quality.py
index a759d49098fd88df2dc6cdb18b2f35e789521e26..287770b693491baf083812bb8739468f397a5f6f 100644
--- a/src/mcp_quality.py
+++ b/src/mcp_quality.py
@@ -255,7 +255,7 @@ def compute_quality(
)
raw = sum(cfg.weights[name] * signals[name].score for name in _MCP_WEIGHT_KEYS)
- score = max(0.0, min(1.0, raw))
+ score = round(max(0.0, min(1.0, raw)), 10)
grade = _grade_from_score(score, cfg.grade_thresholds)
return McpQualityScore(
diff --git a/src/mcp_rebuild_index.py b/src/mcp_rebuild_index.py
index 1abf571144db69b36c34c5ff15205241b45f9c27..a9846ed5e726e8822d2c495956b2c4829fc12752 100644
--- a/src/mcp_rebuild_index.py
+++ b/src/mcp_rebuild_index.py
@@ -1,113 +1,113 @@
-#!/usr/bin/env python3
-"""
-mcp_rebuild_index.py -- Rebuild the canonical-key sidecar index from disk.
-
-Usage
------
- ctx-mcp-rebuild-index [--wiki PATH] [--dry-run]
-
-Reads every ``*.md`` under ``/entities/mcp-servers/``, parses its
-YAML frontmatter, and writes
-``/entities/mcp-servers/.canonical-index.json`` with a fresh
-``github_url -> {slug, relpath}`` map.
-
-Intended to be run:
-
-- Once, to backfill the sidecar for the entities that existed before
- Phase 6b (the ``add_mcp`` hot-path upsert only covers records added
- after the feature landed).
-- Any time the index is suspected stale (manual edits, restored from
- backup, cross-wiki merge). The normal scan-and-repair fallback in
- ``_find_existing_by_github_url`` handles one-off drift, but a full
- rebuild is cheap (~1 s at 15k entities) and gives a clean baseline.
-
-Exit codes: 0 on success, 2 on missing wiki path, 1 on unexpected error.
-"""
-
-from __future__ import annotations
-
-import argparse
-import os
-import sys
-from pathlib import Path
-
-from ctx_config import cfg
-from mcp_canonical_index import rebuild_from_scan
-
-_MCP_ENTITY_SUBDIR = "entities/mcp-servers"
-
-
-def main() -> None:
- """Entry point for ``ctx-mcp-rebuild-index``."""
- parser = argparse.ArgumentParser(
- prog="ctx-mcp-rebuild-index",
- description=(
- "Rebuild the canonical-key sidecar index from existing MCP entity "
- "pages. Idempotent; safe to run repeatedly."
- ),
- )
- parser.add_argument(
- "--wiki",
- default=str(cfg.wiki_dir),
- help="Wiki root path (default: config wiki_dir)",
- )
- parser.add_argument(
- "--dry-run",
- action="store_true",
- help="Scan and report counts without writing the sidecar file",
- )
- args = parser.parse_args()
-
- wiki_path = Path(os.path.expanduser(args.wiki))
- mcp_dir = wiki_path / _MCP_ENTITY_SUBDIR
-
- if not mcp_dir.is_dir():
- print(
- f"Error: MCP entity directory does not exist: {mcp_dir}",
- file=sys.stderr,
- )
- sys.exit(2)
-
- if args.dry_run:
- # Dry-run uses the same traversal but discards the write. Easiest
- # way is to call the real rebuild, then overwrite the file back
- # — but that's still a write. Instead, walk inline and count.
- indexed = 0
- skipped = 0
- for page in mcp_dir.rglob("*.md"):
- if page.name.startswith("."):
- skipped += 1
- continue
- # Lazy import to match the module pattern.
- from mcp_add import _normalize_github_url, _parse_frontmatter # noqa: PLC0415
- try:
- text = page.read_text(encoding="utf-8", errors="replace")
- except OSError:
- skipped += 1
- continue
- fm = _parse_frontmatter(text)
- if _normalize_github_url(fm.get("github_url")) is None:
- skipped += 1
- else:
- indexed += 1
- print(
- f"[dry-run] would index {indexed} entities, "
- f"skip {skipped} (no github_url or unreadable)."
- )
- sys.exit(0)
-
- try:
- _, indexed, skipped = rebuild_from_scan(mcp_dir)
- except Exception as exc: # noqa: BLE001 — surface any failure to operator
- print(f"Error: rebuild failed: {exc}", file=sys.stderr)
- sys.exit(1)
-
- print(
- f"Canonical index rebuilt: {indexed} entities indexed, "
- f"{skipped} skipped (no github_url)."
- )
- sys.exit(0)
-
-
-if __name__ == "__main__":
- main()
+#!/usr/bin/env python3
+"""
+mcp_rebuild_index.py -- Rebuild the canonical-key sidecar index from disk.
+
+Usage
+-----
+ ctx-mcp-rebuild-index [--wiki PATH] [--dry-run]
+
+Reads every ``*.md`` under ``/entities/mcp-servers/``, parses its
+YAML frontmatter, and writes
+``/entities/mcp-servers/.canonical-index.json`` with a fresh
+``github_url -> {slug, relpath}`` map.
+
+Intended to be run:
+
+- Once, to backfill the sidecar for the entities that existed before
+ Phase 6b (the ``add_mcp`` hot-path upsert only covers records added
+ after the feature landed).
+- Any time the index is suspected stale (manual edits, restored from
+ backup, cross-wiki merge). The normal scan-and-repair fallback in
+ ``_find_existing_by_github_url`` handles one-off drift, but a full
+ rebuild is cheap (~1 s at 15k entities) and gives a clean baseline.
+
+Exit codes: 0 on success, 2 on missing wiki path, 1 on unexpected error.
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import sys
+from pathlib import Path
+
+from ctx_config import cfg
+from mcp_canonical_index import rebuild_from_scan
+
+_MCP_ENTITY_SUBDIR = "entities/mcp-servers"
+
+
+def main() -> None:
+ """Entry point for ``ctx-mcp-rebuild-index``."""
+ parser = argparse.ArgumentParser(
+ prog="ctx-mcp-rebuild-index",
+ description=(
+ "Rebuild the canonical-key sidecar index from existing MCP entity "
+ "pages. Idempotent; safe to run repeatedly."
+ ),
+ )
+ parser.add_argument(
+ "--wiki",
+ default=str(cfg.wiki_dir),
+ help="Wiki root path (default: config wiki_dir)",
+ )
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Scan and report counts without writing the sidecar file",
+ )
+ args = parser.parse_args()
+
+ wiki_path = Path(os.path.expanduser(args.wiki))
+ mcp_dir = wiki_path / _MCP_ENTITY_SUBDIR
+
+ if not mcp_dir.is_dir():
+ print(
+ f"Error: MCP entity directory does not exist: {mcp_dir}",
+ file=sys.stderr,
+ )
+ sys.exit(2)
+
+ if args.dry_run:
+ # Dry-run uses the same traversal but discards the write. Easiest
+ # way is to call the real rebuild, then overwrite the file back
+ # — but that's still a write. Instead, walk inline and count.
+ indexed = 0
+ skipped = 0
+ for page in mcp_dir.rglob("*.md"):
+ if page.name.startswith("."):
+ skipped += 1
+ continue
+ # Lazy import to match the module pattern.
+ from mcp_add import _normalize_github_url, _parse_frontmatter # noqa: PLC0415
+ try:
+ text = page.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ skipped += 1
+ continue
+ fm = _parse_frontmatter(text)
+ if _normalize_github_url(fm.get("github_url")) is None:
+ skipped += 1
+ else:
+ indexed += 1
+ print(
+ f"[dry-run] would index {indexed} entities, "
+ f"skip {skipped} (no github_url or unreadable)."
+ )
+ sys.exit(0)
+
+ try:
+ _, indexed, skipped = rebuild_from_scan(mcp_dir)
+ except Exception as exc: # noqa: BLE001 — surface any failure to operator
+ print(f"Error: rebuild failed: {exc}", file=sys.stderr)
+ sys.exit(1)
+
+ print(
+ f"Canonical index rebuilt: {indexed} entities indexed, "
+ f"{skipped} skipped (no github_url)."
+ )
+ sys.exit(0)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/mcp_sources/__init__.py b/src/mcp_sources/__init__.py
index a956e8bfd7384aa2bfc02dc60f65869b2d038012..66392fb72bb24cb423aea75eca7ae33c7b618e5e 100644
--- a/src/mcp_sources/__init__.py
+++ b/src/mcp_sources/__init__.py
@@ -1,23 +1,23 @@
-"""Registry of MCP catalog sources.
-
-Each :class:`~mcp_sources.base.Source` implementation lives in
-``mcp_sources/.py`` and exposes a module-level ``SOURCE`` attribute.
-This package imports every known source eagerly and maps its ``name`` into
-:data:`SOURCES` so CLI dispatchers can resolve ``--source `` without
-reflection or entry-point discovery.
-
-Adding a source is a two-line patch here plus the new module file; keep the
-list alphabetical so reviewers can tell at a glance whether a source is
-already registered.
-"""
-
-from mcp_sources.awesome_mcp import SOURCE as _AWESOME
-from mcp_sources.base import Source
-from mcp_sources.pulsemcp import SOURCE as _PULSEMCP
-
-SOURCES: dict[str, Source] = {
- _AWESOME.name: _AWESOME,
- _PULSEMCP.name: _PULSEMCP,
-}
-
-__all__ = ["SOURCES", "Source"]
+"""Registry of MCP catalog sources.
+
+Each :class:`~mcp_sources.base.Source` implementation lives in
+``mcp_sources/.py`` and exposes a module-level ``SOURCE`` attribute.
+This package imports every known source eagerly and maps its ``name`` into
+:data:`SOURCES` so CLI dispatchers can resolve ``--source `` without
+reflection or entry-point discovery.
+
+Adding a source is a two-line patch here plus the new module file; keep the
+list alphabetical so reviewers can tell at a glance whether a source is
+already registered.
+"""
+
+from mcp_sources.awesome_mcp import SOURCE as _AWESOME
+from mcp_sources.base import Source
+from mcp_sources.pulsemcp import SOURCE as _PULSEMCP
+
+SOURCES: dict[str, Source] = {
+ _AWESOME.name: _AWESOME,
+ _PULSEMCP.name: _PULSEMCP,
+}
+
+__all__ = ["SOURCES", "Source"]
diff --git a/src/mcp_sources/awesome_mcp.py b/src/mcp_sources/awesome_mcp.py
index 39fa6f505d84c2c0231e1f1376e6f149512d0489..ad40eb0e534fb8a0b4708d398989d8f2cbb9d270 100644
--- a/src/mcp_sources/awesome_mcp.py
+++ b/src/mcp_sources/awesome_mcp.py
@@ -1,263 +1,263 @@
-"""src/mcp_sources/awesome_mcp.py -- Source for github.com/punkpeye/awesome-mcp-servers.
-
-Parses the README markdown into raw McpRecord-shaped dicts.
-
-README structure (as observed 2026-04-20):
-- ## Server Implementations (top-level gate — only parse after this heading)
-- ### (section headers)
-- - [name](url) [badge markup] [emoji flags] - description (entry lines)
-
-Entry separators may be ` - `, ` – ` (en-dash), or ` — ` (em-dash).
-Some entries have no description. Badge markup ([!img](url)) is stripped.
-Language is inferred from emoji annotation in the entry line.
-"""
-
-from __future__ import annotations
-
-import logging
-import re
-from collections.abc import Iterator
-from datetime import date
-
-from mcp_sources.base import Source, fetch_text, read_cache, write_cache
-
-_logger = logging.getLogger(__name__)
-
-
-URL = "https://raw.githubusercontent.com/punkpeye/awesome-mcp-servers/main/README.md"
-
-# ---------------------------------------------------------------------------
-# Language emoji -> language name map (from the README legend)
-# ---------------------------------------------------------------------------
-_LANG_EMOJI: dict[str, str] = {
- "\U0001f40d": "python", # 🐍
- "\U0001f4c7": "typescript", # 📇 (card index dividers — TS/JS)
- "\U0001f3ce\ufe0f": "go", # 🏎️
- "\U0001f980": "rust", # 🦀
- "#\ufe0f\u20e3": "csharp", # #️⃣
- "\u2615": "java", # ☕
- "\U0001f30a": "c/c++", # 🌊
- "\U0001f48e": "ruby", # 💎
-}
-
-# Badge image markup: [](link-url) — strip entirely
-_BADGE_RE = re.compile(r"\[!\[.*?\]\(.*?\)\]\(.*?\)")
-
-# Inline image (no outer link): 
-_INLINE_IMG_RE = re.compile(r"!\[.*?\]\(.*?\)")
-
-# Markdown link: [text](url)
-_LINK_RE = re.compile(r"\[([^\]]*)\]\(([^)]*)\)")
-
-# Section heading: ### ... Title
-_SECTION_H3_RE = re.compile(r"^#{1,3}\s+(.+)$")
-
-# Anchor tag used inside headings:
-_ANCHOR_TAG_RE = re.compile(r"]*>.*?", re.IGNORECASE)
-
-# Non-ASCII characters (for stripping emoji before slugifying section names)
-_NON_ASCII_RE = re.compile(r"[^\x00-\x7f]")
-
-# Description separators: ` - `, ` – `, ` — ` (with surrounding spaces)
-_DESC_SEP_RE = re.compile(r"\s[-\u2013\u2014]\s")
-
-# The ## heading that gates the server entry section
-_SERVER_SECTION_MARKER = "Server Implementations"
-
-# Sections we know are not server entries (after ## Server Implementations ends
-# another ## heading appears — we stop at the next ## that isn't a sub-section)
-_STOP_MARKER_RE = re.compile(r"^##\s+(?!#)")
-
-
-def _section_to_tag(raw_heading: str) -> str:
- """Convert a raw ### heading text to a hyphenated lowercase tag.
-
- Strips HTML anchor tags, emoji/non-ASCII, normalizes whitespace,
- and collapses runs of non-alphanumeric characters to single hyphens.
-
- Examples::
-
- "🔗 Aggregators" -> "aggregators"
- "🔄 Version Control" -> "version-control"
- "Biology, Medicine and Bioinformatics" -> "biology-medicine-and-bioinformatics"
- """
- # Remove HTML anchor tags
- text = _ANCHOR_TAG_RE.sub("", raw_heading)
- # Remove non-ASCII (emoji, etc.)
- text = _NON_ASCII_RE.sub("", text)
- # Lowercase and collapse runs of non-alphanumeric to hyphen
- text = text.strip().lower()
- text = re.sub(r"[^a-z0-9]+", "-", text).strip("-")
- return text or "uncategorized"
-
-
-def _detect_language(line: str) -> str | None:
- """Return a language string if a known language emoji is present."""
- for emoji, lang in _LANG_EMOJI.items():
- if emoji in line:
- return lang
- return None
-
-
-def _strip_badges_and_links(text: str) -> tuple[str, list[tuple[str, str]]]:
- """Remove badge markup from *text*, return cleaned text + list of (label, url) links."""
- cleaned = _BADGE_RE.sub("", text)
- cleaned = _INLINE_IMG_RE.sub("", cleaned)
- links = _LINK_RE.findall(cleaned)
- return cleaned, links
-
-
-def _parse_readme(text: str) -> list[dict]: # noqa: C901 — complexity justified by format variance
- """Walk the README headings + bullets, yield one dict per server entry.
-
- Pure function — no I/O. Designed to be easy to unit-test against a
- fixture excerpt.
-
- Args:
- text: Full contents of the README markdown file.
-
- Returns:
- List of raw dicts, each acceptable to ``McpRecord.from_dict()``.
- """
- records: list[dict] = []
- skipped = 0
-
- in_server_section = False
- current_tag: str = "uncategorized"
-
- for raw_line in text.splitlines():
- line = raw_line.rstrip()
-
- # ----------------------------------------------------------------
- # Track ## / ### headings
- # ----------------------------------------------------------------
- if line.startswith("##"):
- # A bare ## (not ###) is either the gate-in or the gate-out
- if not line.startswith("###"):
- if _SERVER_SECTION_MARKER in line:
- in_server_section = True
- elif in_server_section:
- # Next top-level ## ends the server listing
- in_server_section = False
- continue
-
- # ### section inside server implementations
- if in_server_section:
- m = _SECTION_H3_RE.match(line)
- if m:
- current_tag = _section_to_tag(m.group(1))
- continue
-
- if not in_server_section:
- continue
-
- # ----------------------------------------------------------------
- # Entry lines start with `- ` (possibly leading whitespace)
- # ----------------------------------------------------------------
- stripped = line.lstrip()
- if not stripped.startswith("- "):
- continue
-
- entry_body = stripped[2:] # drop the leading "- "
-
- # Strip badge markup first, collect all plain links
- clean_body, links = _strip_badges_and_links(entry_body)
-
- if not links:
- # No markdown link at all — skip (section description, back-to-top, etc.)
- skipped += 1
- _logger.debug("skip (no link): %r", entry_body[:80])
- continue
-
- # First link is the primary entry link
- name, primary_url = links[0]
- name = name.strip()
- if not name:
- skipped += 1
- _logger.debug("skip (empty name): %r", entry_body[:80])
- continue
-
- # Classify URL
- github_url: str | None = None
- homepage_url: str | None = None
- primary_url = primary_url.strip()
- if re.match(r"^https?://(?:www\.)?github\.com/", primary_url, re.IGNORECASE):
- github_url = primary_url
- else:
- homepage_url = primary_url if primary_url else None
-
- # ----------------------------------------------------------------
- # Extract description: text after the first ` - `/ ` – `/ ` — ` separator
- # ----------------------------------------------------------------
- # Work on the cleaned body (badges removed) but preserve the original
- # link text so the separator search is stable.
- # We find the separator that appears AFTER the first link's closing `)`
- first_link_end = clean_body.find(")", clean_body.find("]("))
- search_from = first_link_end + 1 if first_link_end != -1 else 0
- tail = clean_body[search_from:]
-
- desc_match = _DESC_SEP_RE.search(tail)
- if desc_match:
- description: str | None = tail[desc_match.end():].strip()
- if not description:
- description = None
- else:
- description = None
-
- # Detect language from the full original line (before cleaning)
- language = _detect_language(entry_body)
-
- record: dict = {
- "name": name,
- "sources": ["awesome-mcp"],
- "tags": [current_tag],
- }
- if description:
- record["description"] = description
- if github_url:
- record["github_url"] = github_url
- if homepage_url:
- record["homepage_url"] = homepage_url
- if language:
- record["language"] = language
-
- records.append(record)
-
- _logger.info("parsed %d entries, skipped %d", len(records), skipped)
- return records
-
-
-# ---------------------------------------------------------------------------
-# Source class
-# ---------------------------------------------------------------------------
-
-
-class _AwesomeMcpSource:
- name = "awesome-mcp"
- homepage = "https://github.com/punkpeye/awesome-mcp-servers"
-
- def fetch(self, *, limit: int | None = None, refresh: bool = False) -> Iterator[dict]:
- """Yield raw records. Caches the README at raw/marketplace-dumps/awesome-mcp/.
-
- Args:
- limit: If set, yield at most this many records.
- refresh: If ``True``, bypass the cache and re-fetch from network.
-
- Yields:
- Raw dicts suitable for ``McpRecord.from_dict()``.
- """
- cache_basename = f"README-{date.today().isoformat()}.md"
- text: str | None = None
- if not refresh:
- text = read_cache(self.name, cache_basename)
- if text is None:
- text = fetch_text(URL)
- write_cache(self.name, cache_basename, text)
- records = _parse_readme(text)
- if limit is not None:
- records = records[:limit]
- for r in records:
- yield r
-
-
-SOURCE: Source = _AwesomeMcpSource()
+"""src/mcp_sources/awesome_mcp.py -- Source for github.com/punkpeye/awesome-mcp-servers.
+
+Parses the README markdown into raw McpRecord-shaped dicts.
+
+README structure (as observed 2026-04-20):
+- ## Server Implementations (top-level gate — only parse after this heading)
+- ### (section headers)
+- - [name](url) [badge markup] [emoji flags] - description (entry lines)
+
+Entry separators may be ` - `, ` – ` (en-dash), or ` — ` (em-dash).
+Some entries have no description. Badge markup ([!img](url)) is stripped.
+Language is inferred from emoji annotation in the entry line.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+from collections.abc import Iterator
+from datetime import date
+
+from mcp_sources.base import Source, fetch_text, read_cache, write_cache
+
+_logger = logging.getLogger(__name__)
+
+
+URL = "https://raw.githubusercontent.com/punkpeye/awesome-mcp-servers/main/README.md"
+
+# ---------------------------------------------------------------------------
+# Language emoji -> language name map (from the README legend)
+# ---------------------------------------------------------------------------
+_LANG_EMOJI: dict[str, str] = {
+ "\U0001f40d": "python", # 🐍
+ "\U0001f4c7": "typescript", # 📇 (card index dividers — TS/JS)
+ "\U0001f3ce\ufe0f": "go", # 🏎️
+ "\U0001f980": "rust", # 🦀
+ "#\ufe0f\u20e3": "csharp", # #️⃣
+ "\u2615": "java", # ☕
+ "\U0001f30a": "c/c++", # 🌊
+ "\U0001f48e": "ruby", # 💎
+}
+
+# Badge image markup: [](link-url) — strip entirely
+_BADGE_RE = re.compile(r"\[!\[.*?\]\(.*?\)\]\(.*?\)")
+
+# Inline image (no outer link): 
+_INLINE_IMG_RE = re.compile(r"!\[.*?\]\(.*?\)")
+
+# Markdown link: [text](url)
+_LINK_RE = re.compile(r"\[([^\]]*)\]\(([^)]*)\)")
+
+# Section heading: ### ... Title
+_SECTION_H3_RE = re.compile(r"^#{1,3}\s+(.+)$")
+
+# Anchor tag used inside headings:
+_ANCHOR_TAG_RE = re.compile(r"]*>.*?", re.IGNORECASE)
+
+# Non-ASCII characters (for stripping emoji before slugifying section names)
+_NON_ASCII_RE = re.compile(r"[^\x00-\x7f]")
+
+# Description separators: ` - `, ` – `, ` — ` (with surrounding spaces)
+_DESC_SEP_RE = re.compile(r"\s[-\u2013\u2014]\s")
+
+# The ## heading that gates the server entry section
+_SERVER_SECTION_MARKER = "Server Implementations"
+
+# Sections we know are not server entries (after ## Server Implementations ends
+# another ## heading appears — we stop at the next ## that isn't a sub-section)
+_STOP_MARKER_RE = re.compile(r"^##\s+(?!#)")
+
+
+def _section_to_tag(raw_heading: str) -> str:
+ """Convert a raw ### heading text to a hyphenated lowercase tag.
+
+ Strips HTML anchor tags, emoji/non-ASCII, normalizes whitespace,
+ and collapses runs of non-alphanumeric characters to single hyphens.
+
+ Examples::
+
+ "🔗 Aggregators" -> "aggregators"
+ "🔄 Version Control" -> "version-control"
+ "Biology, Medicine and Bioinformatics" -> "biology-medicine-and-bioinformatics"
+ """
+ # Remove HTML anchor tags
+ text = _ANCHOR_TAG_RE.sub("", raw_heading)
+ # Remove non-ASCII (emoji, etc.)
+ text = _NON_ASCII_RE.sub("", text)
+ # Lowercase and collapse runs of non-alphanumeric to hyphen
+ text = text.strip().lower()
+ text = re.sub(r"[^a-z0-9]+", "-", text).strip("-")
+ return text or "uncategorized"
+
+
+def _detect_language(line: str) -> str | None:
+ """Return a language string if a known language emoji is present."""
+ for emoji, lang in _LANG_EMOJI.items():
+ if emoji in line:
+ return lang
+ return None
+
+
+def _strip_badges_and_links(text: str) -> tuple[str, list[tuple[str, str]]]:
+ """Remove badge markup from *text*, return cleaned text + list of (label, url) links."""
+ cleaned = _BADGE_RE.sub("", text)
+ cleaned = _INLINE_IMG_RE.sub("", cleaned)
+ links = _LINK_RE.findall(cleaned)
+ return cleaned, links
+
+
+def _parse_readme(text: str) -> list[dict]: # noqa: C901 — complexity justified by format variance
+ """Walk the README headings + bullets, yield one dict per server entry.
+
+ Pure function — no I/O. Designed to be easy to unit-test against a
+ fixture excerpt.
+
+ Args:
+ text: Full contents of the README markdown file.
+
+ Returns:
+ List of raw dicts, each acceptable to ``McpRecord.from_dict()``.
+ """
+ records: list[dict] = []
+ skipped = 0
+
+ in_server_section = False
+ current_tag: str = "uncategorized"
+
+ for raw_line in text.splitlines():
+ line = raw_line.rstrip()
+
+ # ----------------------------------------------------------------
+ # Track ## / ### headings
+ # ----------------------------------------------------------------
+ if line.startswith("##"):
+ # A bare ## (not ###) is either the gate-in or the gate-out
+ if not line.startswith("###"):
+ if _SERVER_SECTION_MARKER in line:
+ in_server_section = True
+ elif in_server_section:
+ # Next top-level ## ends the server listing
+ in_server_section = False
+ continue
+
+ # ### section inside server implementations
+ if in_server_section:
+ m = _SECTION_H3_RE.match(line)
+ if m:
+ current_tag = _section_to_tag(m.group(1))
+ continue
+
+ if not in_server_section:
+ continue
+
+ # ----------------------------------------------------------------
+ # Entry lines start with `- ` (possibly leading whitespace)
+ # ----------------------------------------------------------------
+ stripped = line.lstrip()
+ if not stripped.startswith("- "):
+ continue
+
+ entry_body = stripped[2:] # drop the leading "- "
+
+ # Strip badge markup first, collect all plain links
+ clean_body, links = _strip_badges_and_links(entry_body)
+
+ if not links:
+ # No markdown link at all — skip (section description, back-to-top, etc.)
+ skipped += 1
+ _logger.debug("skip (no link): %r", entry_body[:80])
+ continue
+
+ # First link is the primary entry link
+ name, primary_url = links[0]
+ name = name.strip()
+ if not name:
+ skipped += 1
+ _logger.debug("skip (empty name): %r", entry_body[:80])
+ continue
+
+ # Classify URL
+ github_url: str | None = None
+ homepage_url: str | None = None
+ primary_url = primary_url.strip()
+ if re.match(r"^https?://(?:www\.)?github\.com/", primary_url, re.IGNORECASE):
+ github_url = primary_url
+ else:
+ homepage_url = primary_url if primary_url else None
+
+ # ----------------------------------------------------------------
+ # Extract description: text after the first ` - `/ ` – `/ ` — ` separator
+ # ----------------------------------------------------------------
+ # Work on the cleaned body (badges removed) but preserve the original
+ # link text so the separator search is stable.
+ # We find the separator that appears AFTER the first link's closing `)`
+ first_link_end = clean_body.find(")", clean_body.find("]("))
+ search_from = first_link_end + 1 if first_link_end != -1 else 0
+ tail = clean_body[search_from:]
+
+ desc_match = _DESC_SEP_RE.search(tail)
+ if desc_match:
+ description: str | None = tail[desc_match.end():].strip()
+ if not description:
+ description = None
+ else:
+ description = None
+
+ # Detect language from the full original line (before cleaning)
+ language = _detect_language(entry_body)
+
+ record: dict = {
+ "name": name,
+ "sources": ["awesome-mcp"],
+ "tags": [current_tag],
+ }
+ if description:
+ record["description"] = description
+ if github_url:
+ record["github_url"] = github_url
+ if homepage_url:
+ record["homepage_url"] = homepage_url
+ if language:
+ record["language"] = language
+
+ records.append(record)
+
+ _logger.info("parsed %d entries, skipped %d", len(records), skipped)
+ return records
+
+
+# ---------------------------------------------------------------------------
+# Source class
+# ---------------------------------------------------------------------------
+
+
+class _AwesomeMcpSource:
+ name = "awesome-mcp"
+ homepage = "https://github.com/punkpeye/awesome-mcp-servers"
+
+ def fetch(self, *, limit: int | None = None, refresh: bool = False) -> Iterator[dict]:
+ """Yield raw records. Caches the README at raw/marketplace-dumps/awesome-mcp/.
+
+ Args:
+ limit: If set, yield at most this many records.
+ refresh: If ``True``, bypass the cache and re-fetch from network.
+
+ Yields:
+ Raw dicts suitable for ``McpRecord.from_dict()``.
+ """
+ cache_basename = f"README-{date.today().isoformat()}.md"
+ text: str | None = None
+ if not refresh:
+ text = read_cache(self.name, cache_basename)
+ if text is None:
+ text = fetch_text(URL)
+ write_cache(self.name, cache_basename, text)
+ records = _parse_readme(text)
+ if limit is not None:
+ records = records[:limit]
+ for r in records:
+ yield r
+
+
+SOURCE: Source = _AwesomeMcpSource()
diff --git a/src/mcp_sources/pulsemcp.py b/src/mcp_sources/pulsemcp.py
index 583382991af8b7c039d6301aadb84586572b510a..3ea5feea7ff1549ffa17af808ee3b06608addce1 100644
--- a/src/mcp_sources/pulsemcp.py
+++ b/src/mcp_sources/pulsemcp.py
@@ -1,350 +1,350 @@
-"""src/mcp_sources/pulsemcp.py -- Source for pulsemcp.com (HTML scraping mode).
-
-Iterates the public listing pages at https://www.pulsemcp.com/servers
-?page=N. Stdlib only (html.parser). No credentials required — the
-authenticated JSON API at /api/v0.1 is documented but gated behind
-manual approval; scraping the public pages is the only path users
-without a partnership API key can take.
-
-Each listing page returns 42 server cards. Total ~12,975 servers
-across ~310 pages as of v0.6.5. Detail-page enrichment (github_url,
-language, transports) is deferred to Phase 6 — Phase 2b.5 ships only
-the listing-card data: slug (from URL), name (from h3), creator,
-description, classification (official / community / reference).
-
-The HTML structure is content-addressed via ``data-test-id="mcp-server-card-"``
-attributes which gives us a stable card boundary without depending on
-class names that may shift with a frontend redesign.
-"""
-
-from __future__ import annotations
-
-import re
-from collections.abc import Iterator
-from datetime import date
-from html.parser import HTMLParser
-from urllib.parse import quote as _url_quote
-
-from mcp_sources.base import Source, fetch_text, read_cache, write_cache
-
-__all__ = ["SOURCE"]
-
-LISTING_BASE = "https://www.pulsemcp.com/servers"
-_TOTAL_PAGES_FALLBACK = 310 # As of 2026-04: 12,975 servers / 42 per page = 310
-
-# Card boundary marker — content-addressed so a frontend restyle of
-# class names doesn't silently break the parser.
-_CARD_TEST_ID_RE = re.compile(r'data-test-id="mcp-server-card-([a-z0-9][a-z0-9_-]+)"')
-
-# Detail-page anchors — used by fetch_details(). The GitHub-repo
-# anchor is a structural marker (``data-test-id``) which is why we
-# prefer it over class-based matching that'd break on a frontend
-# restyle. Pulsemcp emits this anchor only for MCPs whose creator
-# claimed a GitHub repo; SaaS-wrapper MCPs legitimately omit it.
-#
-# Attribute order inside the ```` is not stable (we've seen both
-# ``data-test-id`` then ``href`` and ``href`` then ``data-test-id``),
-# so we anchor on the test-id and extract href + inner separately
-# rather than encoding an attribute order into a single regex.
-_DETAIL_REPO_TAG_RE = re.compile(
- r']*?data-test-id="mcp-server-github-repo"[^>]*?>'
- r'(?P.*?)',
- re.DOTALL,
-)
-_DETAIL_REPO_HREF_RE = re.compile(
- r'href="(?Phttps://github\.com/[A-Za-z0-9_.\-/]+)"'
-)
-# Stars render as ``(N stars)`` or ``(N star)`` inside the GitHub
-# anchor, often wrapped across multiple lines with whitespace/newlines
-# between ``(``, the number, and the word. ``\s+`` matches newlines so
-# the pattern survives pulsemcp's pretty-printed markup.
-_STARS_RE = re.compile(r'\(\s*(\d+)\s+stars?\s*\)', re.DOTALL)
-
-
-class _CardTextExtractor(HTMLParser):
- """Stream-extract text content per tag inside one server card.
-
- Builds an ordered list of ``(tag, attrs, text)`` triples for every
- leaf text node, plus a separate flat string of all text for fallback
- matching. We keep both so the record-mapping step can prefer
- structural matches (h3 → name, gray-500 p → creator) while degrading
- gracefully when the markup shifts.
- """
-
- def __init__(self) -> None:
- super().__init__(convert_charrefs=True)
- self.items: list[tuple[str, dict[str, str], str]] = []
- self._stack: list[tuple[str, dict[str, str]]] = []
- self._buffer: list[str] = []
-
- def _flush(self) -> None:
- if not self._stack:
- return
- text = "".join(self._buffer).strip()
- if text:
- tag, attrs = self._stack[-1]
- self.items.append((tag, attrs, text))
- self._buffer = []
-
- def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
- self._flush()
- attrs_dict = {k: (v or "") for k, v in attrs}
- self._stack.append((tag, attrs_dict))
-
- def handle_endtag(self, tag: str) -> None:
- self._flush()
- if self._stack and self._stack[-1][0] == tag:
- self._stack.pop()
-
- def handle_data(self, data: str) -> None:
- self._buffer.append(data)
-
-
-def _split_cards(html: str) -> list[str]:
- """Return the substring slice for each card found in *html*.
-
- Uses ``data-test-id="mcp-server-card-"`` as the anchor and
- walks forward to the next card anchor (or end of input) to bound
- the slice. Avoids html.parser overhead for the page-level split.
- """
- anchors = list(_CARD_TEST_ID_RE.finditer(html))
- if not anchors:
- return []
- slices = []
- for i, m in enumerate(anchors):
- # Walk back to the opening inside the ,
- # so we step back to the nearest = 0 else m.start()
- slices.append(html[start:end])
- return slices
-
-
-def _slug_from_card(card_html: str) -> str | None:
- """Extract the slug from the card's data-test-id."""
- m = _CARD_TEST_ID_RE.search(card_html)
- return m.group(1) if m else None
-
-
-def _to_record(card_html: str) -> dict | None:
- """Map one server card's HTML slice to a McpRecord-compatible dict.
-
- Returns ``None`` when the card is too malformed to use (no slug
- or no name). Listing-page data is sparse: we get slug, name,
- creator, description, classification. github_url, language, and
- transports remain unset until Phase 6 fetches detail pages.
- """
- slug = _slug_from_card(card_html)
- if not slug:
- return None
-
- extractor = _CardTextExtractor()
- try:
- extractor.feed(card_html)
- except Exception: # noqa: BLE001 — html.parser may choke on malformed input
- return None
-
- name: str | None = None
- creator: str | None = None
- description: str | None = None
- classification: str | None = None
- saw_classification_label = False
-
- for tag, attrs, text in extractor.items:
- cls = attrs.get("class", "")
- if name is None and tag == "h3":
- name = text
- continue
- if creator is None and tag == "p" and "text-gray-500" in cls:
- creator = text
- continue
- if description is None and tag == "p" and "text-pulse-black" in cls and "leading-relaxed" in cls:
- description = text
- continue
- if tag == "p" and "Classification" in text:
- saw_classification_label = True
- continue
- if saw_classification_label and tag == "p" and classification is None:
- # Next text-bearing