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: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) -[![Python 3.11+](https://img.shields.io/badge/Python-3.11+-green.svg)](https://python.org) -[![PyPI](https://img.shields.io/pypi/v/claude-ctx.svg)](https://pypi.org/project/claude-ctx/) -[![Tests](https://img.shields.io/badge/Tests-3516_collected-brightgreen.svg)](#) -[![Graph](https://img.shields.io/badge/Graph-102%2C696_nodes_/_2.9M_edges-red.svg)](graph/) -[![Docs](https://img.shields.io/badge/docs-MkDocs_Material-blue.svg)](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: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) +[![Python 3.11+](https://img.shields.io/badge/Python-3.11+-green.svg)](https://python.org) +[![PyPI](https://img.shields.io/pypi/v/claude-ctx.svg)](https://pypi.org/project/claude-ctx/) +[![Tests](https://img.shields.io/badge/Tests-3617_collected-brightgreen.svg)](#) +[![Graph](https://img.shields.io/badge/Graph-102%2C696_nodes_/_2.9M_edges-red.svg)](graph/) +[![Docs](https://img.shields.io/badge/docs-MkDocs_Material-blue.svg)](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