Stevesolun commited on
Commit
3d1baef
·
verified ·
1 Parent(s): 7f74297

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .github/workflows/clean-host-contract.yml +35 -35
  2. .github/workflows/docs.yml +73 -73
  3. .github/workflows/huggingface-sync.yml +64 -0
  4. .github/workflows/publish.yml +481 -475
  5. .github/workflows/test.yml +710 -704
  6. .github/workflows/xdist-experiment.yml +90 -90
  7. docs/SKILL.md +303 -303
  8. docs/assets/javascripts/repo-stats-refresh.js +120 -120
  9. docs/backup-hook-install.md +224 -224
  10. docs/dashboard.md +347 -325
  11. docs/entity-onboarding.md +394 -394
  12. docs/harness/attaching-to-hosts.md +289 -289
  13. docs/harness/clean-host-contract.md +103 -103
  14. docs/huggingface-publish.md +79 -67
  15. docs/index.md +232 -232
  16. docs/knowledge-graph.md +359 -359
  17. docs/marketplace-registry.md +129 -129
  18. docs/memory-anchor.md +102 -102
  19. docs/skill-lifecycle-and-dashboard.md +171 -171
  20. docs/skill-quality-install.md +170 -170
  21. docs/skill-router/index.md +51 -51
  22. docs/skill-stack-matrix.md +166 -166
  23. docs/skills-health.md +107 -107
  24. docs/toolbox/behavior-miner.md +90 -90
  25. docs/toolbox/configuration.md +143 -143
  26. docs/toolbox/council-runner.md +81 -81
  27. docs/toolbox/index.md +70 -70
  28. docs/toolbox/intent-interview.md +94 -94
  29. docs/toolbox/starters.md +96 -96
  30. docs/toolbox/verdicts.md +142 -142
  31. graph/README.md +274 -274
  32. graph/communities.json +0 -0
  33. graph/entity-overlays.jsonl +0 -0
  34. graph/sample-top60.html +0 -0
  35. graph/viz-ai-agents.html +0 -0
  36. graph/viz-overview.html +0 -0
  37. graph/viz-python.html +0 -0
  38. graph/viz-security.html +0 -0
  39. imported-skills/julius-caveman/LICENSE +21 -21
  40. imported-skills/julius-caveman/MANIFEST.json +123 -123
  41. imported-skills/julius-caveman/agents/cavecrew-builder.md +47 -47
  42. imported-skills/julius-caveman/agents/cavecrew-investigator.md +57 -57
  43. imported-skills/julius-caveman/agents/cavecrew-reviewer.md +48 -48
  44. imported-skills/julius-caveman/skills/cavecrew/README.md +41 -41
  45. imported-skills/julius-caveman/skills/cavecrew/SKILL.md +82 -82
  46. imported-skills/julius-caveman/skills/caveman-commit/README.md +44 -44
  47. imported-skills/julius-caveman/skills/caveman-commit/SKILL.md +64 -64
  48. imported-skills/julius-caveman/skills/caveman-compress/README.md +163 -163
  49. imported-skills/julius-caveman/skills/caveman-compress/SECURITY.md +31 -31
  50. imported-skills/julius-caveman/skills/caveman-compress/SKILL.md +111 -111
.github/workflows/clean-host-contract.yml CHANGED
@@ -1,35 +1,35 @@
1
- name: Clean Host Contract
2
-
3
- on:
4
- workflow_dispatch:
5
- schedule:
6
- - cron: "17 3 * * 1"
7
-
8
- env:
9
- FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
10
-
11
- permissions:
12
- contents: read
13
-
14
- jobs:
15
- clean-host-contract:
16
- name: Clean wheel install and A-Z contract
17
- runs-on: ubuntu-latest
18
- timeout-minutes: 25
19
-
20
- steps:
21
- - name: Checkout
22
- uses: actions/checkout@v5
23
-
24
- - name: Set up Python 3.12
25
- uses: actions/setup-python@v6
26
- with:
27
- python-version: "3.12"
28
- cache: pip
29
- cache-dependency-path: pyproject.toml
30
-
31
- - name: Upgrade pip
32
- run: python -m pip install --upgrade pip
33
-
34
- - name: Run clean-host contract
35
- run: python scripts/clean_host_contract.py --fast
 
1
+ name: Clean Host Contract
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ schedule:
6
+ - cron: "17 3 * * 1"
7
+
8
+ env:
9
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
10
+
11
+ permissions:
12
+ contents: read
13
+
14
+ jobs:
15
+ clean-host-contract:
16
+ name: Clean wheel install and A-Z contract
17
+ runs-on: ubuntu-latest
18
+ timeout-minutes: 25
19
+
20
+ steps:
21
+ - name: Checkout
22
+ uses: actions/checkout@v5
23
+
24
+ - name: Set up Python 3.12
25
+ uses: actions/setup-python@v6
26
+ with:
27
+ python-version: "3.12"
28
+ cache: pip
29
+ cache-dependency-path: pyproject.toml
30
+
31
+ - name: Upgrade pip
32
+ run: python -m pip install --upgrade pip
33
+
34
+ - name: Run clean-host contract
35
+ run: python scripts/clean_host_contract.py --fast
.github/workflows/docs.yml CHANGED
@@ -1,73 +1,73 @@
1
- name: Deploy docs to GitHub Pages
2
-
3
- # Build the MkDocs Material site and publish to GitHub Pages on every push
4
- # to main. Also deployable on demand via the workflow_dispatch trigger.
5
-
6
- on:
7
- push:
8
- branches:
9
- - main
10
- paths:
11
- - "docs/**"
12
- - "mkdocs.yml"
13
- - "requirements-docs.txt"
14
- - ".github/workflows/docs.yml"
15
- workflow_dispatch:
16
-
17
- env:
18
- FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
19
-
20
- permissions:
21
- contents: read
22
-
23
- # Allow only one concurrent deploy; cancel in-progress runs on a new push.
24
- concurrency:
25
- group: "pages"
26
- cancel-in-progress: true
27
-
28
- jobs:
29
- build:
30
- name: Build site
31
- runs-on: ubuntu-latest
32
- steps:
33
- - name: Checkout
34
- uses: actions/checkout@v5
35
- with:
36
- fetch-depth: 0 # Required by mkdocs git-revision plugins if added.
37
-
38
- - name: Set up Python
39
- uses: actions/setup-python@v6
40
- with:
41
- python-version: "3.11"
42
- cache: "pip"
43
- cache-dependency-path: requirements-docs.txt
44
-
45
- - name: Install docs dependencies
46
- run: |
47
- python -m pip install --upgrade pip
48
- python -m pip install -r requirements-docs.txt
49
-
50
- - name: Build site (strict)
51
- run: |
52
- python -m mkdocs build --strict
53
-
54
- - name: Upload Pages artifact
55
- uses: actions/upload-pages-artifact@v5
56
- with:
57
- path: site
58
-
59
- deploy:
60
- name: Deploy to GitHub Pages
61
- needs: build
62
- runs-on: ubuntu-latest
63
- permissions:
64
- contents: read
65
- pages: write
66
- id-token: write
67
- environment:
68
- name: github-pages
69
- url: ${{ steps.deployment.outputs.page_url }}
70
- steps:
71
- - name: Deploy
72
- id: deployment
73
- uses: actions/deploy-pages@v5
 
1
+ name: Deploy docs to GitHub Pages
2
+
3
+ # Build the MkDocs Material site and publish to GitHub Pages on every push
4
+ # to main. Also deployable on demand via the workflow_dispatch trigger.
5
+
6
+ on:
7
+ push:
8
+ branches:
9
+ - main
10
+ paths:
11
+ - "docs/**"
12
+ - "mkdocs.yml"
13
+ - "requirements-docs.txt"
14
+ - ".github/workflows/docs.yml"
15
+ workflow_dispatch:
16
+
17
+ env:
18
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
19
+
20
+ permissions:
21
+ contents: read
22
+
23
+ # Allow only one concurrent deploy; cancel in-progress runs on a new push.
24
+ concurrency:
25
+ group: "pages"
26
+ cancel-in-progress: true
27
+
28
+ jobs:
29
+ build:
30
+ name: Build site
31
+ runs-on: ubuntu-latest
32
+ steps:
33
+ - name: Checkout
34
+ uses: actions/checkout@v5
35
+ with:
36
+ fetch-depth: 0 # Required by mkdocs git-revision plugins if added.
37
+
38
+ - name: Set up Python
39
+ uses: actions/setup-python@v6
40
+ with:
41
+ python-version: "3.11"
42
+ cache: "pip"
43
+ cache-dependency-path: requirements-docs.txt
44
+
45
+ - name: Install docs dependencies
46
+ run: |
47
+ python -m pip install --upgrade pip
48
+ python -m pip install -r requirements-docs.txt
49
+
50
+ - name: Build site (strict)
51
+ run: |
52
+ python -m mkdocs build --strict
53
+
54
+ - name: Upload Pages artifact
55
+ uses: actions/upload-pages-artifact@v5
56
+ with:
57
+ path: site
58
+
59
+ deploy:
60
+ name: Deploy to GitHub Pages
61
+ needs: build
62
+ runs-on: ubuntu-latest
63
+ permissions:
64
+ contents: read
65
+ pages: write
66
+ id-token: write
67
+ environment:
68
+ name: github-pages
69
+ url: ${{ steps.deployment.outputs.page_url }}
70
+ steps:
71
+ - name: Deploy
72
+ id: deployment
73
+ uses: actions/deploy-pages@v5
.github/workflows/huggingface-sync.yml ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Sync Hugging Face
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ workflow_dispatch:
8
+
9
+ env:
10
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
11
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
12
+
13
+ permissions:
14
+ contents: read
15
+
16
+ concurrency:
17
+ group: "huggingface-sync-main"
18
+ cancel-in-progress: true
19
+
20
+ jobs:
21
+ sync:
22
+ name: Sync dataset
23
+ runs-on: ubuntu-latest
24
+ steps:
25
+ - name: Checkout
26
+ uses: actions/checkout@v5
27
+ with:
28
+ lfs: false
29
+
30
+ - name: Skip when HF_TOKEN is not configured
31
+ if: ${{ env.HF_TOKEN == '' }}
32
+ run: |
33
+ echo "::notice title=Hugging Face sync skipped::Set the HF_TOKEN repository secret to publish Stevesolun/ctx automatically."
34
+
35
+ - name: Hydrate required graph artifacts from release assets
36
+ if: ${{ env.HF_TOKEN != '' }}
37
+ env:
38
+ GH_TOKEN: ${{ github.token }}
39
+ run: |
40
+ latest_tag="$(gh release view --repo "$GITHUB_REPOSITORY" --json tagName --jq .tagName)"
41
+ echo "Hydrating graph artifacts from release ${latest_tag}"
42
+ rm -f graph/wiki-graph.tar.gz graph/wiki-graph-runtime.tar.gz graph/skills-sh-catalog.json.gz
43
+ gh release download "$latest_tag" --repo "$GITHUB_REPOSITORY" --dir graph --pattern wiki-graph.tar.gz
44
+ gh release download "$latest_tag" --repo "$GITHUB_REPOSITORY" --dir graph --pattern wiki-graph-runtime.tar.gz
45
+ gh release download "$latest_tag" --repo "$GITHUB_REPOSITORY" --dir graph --pattern skills-sh-catalog.json.gz
46
+
47
+ - name: Set up Python
48
+ if: ${{ env.HF_TOKEN != '' }}
49
+ uses: actions/setup-python@v6
50
+ with:
51
+ python-version: "3.11"
52
+ cache: "pip"
53
+ cache-dependency-path: pyproject.toml
54
+
55
+ - name: Install sync dependencies
56
+ if: ${{ env.HF_TOKEN != '' }}
57
+ run: |
58
+ python -m pip install --upgrade pip
59
+ python -m pip install -e ".[dev]" huggingface_hub
60
+
61
+ - name: Sync Hugging Face dataset
62
+ if: ${{ env.HF_TOKEN != '' }}
63
+ run: |
64
+ python scripts/sync_huggingface.py --repo . --repo-id Stevesolun/ctx --repo-type dataset
.github/workflows/publish.yml CHANGED
@@ -1,475 +1,481 @@
1
- name: Publish to PyPI
2
-
3
- # Publish claude-ctx to PyPI on every tag that looks like a version
4
- # (v0.5.0, v0.5.0-rc1, v1.0.0, …). Uses PyPI Trusted Publishing —
5
- # no API token needed once the pending publisher is configured at
6
- # https://pypi.org/manage/account/publishing/.
7
- #
8
- # Also deployable on demand to TestPyPI via workflow_dispatch. Production
9
- # PyPI publishes must use a version tag push so graph release assets are
10
- # uploaded before the wheel is published.
11
-
12
- on:
13
- push:
14
- tags:
15
- - "v*"
16
- workflow_dispatch:
17
- inputs:
18
- repository:
19
- description: "PyPI repository (pypi or testpypi)"
20
- required: true
21
- default: "pypi"
22
- type: choice
23
- options:
24
- - pypi
25
- - testpypi
26
-
27
- env:
28
- FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
29
-
30
- permissions:
31
- contents: read
32
-
33
- jobs:
34
- build:
35
- name: Build sdist + wheel
36
- runs-on: ubuntu-latest
37
- permissions:
38
- contents: read
39
- outputs:
40
- graph_assets_available: ${{ steps.resolve_graph_lfs.outcome == 'success' }}
41
- steps:
42
- - name: Checkout
43
- uses: actions/checkout@v5
44
- with:
45
- lfs: false
46
-
47
- - name: Set up Python
48
- uses: actions/setup-python@v6
49
- with:
50
- python-version: "3.12"
51
-
52
- - name: Install release tooling
53
- run: |
54
- python -m pip install --upgrade pip
55
- python -m pip install ".[dev]" build packaging twine
56
-
57
- - name: Validate release target
58
- run: |
59
- python - <<'PY'
60
- import os
61
- import tomllib
62
- from packaging.version import Version
63
-
64
- event = os.environ["GITHUB_EVENT_NAME"]
65
- target_repository = os.environ.get("INPUT_REPOSITORY", "pypi")
66
- ref_type = os.environ.get("GITHUB_REF_TYPE", "")
67
- ref_name = os.environ["GITHUB_REF_NAME"]
68
-
69
- if event == "workflow_dispatch" and target_repository == "pypi":
70
- raise SystemExit(
71
- "Manual PyPI publish is disabled; push a version tag so "
72
- "graph release assets are uploaded before publishing"
73
- )
74
- if event == "workflow_dispatch" and target_repository == "testpypi":
75
- print(f"manual TestPyPI publish allowed from {ref_type}:{ref_name}")
76
- raise SystemExit(0)
77
-
78
- if ref_type != "tag":
79
- raise SystemExit(
80
- "PyPI release must run from a version tag; "
81
- f"got {ref_type}:{ref_name}"
82
- )
83
- tag = ref_name
84
- if not tag.startswith("v"):
85
- raise SystemExit(f"release tag must start with v: {tag}")
86
-
87
- with open("pyproject.toml", "rb") as fh:
88
- package_version = tomllib.load(fh)["project"]["version"]
89
-
90
- tag_version = str(Version(tag[1:]))
91
- normalized_package_version = str(Version(package_version))
92
- if tag_version != normalized_package_version:
93
- raise SystemExit(
94
- f"tag {tag!r} does not match pyproject version {package_version!r}"
95
- )
96
- print(f"release version {package_version} matches tag {tag}")
97
- PY
98
- env:
99
- INPUT_REPOSITORY: ${{ github.event.inputs.repository || 'pypi' }}
100
-
101
- - name: Reject already published PyPI version
102
- run: |
103
- python - <<'PY'
104
- import os
105
- import tomllib
106
- import urllib.error
107
- import urllib.request
108
-
109
- target_repository = os.environ.get("INPUT_REPOSITORY", "pypi")
110
- if target_repository != "pypi":
111
- print(f"skipping PyPI reuse check for {target_repository}")
112
- raise SystemExit(0)
113
-
114
- with open("pyproject.toml", "rb") as fh:
115
- project = tomllib.load(fh)["project"]
116
-
117
- name = project["name"]
118
- package_version = project["version"]
119
- url = f"https://pypi.org/pypi/{name}/{package_version}/json"
120
- try:
121
- with urllib.request.urlopen(url, timeout=15):
122
- raise SystemExit(
123
- f"{name} {package_version} already exists on PyPI; "
124
- "bump the version before publishing"
125
- )
126
- except urllib.error.HTTPError as exc:
127
- if exc.code == 404:
128
- print(f"{name} {package_version} is not present on PyPI")
129
- raise SystemExit(0)
130
- raise
131
- PY
132
- env:
133
- INPUT_REPOSITORY: ${{ github.event.inputs.repository || 'pypi' }}
134
-
135
- - name: Resolve release graph LFS artifacts
136
- id: resolve_graph_lfs
137
- env:
138
- GH_TOKEN: ${{ github.token }}
139
- TAG_NAME: ${{ github.ref_name }}
140
- run: |
141
- set -euo pipefail
142
- git lfs install --local
143
- if git lfs pull --include="graph/wiki-graph.tar.gz,graph/wiki-graph-runtime.tar.gz" --exclude=""; then
144
- exit 0
145
- fi
146
- echo "Git LFS download failed; trying matching prior release asset."
147
- python - <<'PY'
148
- import hashlib
149
- import json
150
- import os
151
- from pathlib import Path
152
- import subprocess
153
- import time
154
- import urllib.request
155
-
156
- repo = os.environ["GITHUB_REPOSITORY"]
157
- current_tag = os.environ.get("TAG_NAME", "")
158
- release_asset_wait_seconds = 300
159
- release_asset_poll_seconds = 10
160
-
161
- def load_releases() -> list[dict]:
162
- return json.loads(subprocess.check_output(
163
- ["gh", "api", f"repos/{repo}/releases?per_page=50"],
164
- text=True,
165
- ))
166
-
167
- def hydrate_from_release(path_name: str, hydrated_min_size: int) -> None:
168
- graph_tar = Path(path_name)
169
- pointer = graph_tar.read_text(encoding="utf-8", errors="replace")
170
- expected_oid = ""
171
- expected_size = 0
172
- for line in pointer.splitlines():
173
- if line.startswith("oid sha256:"):
174
- expected_oid = line.split(":", 1)[1].strip()
175
- elif line.startswith("size "):
176
- expected_size = int(line.split(" ", 1)[1].strip())
177
- if not expected_oid:
178
- if graph_tar.stat().st_size > hydrated_min_size:
179
- print(f"{graph_tar} is already hydrated")
180
- return
181
- raise SystemExit(f"{path_name} is neither hydrated nor an LFS pointer")
182
-
183
- deadline = time.monotonic() + release_asset_wait_seconds
184
- while True:
185
- candidates = []
186
- for release in load_releases():
187
- tag_name = str(release.get("tag_name") or "")
188
- is_graph_cache = tag_name.startswith("graph-artifacts-")
189
- if release.get("draft") or (
190
- release.get("prerelease") and not is_graph_cache
191
- ):
192
- continue
193
- if tag_name == current_tag:
194
- continue
195
- for asset in release.get("assets", []):
196
- if asset.get("name") != graph_tar.name:
197
- continue
198
- digest = str(asset.get("digest") or "")
199
- size = int(asset.get("size") or 0)
200
- if size != expected_size:
201
- continue
202
- if digest and digest != f"sha256:{expected_oid}":
203
- continue
204
- candidates.append((tag_name, asset))
205
-
206
- if candidates:
207
- break
208
- if time.monotonic() >= deadline:
209
- raise SystemExit(
210
- f"No previous release asset matches {path_name} "
211
- f"sha256:{expected_oid} size:{expected_size}"
212
- )
213
- print(
214
- f"Waiting for matching release asset {graph_tar.name} "
215
- f"sha256:{expected_oid} size:{expected_size}"
216
- )
217
- time.sleep(release_asset_poll_seconds)
218
-
219
- source_tag, asset = candidates[0]
220
- tmp = graph_tar.with_name(f"{graph_tar.name}.download")
221
- sha = hashlib.sha256()
222
- total = 0
223
- with urllib.request.urlopen(asset["browser_download_url"], timeout=300) as resp: # noqa: S310
224
- with tmp.open("wb") as fh:
225
- while True:
226
- chunk = resp.read(1024 * 1024)
227
- if not chunk:
228
- break
229
- sha.update(chunk)
230
- total += len(chunk)
231
- fh.write(chunk)
232
- actual_oid = sha.hexdigest()
233
- if actual_oid != expected_oid or total != expected_size:
234
- tmp.unlink(missing_ok=True)
235
- raise SystemExit(
236
- f"Downloaded {path_name} does not match LFS pointer: "
237
- f"sha256:{actual_oid} size:{total}"
238
- )
239
- tmp.replace(graph_tar)
240
- print(
241
- f"Hydrated {path_name} from {source_tag} release asset "
242
- f"sha256:{actual_oid} size:{total}"
243
- )
244
-
245
- hydrate_from_release("graph/wiki-graph.tar.gz", 100_000_000)
246
- hydrate_from_release("graph/wiki-graph-runtime.tar.gz", 10_000_000)
247
- PY
248
-
249
- - name: Validate release graph artifacts
250
- if: steps.resolve_graph_lfs.outcome == 'success'
251
- run: |
252
- python src/validate_graph_artifacts.py \
253
- --graph-dir graph \
254
- --deep \
255
- --min-nodes 100000 \
256
- --min-edges 2000000 \
257
- --min-skills-sh-nodes 89000 \
258
- --min-semantic-edges 1000000 \
259
- --expected-nodes 102928 \
260
- --expected-edges 2913960 \
261
- --expected-semantic-edges 1683193 \
262
- --expected-harness-nodes 207 \
263
- --expected-skills-sh-nodes 89471 \
264
- --expected-skills-sh-catalog-entries 89465 \
265
- --expected-skills-sh-converted 89465 \
266
- --expected-skill-pages 91464 \
267
- --expected-agent-pages 467 \
268
- --expected-mcp-pages 10790 \
269
- --expected-harness-pages 207 \
270
- --line-threshold 180 \
271
- --max-stage-lines 40
272
-
273
- - name: Validate README and docs stats
274
- if: steps.resolve_graph_lfs.outcome == 'success'
275
- run: python src/update_repo_stats.py --check
276
-
277
- - name: Static gates
278
- run: |
279
- python -m ruff check src hooks scripts
280
- python -m mypy src
281
-
282
- - name: Clean-host contract
283
- run: python scripts/clean_host_contract.py --fast
284
-
285
- - name: Release canary tests
286
- run: |
287
- python -m pytest -q --no-cov \
288
- src/tests/test_ci_classifier.py \
289
- src/tests/test_package_scaffold.py \
290
- src/tests/test_clean_host_contract.py \
291
- src/tests/test_alive_loop_e2e.py
292
-
293
- - name: Build distributions
294
- run: python -m build
295
-
296
- - name: Check distributions
297
- run: python -m twine check dist/*
298
-
299
- - name: Check distribution contents
300
- run: |
301
- python - <<'PY'
302
- import tarfile
303
- import zipfile
304
- from pathlib import Path
305
-
306
- wheel = next(Path("dist").glob("*.whl"))
307
- sdist = next(Path("dist").glob("*.tar.gz"))
308
-
309
- with zipfile.ZipFile(wheel) as zf:
310
- wheel_names = set(zf.namelist())
311
- required = {"ctx/config.json", "ctx/skill-registry.json"}
312
- missing = sorted(required - wheel_names)
313
- if missing:
314
- raise SystemExit(f"wheel missing packaged defaults: {missing}")
315
-
316
- with tarfile.open(sdist, "r:gz") as tf:
317
- names = set(tf.getnames())
318
- forbidden = ("/src/tests/", "/.claude/", "/.a5c/")
319
- leaked = sorted(name for name in names if any(part in name for part in forbidden))
320
- if leaked:
321
- raise SystemExit("sdist contains local/test artifacts:\n" + "\n".join(leaked[:20]))
322
- print(f"checked distribution contents: {wheel.name}, {sdist.name}")
323
- PY
324
-
325
- - name: Smoke install wheel
326
- run: |
327
- python -m venv .venv-smoke
328
- . .venv-smoke/bin/activate
329
- python -m pip install --upgrade pip
330
- wheel="$(python - <<'PY'
331
- from pathlib import Path
332
- print(next(Path("dist").glob("*.whl")))
333
- PY
334
- )"
335
- python -m pip install "$wheel"
336
- python -m pip check
337
- python - <<'PY'
338
- import tomllib
339
- from importlib.metadata import entry_points, version
340
-
341
- import ctx
342
- import ctx_config
343
-
344
- with open("pyproject.toml", "rb") as fh:
345
- expected_scripts = set(tomllib.load(fh)["project"]["scripts"])
346
-
347
- dist_version = version("claude-ctx")
348
- if ctx.__version__ != dist_version:
349
- raise SystemExit(
350
- f"ctx.__version__={ctx.__version__!r} != metadata {dist_version!r}"
351
- )
352
- if ctx_config.cfg.recommendation_top_k != 5:
353
- raise SystemExit("packaged default config was not loaded")
354
- scripts = {
355
- ep.name: ep for ep in entry_points(group="console_scripts")
356
- if ep.name == "ctx" or ep.name.startswith("ctx-")
357
- }
358
- missing = sorted(expected_scripts - set(scripts))
359
- extra = sorted(set(scripts) - expected_scripts)
360
- if missing or extra:
361
- raise SystemExit(
362
- "wheel console-script surface mismatch\n"
363
- f"missing: {missing}\n"
364
- f"extra: {extra}"
365
- )
366
- failures = []
367
- for ep in scripts.values():
368
- try:
369
- ep.load()
370
- except Exception as exc:
371
- failures.append(f"{ep.name}: {exc!r}")
372
- if failures:
373
- raise SystemExit("console script load failures:\n" + "\n".join(failures))
374
- unsafe_help = {"ctx-mcp-server"}
375
- safe_help = sorted(expected_scripts - unsafe_help)
376
- with open("ctx-console-help.txt", "w", encoding="utf-8", newline="\n") as fh:
377
- fh.write("\n".join(safe_help) + "\n")
378
- print(
379
- f"loaded {len(scripts)} ctx console scripts from wheel "
380
- f"{dist_version}; help-smoke={len(safe_help)}"
381
- )
382
- PY
383
- while IFS= read -r cmd; do
384
- cmd="${cmd%$'\r'}"
385
- [[ -z "$cmd" ]] && continue
386
- echo "help smoke: $cmd"
387
- "$cmd" --help >/dev/null
388
- done < ctx-console-help.txt
389
- python -m pip install "${wheel}[harness]"
390
- python - <<'PY'
391
- import litellm
392
-
393
- print(f"harness extra import ok: litellm {getattr(litellm, '__version__', 'unknown')}")
394
- PY
395
-
396
- - name: Upload dist artifact
397
- uses: actions/upload-artifact@v7
398
- with:
399
- name: dist
400
- path: dist/
401
-
402
- - name: Upload graph artifact bundle
403
- if: steps.resolve_graph_lfs.outcome == 'success'
404
- uses: actions/upload-artifact@v7
405
- with:
406
- name: graph-release-assets
407
- path: |
408
- graph/wiki-graph.tar.gz
409
- graph/wiki-graph-runtime.tar.gz
410
- graph/skills-sh-catalog.json.gz
411
- graph/communities.json
412
- graph/entity-overlays.jsonl
413
-
414
- release-assets:
415
- name: Upload graph release assets
416
- needs: build
417
- if: github.event_name == 'push' && needs.build.outputs.graph_assets_available == 'true'
418
- runs-on: ubuntu-latest
419
- permissions:
420
- contents: write
421
- steps:
422
- - name: Download graph artifact bundle
423
- uses: actions/download-artifact@v7
424
- with:
425
- name: graph-release-assets
426
- path: graph-release-assets
427
-
428
- - name: Upload graph assets to GitHub release
429
- env:
430
- GH_TOKEN: ${{ github.token }}
431
- TAG_NAME: ${{ github.ref_name }}
432
- run: |
433
- gh release view "$TAG_NAME" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1 \
434
- || gh release create "$TAG_NAME" \
435
- --repo "$GITHUB_REPOSITORY" \
436
- --title "$TAG_NAME" \
437
- --notes "ctx $TAG_NAME"
438
- gh release upload "$TAG_NAME" \
439
- --repo "$GITHUB_REPOSITORY" \
440
- graph-release-assets/wiki-graph.tar.gz \
441
- graph-release-assets/wiki-graph-runtime.tar.gz \
442
- graph-release-assets/skills-sh-catalog.json.gz \
443
- graph-release-assets/communities.json \
444
- graph-release-assets/entity-overlays.jsonl \
445
- --clobber
446
-
447
- publish:
448
- name: Publish to PyPI
449
- needs:
450
- - build
451
- - release-assets
452
- if: ${{ always() && needs.build.result == 'success' && (needs.release-assets.result == 'success' || (github.event_name == 'workflow_dispatch' && github.event.inputs.repository == 'testpypi')) }}
453
- runs-on: ubuntu-latest
454
- permissions:
455
- contents: read
456
- id-token: write # required for Trusted Publishing
457
- environment:
458
- name: pypi
459
- url: https://pypi.org/project/claude-ctx/
460
- steps:
461
- - name: Download dist artifact
462
- uses: actions/download-artifact@v7
463
- with:
464
- name: dist
465
- path: dist/
466
-
467
- - name: Publish to PyPI
468
- if: github.event_name == 'push'
469
- uses: pypa/gh-action-pypi-publish@release/v1
470
-
471
- - name: Publish to TestPyPI
472
- if: github.event_name == 'workflow_dispatch' && github.event.inputs.repository == 'testpypi'
473
- uses: pypa/gh-action-pypi-publish@release/v1
474
- with:
475
- repository-url: https://test.pypi.org/legacy/
 
 
 
 
 
 
 
1
+ name: Publish to PyPI
2
+
3
+ # Publish claude-ctx to PyPI on every tag that looks like a version
4
+ # (v0.5.0, v0.5.0-rc1, v1.0.0, …). Uses PyPI Trusted Publishing —
5
+ # no API token needed once the pending publisher is configured at
6
+ # https://pypi.org/manage/account/publishing/.
7
+ #
8
+ # Also deployable on demand to TestPyPI via workflow_dispatch. Production
9
+ # PyPI publishes must use a version tag push so graph release assets are
10
+ # uploaded before the wheel is published.
11
+
12
+ on:
13
+ push:
14
+ tags:
15
+ - "v*"
16
+ workflow_dispatch:
17
+ inputs:
18
+ repository:
19
+ description: "PyPI repository (pypi or testpypi)"
20
+ required: true
21
+ default: "pypi"
22
+ type: choice
23
+ options:
24
+ - pypi
25
+ - testpypi
26
+
27
+ env:
28
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
29
+
30
+ permissions:
31
+ contents: read
32
+
33
+ jobs:
34
+ build:
35
+ name: Build sdist + wheel
36
+ runs-on: ubuntu-latest
37
+ permissions:
38
+ contents: read
39
+ outputs:
40
+ graph_assets_available: ${{ steps.resolve_graph_assets.outcome == 'success' }}
41
+ steps:
42
+ - name: Checkout
43
+ uses: actions/checkout@v5
44
+ with:
45
+ lfs: false
46
+
47
+ - name: Set up Python
48
+ uses: actions/setup-python@v6
49
+ with:
50
+ python-version: "3.12"
51
+
52
+ - name: Install release tooling
53
+ run: |
54
+ python -m pip install --upgrade pip
55
+ python -m pip install ".[dev]" build packaging twine
56
+
57
+ - name: Validate release target
58
+ run: |
59
+ python - <<'PY'
60
+ import os
61
+ import tomllib
62
+ from packaging.version import Version
63
+
64
+ event = os.environ["GITHUB_EVENT_NAME"]
65
+ target_repository = os.environ.get("INPUT_REPOSITORY", "pypi")
66
+ ref_type = os.environ.get("GITHUB_REF_TYPE", "")
67
+ ref_name = os.environ["GITHUB_REF_NAME"]
68
+
69
+ if event == "workflow_dispatch" and target_repository == "pypi":
70
+ raise SystemExit(
71
+ "Manual PyPI publish is disabled; push a version tag so "
72
+ "graph release assets are uploaded before publishing"
73
+ )
74
+ if event == "workflow_dispatch" and target_repository == "testpypi":
75
+ print(f"manual TestPyPI publish allowed from {ref_type}:{ref_name}")
76
+ raise SystemExit(0)
77
+
78
+ if ref_type != "tag":
79
+ raise SystemExit(
80
+ "PyPI release must run from a version tag; "
81
+ f"got {ref_type}:{ref_name}"
82
+ )
83
+ tag = ref_name
84
+ if not tag.startswith("v"):
85
+ raise SystemExit(f"release tag must start with v: {tag}")
86
+
87
+ with open("pyproject.toml", "rb") as fh:
88
+ package_version = tomllib.load(fh)["project"]["version"]
89
+
90
+ tag_version = str(Version(tag[1:]))
91
+ normalized_package_version = str(Version(package_version))
92
+ if tag_version != normalized_package_version:
93
+ raise SystemExit(
94
+ f"tag {tag!r} does not match pyproject version {package_version!r}"
95
+ )
96
+ print(f"release version {package_version} matches tag {tag}")
97
+ PY
98
+ env:
99
+ INPUT_REPOSITORY: ${{ github.event.inputs.repository || 'pypi' }}
100
+
101
+ - name: Reject already published PyPI version
102
+ run: |
103
+ python - <<'PY'
104
+ import os
105
+ import tomllib
106
+ import urllib.error
107
+ import urllib.request
108
+
109
+ target_repository = os.environ.get("INPUT_REPOSITORY", "pypi")
110
+ if target_repository != "pypi":
111
+ print(f"skipping PyPI reuse check for {target_repository}")
112
+ raise SystemExit(0)
113
+
114
+ with open("pyproject.toml", "rb") as fh:
115
+ project = tomllib.load(fh)["project"]
116
+
117
+ name = project["name"]
118
+ package_version = project["version"]
119
+ url = f"https://pypi.org/pypi/{name}/{package_version}/json"
120
+ try:
121
+ with urllib.request.urlopen(url, timeout=15):
122
+ raise SystemExit(
123
+ f"{name} {package_version} already exists on PyPI; "
124
+ "bump the version before publishing"
125
+ )
126
+ except urllib.error.HTTPError as exc:
127
+ if exc.code == 404:
128
+ print(f"{name} {package_version} is not present on PyPI")
129
+ raise SystemExit(0)
130
+ raise
131
+ PY
132
+ env:
133
+ INPUT_REPOSITORY: ${{ github.event.inputs.repository || 'pypi' }}
134
+
135
+ - name: Resolve release graph artifacts from release assets
136
+ id: resolve_graph_assets
137
+ env:
138
+ GH_TOKEN: ${{ github.token }}
139
+ TAG_NAME: ${{ github.ref_name }}
140
+ run: |
141
+ set -euo pipefail
142
+ echo "Resolving graph artifacts from matching release assets to avoid Git LFS bandwidth."
143
+ python - <<'PY'
144
+ import hashlib
145
+ import json
146
+ import os
147
+ from pathlib import Path
148
+ import subprocess
149
+ import time
150
+ import urllib.request
151
+
152
+ repo = os.environ["GITHUB_REPOSITORY"]
153
+ current_tag = os.environ.get("TAG_NAME", "")
154
+ release_asset_wait_seconds = 300
155
+ release_asset_poll_seconds = 10
156
+ expected_graph_assets = {
157
+ "graph/wiki-graph.tar.gz": {
158
+ "sha256": "91b30795e7d200cf31a62a8749969d12658f5f74636d2de06d6b2b24b393c12f",
159
+ "size": 457545675,
160
+ },
161
+ "graph/wiki-graph-runtime.tar.gz": {
162
+ "sha256": "334fb19bace3fd6e4b92087850f17297fb248032957d123f3f1432dfde2e36c0",
163
+ "size": 175773376,
164
+ },
165
+ }
166
+
167
+ def load_releases() -> list[dict]:
168
+ return json.loads(subprocess.check_output(
169
+ ["gh", "api", f"repos/{repo}/releases?per_page=50"],
170
+ text=True,
171
+ ))
172
+
173
+ def hydrate_from_release(path_name: str, hydrated_min_size: int) -> None:
174
+ graph_tar = Path(path_name)
175
+ fallback = expected_graph_assets[path_name]
176
+ expected_oid = fallback["sha256"]
177
+ expected_size = int(fallback["size"])
178
+ if graph_tar.exists():
179
+ pointer = graph_tar.read_text(encoding="utf-8", errors="replace")
180
+ for line in pointer.splitlines():
181
+ if line.startswith("oid sha256:"):
182
+ expected_oid = line.split(":", 1)[1].strip()
183
+ elif line.startswith("size "):
184
+ expected_size = int(line.split(" ", 1)[1].strip())
185
+ if not pointer.startswith("version https://git-lfs.github.com/spec/v1") and graph_tar.stat().st_size > hydrated_min_size:
186
+ print(f"{graph_tar} is already hydrated")
187
+ return
188
+
189
+ deadline = time.monotonic() + release_asset_wait_seconds
190
+ while True:
191
+ candidates = []
192
+ for release in load_releases():
193
+ tag_name = str(release.get("tag_name") or "")
194
+ is_graph_cache = tag_name.startswith("graph-artifacts-")
195
+ if release.get("draft") or (
196
+ release.get("prerelease") and not is_graph_cache
197
+ ):
198
+ continue
199
+ if tag_name == current_tag:
200
+ continue
201
+ for asset in release.get("assets", []):
202
+ if asset.get("name") != graph_tar.name:
203
+ continue
204
+ digest = str(asset.get("digest") or "")
205
+ size = int(asset.get("size") or 0)
206
+ if size != expected_size:
207
+ continue
208
+ if digest and digest != f"sha256:{expected_oid}":
209
+ continue
210
+ candidates.append((tag_name, asset))
211
+
212
+ if candidates:
213
+ break
214
+ if time.monotonic() >= deadline:
215
+ raise SystemExit(
216
+ f"No previous release asset matches {path_name} "
217
+ f"sha256:{expected_oid} size:{expected_size}"
218
+ )
219
+ print(
220
+ f"Waiting for matching release asset {graph_tar.name} "
221
+ f"sha256:{expected_oid} size:{expected_size}"
222
+ )
223
+ time.sleep(release_asset_poll_seconds)
224
+
225
+ source_tag, asset = candidates[0]
226
+ tmp = graph_tar.with_name(f"{graph_tar.name}.download")
227
+ sha = hashlib.sha256()
228
+ total = 0
229
+ with urllib.request.urlopen(asset["browser_download_url"], timeout=300) as resp: # noqa: S310
230
+ with tmp.open("wb") as fh:
231
+ while True:
232
+ chunk = resp.read(1024 * 1024)
233
+ if not chunk:
234
+ break
235
+ sha.update(chunk)
236
+ total += len(chunk)
237
+ fh.write(chunk)
238
+ actual_oid = sha.hexdigest()
239
+ if actual_oid != expected_oid or total != expected_size:
240
+ tmp.unlink(missing_ok=True)
241
+ raise SystemExit(
242
+ f"Downloaded {path_name} does not match LFS pointer: "
243
+ f"sha256:{actual_oid} size:{total}"
244
+ )
245
+ tmp.replace(graph_tar)
246
+ print(
247
+ f"Hydrated {path_name} from {source_tag} release asset "
248
+ f"sha256:{actual_oid} size:{total}"
249
+ )
250
+
251
+ hydrate_from_release("graph/wiki-graph.tar.gz", 100_000_000)
252
+ hydrate_from_release("graph/wiki-graph-runtime.tar.gz", 10_000_000)
253
+ PY
254
+
255
+ - name: Validate release graph artifacts
256
+ if: steps.resolve_graph_assets.outcome == 'success'
257
+ run: |
258
+ python src/validate_graph_artifacts.py \
259
+ --graph-dir graph \
260
+ --deep \
261
+ --min-nodes 100000 \
262
+ --min-edges 2000000 \
263
+ --min-skills-sh-nodes 89000 \
264
+ --min-semantic-edges 1000000 \
265
+ --expected-nodes 102928 \
266
+ --expected-edges 2913960 \
267
+ --expected-semantic-edges 1683193 \
268
+ --expected-harness-nodes 207 \
269
+ --expected-skills-sh-nodes 89471 \
270
+ --expected-skills-sh-catalog-entries 89465 \
271
+ --expected-skills-sh-converted 89465 \
272
+ --expected-skill-pages 91464 \
273
+ --expected-agent-pages 467 \
274
+ --expected-mcp-pages 10790 \
275
+ --expected-harness-pages 207 \
276
+ --line-threshold 180 \
277
+ --max-stage-lines 40
278
+
279
+ - name: Validate README and docs stats
280
+ if: steps.resolve_graph_assets.outcome == 'success'
281
+ run: python src/update_repo_stats.py --check
282
+
283
+ - name: Static gates
284
+ run: |
285
+ python -m ruff check src hooks scripts
286
+ python -m mypy src
287
+
288
+ - name: Clean-host contract
289
+ run: python scripts/clean_host_contract.py --fast
290
+
291
+ - name: Release canary tests
292
+ run: |
293
+ python -m pytest -q --no-cov \
294
+ src/tests/test_ci_classifier.py \
295
+ src/tests/test_package_scaffold.py \
296
+ src/tests/test_clean_host_contract.py \
297
+ src/tests/test_alive_loop_e2e.py
298
+
299
+ - name: Build distributions
300
+ run: python -m build
301
+
302
+ - name: Check distributions
303
+ run: python -m twine check dist/*
304
+
305
+ - name: Check distribution contents
306
+ run: |
307
+ python - <<'PY'
308
+ import tarfile
309
+ import zipfile
310
+ from pathlib import Path
311
+
312
+ wheel = next(Path("dist").glob("*.whl"))
313
+ sdist = next(Path("dist").glob("*.tar.gz"))
314
+
315
+ with zipfile.ZipFile(wheel) as zf:
316
+ wheel_names = set(zf.namelist())
317
+ required = {"ctx/config.json", "ctx/skill-registry.json"}
318
+ missing = sorted(required - wheel_names)
319
+ if missing:
320
+ raise SystemExit(f"wheel missing packaged defaults: {missing}")
321
+
322
+ with tarfile.open(sdist, "r:gz") as tf:
323
+ names = set(tf.getnames())
324
+ forbidden = ("/src/tests/", "/.claude/", "/.a5c/")
325
+ leaked = sorted(name for name in names if any(part in name for part in forbidden))
326
+ if leaked:
327
+ raise SystemExit("sdist contains local/test artifacts:\n" + "\n".join(leaked[:20]))
328
+ print(f"checked distribution contents: {wheel.name}, {sdist.name}")
329
+ PY
330
+
331
+ - name: Smoke install wheel
332
+ run: |
333
+ python -m venv .venv-smoke
334
+ . .venv-smoke/bin/activate
335
+ python -m pip install --upgrade pip
336
+ wheel="$(python - <<'PY'
337
+ from pathlib import Path
338
+ print(next(Path("dist").glob("*.whl")))
339
+ PY
340
+ )"
341
+ python -m pip install "$wheel"
342
+ python -m pip check
343
+ python - <<'PY'
344
+ import tomllib
345
+ from importlib.metadata import entry_points, version
346
+
347
+ import ctx
348
+ import ctx_config
349
+
350
+ with open("pyproject.toml", "rb") as fh:
351
+ expected_scripts = set(tomllib.load(fh)["project"]["scripts"])
352
+
353
+ dist_version = version("claude-ctx")
354
+ if ctx.__version__ != dist_version:
355
+ raise SystemExit(
356
+ f"ctx.__version__={ctx.__version__!r} != metadata {dist_version!r}"
357
+ )
358
+ if ctx_config.cfg.recommendation_top_k != 5:
359
+ raise SystemExit("packaged default config was not loaded")
360
+ scripts = {
361
+ ep.name: ep for ep in entry_points(group="console_scripts")
362
+ if ep.name == "ctx" or ep.name.startswith("ctx-")
363
+ }
364
+ missing = sorted(expected_scripts - set(scripts))
365
+ extra = sorted(set(scripts) - expected_scripts)
366
+ if missing or extra:
367
+ raise SystemExit(
368
+ "wheel console-script surface mismatch\n"
369
+ f"missing: {missing}\n"
370
+ f"extra: {extra}"
371
+ )
372
+ failures = []
373
+ for ep in scripts.values():
374
+ try:
375
+ ep.load()
376
+ except Exception as exc:
377
+ failures.append(f"{ep.name}: {exc!r}")
378
+ if failures:
379
+ raise SystemExit("console script load failures:\n" + "\n".join(failures))
380
+ unsafe_help = {"ctx-mcp-server"}
381
+ safe_help = sorted(expected_scripts - unsafe_help)
382
+ with open("ctx-console-help.txt", "w", encoding="utf-8", newline="\n") as fh:
383
+ fh.write("\n".join(safe_help) + "\n")
384
+ print(
385
+ f"loaded {len(scripts)} ctx console scripts from wheel "
386
+ f"{dist_version}; help-smoke={len(safe_help)}"
387
+ )
388
+ PY
389
+ while IFS= read -r cmd; do
390
+ cmd="${cmd%$'\r'}"
391
+ [[ -z "$cmd" ]] && continue
392
+ echo "help smoke: $cmd"
393
+ "$cmd" --help >/dev/null
394
+ done < ctx-console-help.txt
395
+ python -m pip install "${wheel}[harness]"
396
+ python - <<'PY'
397
+ import litellm
398
+
399
+ print(f"harness extra import ok: litellm {getattr(litellm, '__version__', 'unknown')}")
400
+ PY
401
+
402
+ - name: Upload dist artifact
403
+ uses: actions/upload-artifact@v7
404
+ with:
405
+ name: dist
406
+ path: dist/
407
+
408
+ - name: Upload graph artifact bundle
409
+ if: steps.resolve_graph_assets.outcome == 'success'
410
+ uses: actions/upload-artifact@v7
411
+ with:
412
+ name: graph-release-assets
413
+ path: |
414
+ graph/wiki-graph.tar.gz
415
+ graph/wiki-graph-runtime.tar.gz
416
+ graph/skills-sh-catalog.json.gz
417
+ graph/communities.json
418
+ graph/entity-overlays.jsonl
419
+
420
+ release-assets:
421
+ name: Upload graph release assets
422
+ needs: build
423
+ if: github.event_name == 'push' && needs.build.outputs.graph_assets_available == 'true'
424
+ runs-on: ubuntu-latest
425
+ permissions:
426
+ contents: write
427
+ steps:
428
+ - name: Download graph artifact bundle
429
+ uses: actions/download-artifact@v7
430
+ with:
431
+ name: graph-release-assets
432
+ path: graph-release-assets
433
+
434
+ - name: Upload graph assets to GitHub release
435
+ env:
436
+ GH_TOKEN: ${{ github.token }}
437
+ TAG_NAME: ${{ github.ref_name }}
438
+ run: |
439
+ gh release view "$TAG_NAME" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1 \
440
+ || gh release create "$TAG_NAME" \
441
+ --repo "$GITHUB_REPOSITORY" \
442
+ --title "$TAG_NAME" \
443
+ --notes "ctx $TAG_NAME"
444
+ gh release upload "$TAG_NAME" \
445
+ --repo "$GITHUB_REPOSITORY" \
446
+ graph-release-assets/wiki-graph.tar.gz \
447
+ graph-release-assets/wiki-graph-runtime.tar.gz \
448
+ graph-release-assets/skills-sh-catalog.json.gz \
449
+ graph-release-assets/communities.json \
450
+ graph-release-assets/entity-overlays.jsonl \
451
+ --clobber
452
+
453
+ publish:
454
+ name: Publish to PyPI
455
+ needs:
456
+ - build
457
+ - release-assets
458
+ if: ${{ always() && needs.build.result == 'success' && (needs.release-assets.result == 'success' || (github.event_name == 'workflow_dispatch' && github.event.inputs.repository == 'testpypi')) }}
459
+ runs-on: ubuntu-latest
460
+ permissions:
461
+ contents: read
462
+ id-token: write # required for Trusted Publishing
463
+ environment:
464
+ name: pypi
465
+ url: https://pypi.org/project/claude-ctx/
466
+ steps:
467
+ - name: Download dist artifact
468
+ uses: actions/download-artifact@v7
469
+ with:
470
+ name: dist
471
+ path: dist/
472
+
473
+ - name: Publish to PyPI
474
+ if: github.event_name == 'push'
475
+ uses: pypa/gh-action-pypi-publish@release/v1
476
+
477
+ - name: Publish to TestPyPI
478
+ if: github.event_name == 'workflow_dispatch' && github.event.inputs.repository == 'testpypi'
479
+ uses: pypa/gh-action-pypi-publish@release/v1
480
+ with:
481
+ repository-url: https://test.pypi.org/legacy/
.github/workflows/test.yml CHANGED
@@ -1,704 +1,710 @@
1
- name: Tests
2
-
3
- on:
4
- push:
5
- branches: [main]
6
- pull_request:
7
- branches: [main]
8
-
9
- env:
10
- FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
11
-
12
- permissions:
13
- contents: read
14
-
15
- concurrency:
16
- group: tests-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
17
- cancel-in-progress: true
18
-
19
- jobs:
20
- classify:
21
- name: "Change classifier"
22
- runs-on: ubuntu-latest
23
- outputs:
24
- browser_changed: ${{ steps.classify.outputs.browser_changed }}
25
- ci_changed: ${{ steps.classify.outputs.ci_changed }}
26
- docs_changed: ${{ steps.classify.outputs.docs_changed }}
27
- docs_only: ${{ steps.classify.outputs.docs_only }}
28
- graph_artifact_changed: ${{ steps.classify.outputs.graph_artifact_changed }}
29
- graph_changed: ${{ steps.classify.outputs.graph_changed }}
30
- graph_only: ${{ steps.classify.outputs.graph_only }}
31
- package_changed: ${{ steps.classify.outputs.package_changed }}
32
- similarity_changed: ${{ steps.classify.outputs.similarity_changed }}
33
- source_changed: ${{ steps.classify.outputs.source_changed }}
34
- steps:
35
- - name: Checkout with full history
36
- uses: actions/checkout@v5
37
- with:
38
- fetch-depth: 0
39
- lfs: false
40
-
41
- - name: Classify changed paths
42
- id: classify
43
- shell: bash
44
- env:
45
- BEFORE_SHA: ${{ github.event.before }}
46
- EVENT_NAME: ${{ github.event_name }}
47
- HEAD_SHA: ${{ github.sha }}
48
- PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
49
- run: |
50
- set -euo pipefail
51
- BASE="$BEFORE_SHA"
52
- if [[ "$EVENT_NAME" == "pull_request" && -n "$PR_BASE_SHA" ]]; then
53
- BASE="$PR_BASE_SHA"
54
- fi
55
- if [[ -z "$BASE" || "$BASE" =~ ^0+$ ]]; then
56
- BASE="$(git rev-list --max-parents=0 "$HEAD_SHA")"
57
- fi
58
- if git cat-file -e "$BASE^{commit}" 2>/dev/null; then
59
- git diff --name-only "$BASE" "$HEAD_SHA" > changed-files.txt
60
- elif git cat-file -e "$HEAD_SHA^" 2>/dev/null; then
61
- git diff --name-only "$HEAD_SHA^" "$HEAD_SHA" > changed-files.txt
62
- else
63
- git diff-tree --no-commit-id --name-only -r "$HEAD_SHA" > changed-files.txt
64
- fi
65
-
66
- python scripts/ci_classifier.py changed-files.txt
67
-
68
- static:
69
- name: "Static quality gates"
70
- needs: classify
71
- if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true') }}
72
- runs-on: ubuntu-latest
73
- steps:
74
- - name: Checkout
75
- uses: actions/checkout@v5
76
- with:
77
- lfs: false
78
-
79
- - name: Set up Python 3.11
80
- uses: actions/setup-python@v6
81
- with:
82
- python-version: "3.11"
83
- cache: pip
84
- cache-dependency-path: pyproject.toml
85
-
86
- - name: Install dependencies
87
- run: |
88
- python -m pip install --upgrade pip
89
- python -m pip install ".[dev]"
90
-
91
- - name: Run static quality gates
92
- run: python -m ruff check src hooks scripts && python -m mypy src && python -m pip check
93
-
94
- unit-linux:
95
- name: "unit-linux"
96
- needs: classify
97
- if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true') }}
98
- runs-on: ubuntu-latest
99
- steps:
100
- - name: Checkout
101
- uses: actions/checkout@v5
102
- with:
103
- lfs: false
104
-
105
- - name: Set up Python 3.11
106
- uses: actions/setup-python@v6
107
- with:
108
- python-version: "3.11"
109
- cache: pip
110
- cache-dependency-path: pyproject.toml
111
-
112
- - name: Install dependencies
113
- run: |
114
- python -m pip install --upgrade pip
115
- python -m pip install ".[dev]"
116
-
117
- - name: Run tests with coverage gate
118
- # Bump this number as the coverage sprint ships - never lower it.
119
- run: pytest -q -m "not browser and not integration" --cov=src --cov-report=term-missing --cov-fail-under=40
120
-
121
- - name: Upload coverage artifact
122
- uses: actions/upload-artifact@v7
123
- with:
124
- name: coverage
125
- path: .coverage
126
- include-hidden-files: true
127
- retention-days: 7
128
-
129
- similarity-integration:
130
- name: "Similarity precision/recall"
131
- needs: classify
132
- if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.similarity_changed == 'true') }}
133
- runs-on: ubuntu-latest
134
- steps:
135
- - name: Checkout
136
- uses: actions/checkout@v5
137
- with:
138
- lfs: false
139
-
140
- - name: Set up Python 3.11
141
- uses: actions/setup-python@v6
142
- with:
143
- python-version: "3.11"
144
- cache: pip
145
- cache-dependency-path: pyproject.toml
146
-
147
- - name: Install embedding dependencies
148
- run: |
149
- python -m pip install --upgrade pip
150
- python -m pip install ".[dev,embeddings]"
151
-
152
- - name: Run similarity precision/recall gate
153
- env:
154
- CTX_REQUIRE_SIMILARITY_EVAL: "1"
155
- run: pytest -q --no-cov -m integration src/tests/test_similarity_precision_recall.py
156
-
157
- test:
158
- name: pytest (${{ matrix.os }} / py${{ matrix.python-version }})
159
- if: ${{ github.event_name != 'pull_request' }}
160
- runs-on: ${{ matrix.os }}
161
- strategy:
162
- fail-fast: false
163
- matrix:
164
- include:
165
- - os: ubuntu-latest
166
- python-version: "3.12"
167
- - os: windows-latest
168
- python-version: "3.11"
169
- - os: windows-latest
170
- python-version: "3.12"
171
- - os: macos-latest
172
- python-version: "3.11"
173
- - os: macos-latest
174
- python-version: "3.12"
175
-
176
- steps:
177
- - name: Checkout
178
- uses: actions/checkout@v5
179
- with:
180
- lfs: false
181
-
182
- - name: Set up Python ${{ matrix.python-version }}
183
- uses: actions/setup-python@v6
184
- with:
185
- python-version: ${{ matrix.python-version }}
186
- cache: pip
187
- cache-dependency-path: pyproject.toml
188
-
189
- - name: Install dependencies
190
- run: |
191
- python -m pip install --upgrade pip
192
- python -m pip install ".[dev]"
193
-
194
- - name: Run tests without coverage
195
- run: pytest -q -m "not browser and not integration" --no-cov
196
-
197
- contract-compat:
198
- name: "Contract compatibility (${{ matrix.os }})"
199
- needs: classify
200
- if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true') }}
201
- runs-on: ${{ matrix.os }}
202
- strategy:
203
- fail-fast: false
204
- matrix:
205
- os: [windows-latest, macos-latest]
206
-
207
- steps:
208
- - name: Checkout
209
- uses: actions/checkout@v5
210
- with:
211
- lfs: false
212
-
213
- - name: Set up Python 3.12
214
- uses: actions/setup-python@v6
215
- with:
216
- python-version: "3.12"
217
-
218
- - name: Install dependencies
219
- run: |
220
- python -m pip install --upgrade pip
221
- python -m pip install ".[dev]"
222
-
223
- - name: Run cross-OS contract tests
224
- run: python -m pytest -q --no-cov src/tests/test_clean_host_contract.py src/tests/test_package_scaffold.py
225
-
226
- e2e-canary:
227
- name: "A-Z alive-loop E2E canary"
228
- needs: classify
229
- if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true') }}
230
- runs-on: ubuntu-latest
231
- steps:
232
- - name: Checkout
233
- uses: actions/checkout@v5
234
- with:
235
- lfs: false
236
-
237
- - name: Set up Python 3.11
238
- uses: actions/setup-python@v6
239
- with:
240
- python-version: "3.11"
241
- cache: pip
242
- cache-dependency-path: pyproject.toml
243
-
244
- - name: Install dependencies
245
- run: |
246
- python -m pip install --upgrade pip
247
- python -m pip install ".[dev]"
248
-
249
- - name: Run E2E + fuzz canary suite
250
- # These two files pin the critical-path invariants:
251
- # test_alive_loop_e2e.py: A-Z user journey (signals → bundle →
252
- # install → unload → purge) — any handoff regression trips it.
253
- # test_fuzz_yaml_rendering.py: property-based YAML injection
254
- # coverage on install/enrich render_scalar.
255
- # They live in the main matrix job already, but pulling them
256
- # forward as a separate fail-fast canary surfaces the regression
257
- # in seconds instead of waiting for the full test run.
258
- run: |
259
- pytest -q --no-cov \
260
- src/tests/test_alive_loop_e2e.py \
261
- src/tests/test_fuzz_yaml_rendering.py
262
-
263
- docs-check:
264
- name: "Docs strict build"
265
- needs: classify
266
- if: ${{ github.event_name == 'pull_request' && needs.classify.outputs.docs_changed == 'true' }}
267
- runs-on: ubuntu-latest
268
- steps:
269
- - name: Checkout
270
- uses: actions/checkout@v5
271
- with:
272
- lfs: false
273
-
274
- - name: Set up Python 3.11
275
- uses: actions/setup-python@v6
276
- with:
277
- python-version: "3.11"
278
- cache: pip
279
- cache-dependency-path: requirements-docs.txt
280
-
281
- - name: Build docs strictly
282
- run: |
283
- python -m pip install --upgrade pip
284
- python -m pip install -r requirements-docs.txt
285
- python -m mkdocs build --strict
286
-
287
- graph-check:
288
- name: "Graph artifact check"
289
- needs: classify
290
- if: ${{ github.event_name == 'pull_request' && needs.classify.outputs.graph_artifact_changed == 'true' }}
291
- runs-on: ubuntu-latest
292
- steps:
293
- - name: Checkout graph artifacts
294
- uses: actions/checkout@v5
295
- with:
296
- lfs: false
297
-
298
- - name: Resolve graph LFS artifacts
299
- shell: bash
300
- env:
301
- GH_TOKEN: ${{ github.token }}
302
- run: |
303
- set -euo pipefail
304
- git lfs install --local
305
- if git lfs pull --include="graph/wiki-graph.tar.gz,graph/wiki-graph-runtime.tar.gz" --exclude=""; then
306
- exit 0
307
- fi
308
- echo "Git LFS download failed; trying matching prior release asset."
309
- python - <<'PY'
310
- import hashlib
311
- import json
312
- import os
313
- from pathlib import Path
314
- import subprocess
315
- import time
316
- import urllib.request
317
-
318
- repo = os.environ["GITHUB_REPOSITORY"]
319
- release_asset_wait_seconds = 300
320
- release_asset_poll_seconds = 10
321
-
322
- def load_releases() -> list[dict]:
323
- return json.loads(subprocess.check_output(
324
- ["gh", "api", f"repos/{repo}/releases?per_page=50"],
325
- text=True,
326
- ))
327
-
328
- def hydrate_from_release(path_name: str, hydrated_min_size: int) -> None:
329
- graph_tar = Path(path_name)
330
- pointer = graph_tar.read_text(encoding="utf-8", errors="replace")
331
- expected_oid = ""
332
- expected_size = 0
333
- for line in pointer.splitlines():
334
- if line.startswith("oid sha256:"):
335
- expected_oid = line.split(":", 1)[1].strip()
336
- elif line.startswith("size "):
337
- expected_size = int(line.split(" ", 1)[1].strip())
338
- if not expected_oid:
339
- if graph_tar.stat().st_size > hydrated_min_size:
340
- print(f"{graph_tar} is already hydrated")
341
- return
342
- raise SystemExit(f"{path_name} is neither hydrated nor an LFS pointer")
343
-
344
- deadline = time.monotonic() + release_asset_wait_seconds
345
- while True:
346
- candidates = []
347
- for release in load_releases():
348
- tag_name = str(release.get("tag_name") or "")
349
- is_graph_cache = tag_name.startswith("graph-artifacts-")
350
- if release.get("draft") or (
351
- release.get("prerelease") and not is_graph_cache
352
- ):
353
- continue
354
- for asset in release.get("assets", []):
355
- if asset.get("name") != graph_tar.name:
356
- continue
357
- digest = str(asset.get("digest") or "")
358
- size = int(asset.get("size") or 0)
359
- if size != expected_size:
360
- continue
361
- if digest and digest != f"sha256:{expected_oid}":
362
- continue
363
- candidates.append((tag_name, asset))
364
-
365
- if candidates:
366
- break
367
- if time.monotonic() >= deadline:
368
- raise SystemExit(
369
- f"No previous release asset matches {path_name} "
370
- f"sha256:{expected_oid} size:{expected_size}"
371
- )
372
- print(
373
- f"Waiting for matching release asset {graph_tar.name} "
374
- f"sha256:{expected_oid} size:{expected_size}"
375
- )
376
- time.sleep(release_asset_poll_seconds)
377
-
378
- source_tag, asset = candidates[0]
379
- tmp = graph_tar.with_name(f"{graph_tar.name}.download")
380
- sha = hashlib.sha256()
381
- total = 0
382
- with urllib.request.urlopen(asset["browser_download_url"], timeout=300) as resp: # noqa: S310
383
- with tmp.open("wb") as fh:
384
- while True:
385
- chunk = resp.read(1024 * 1024)
386
- if not chunk:
387
- break
388
- sha.update(chunk)
389
- total += len(chunk)
390
- fh.write(chunk)
391
- actual_oid = sha.hexdigest()
392
- if actual_oid != expected_oid or total != expected_size:
393
- tmp.unlink(missing_ok=True)
394
- raise SystemExit(
395
- f"Downloaded {path_name} does not match LFS pointer: "
396
- f"sha256:{actual_oid} size:{total}"
397
- )
398
- tmp.replace(graph_tar)
399
- print(
400
- f"Hydrated {path_name} from {source_tag} release asset "
401
- f"sha256:{actual_oid} size:{total}"
402
- )
403
-
404
- hydrate_from_release("graph/wiki-graph.tar.gz", 100_000_000)
405
- hydrate_from_release("graph/wiki-graph-runtime.tar.gz", 10_000_000)
406
- PY
407
-
408
- - name: Validate shipped graph artifacts
409
- run: |
410
- python src/validate_graph_artifacts.py \
411
- --graph-dir graph \
412
- --deep \
413
- --min-nodes 100000 \
414
- --min-edges 2000000 \
415
- --min-skills-sh-nodes 89000 \
416
- --min-semantic-edges 1000000 \
417
- --expected-nodes 102928 \
418
- --expected-edges 2913960 \
419
- --expected-semantic-edges 1683193 \
420
- --expected-harness-nodes 207 \
421
- --expected-skills-sh-nodes 89471 \
422
- --expected-skills-sh-catalog-entries 89465 \
423
- --expected-skills-sh-converted 89465 \
424
- --expected-skill-pages 91464 \
425
- --expected-agent-pages 467 \
426
- --expected-mcp-pages 10790 \
427
- --expected-harness-pages 207 \
428
- --line-threshold 180 \
429
- --max-stage-lines 40
430
-
431
- browser-security:
432
- name: "Browser monitor security"
433
- needs: classify
434
- if: ${{ github.event_name == 'push' || needs.classify.outputs.browser_changed == 'true' }}
435
- runs-on: ubuntu-latest
436
- steps:
437
- - name: Checkout
438
- uses: actions/checkout@v5
439
- with:
440
- lfs: false
441
-
442
- - name: Set up Python 3.12
443
- uses: actions/setup-python@v6
444
- with:
445
- python-version: "3.12"
446
- cache: pip
447
- cache-dependency-path: pyproject.toml
448
-
449
- - name: Install browser Python dependencies
450
- run: |
451
- python -m pip install --upgrade pip
452
- python -m pip install ".[dev,browser]"
453
-
454
- - name: Detect Playwright version
455
- id: playwright
456
- run: |
457
- python - <<'PY' >> "$GITHUB_OUTPUT"
458
- from importlib.metadata import version
459
-
460
- print(f"version={version('playwright')}")
461
- PY
462
-
463
- - name: Cache Playwright browsers
464
- uses: actions/cache@v4
465
- with:
466
- path: ~/.cache/ms-playwright
467
- key: playwright-${{ runner.os }}-${{ steps.playwright.outputs.version }}
468
-
469
- - name: Install browser runtime
470
- run: |
471
- python -m playwright install-deps chromium
472
- python -m playwright install chromium
473
-
474
- - name: Run browser security tests
475
- run: pytest -q --no-cov -m browser src/tests/test_ctx_monitor_browser.py
476
-
477
- package-build:
478
- name: "Build wheel package"
479
- needs: classify
480
- if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true') }}
481
- runs-on: ubuntu-latest
482
- steps:
483
- - name: Checkout
484
- uses: actions/checkout@v5
485
- with:
486
- lfs: false
487
-
488
- - name: Set up Python 3.12
489
- uses: actions/setup-python@v6
490
- with:
491
- python-version: "3.12"
492
- cache: pip
493
- cache-dependency-path: pyproject.toml
494
-
495
- - name: Build and inspect wheel
496
- run: |
497
- python -m pip install --upgrade pip
498
- python -m pip install build twine
499
- python -m build
500
- python -m twine check dist/*
501
- python - <<'PY'
502
- from pathlib import Path
503
-
504
- wheels = sorted(Path("dist").glob("*.whl"))
505
- if len(wheels) != 1:
506
- raise SystemExit(f"expected exactly one wheel, found {len(wheels)}")
507
- wheel = wheels[0]
508
- if not wheel.name.endswith("-py3-none-any.whl"):
509
- message = f"expected a universal pure-Python wheel, got {wheel.name}"
510
- raise SystemExit(message)
511
- print(f"built package-smoke wheel: {wheel.name}")
512
- PY
513
-
514
- - name: Upload wheel artifact
515
- uses: actions/upload-artifact@v7
516
- with:
517
- name: package-smoke-wheel
518
- path: dist/*.whl
519
- retention-days: 7
520
-
521
- package-smoke:
522
- name: "Wheel package smoke (${{ matrix.os }})"
523
- needs:
524
- - classify
525
- - package-build
526
- if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true') }}
527
- runs-on: ${{ matrix.os }}
528
- strategy:
529
- fail-fast: false
530
- matrix:
531
- os: [ubuntu-latest, windows-latest, macos-latest]
532
- defaults:
533
- run:
534
- shell: bash
535
- steps:
536
- - name: Checkout
537
- uses: actions/checkout@v5
538
- with:
539
- lfs: false
540
-
541
- - name: Set up Python 3.12
542
- uses: actions/setup-python@v6
543
- with:
544
- python-version: "3.12"
545
- cache: pip
546
- cache-dependency-path: pyproject.toml
547
-
548
- - name: Download wheel artifact
549
- uses: actions/download-artifact@v7
550
- with:
551
- name: package-smoke-wheel
552
- path: dist
553
-
554
- - name: Install wheel in clean venv
555
- run: |
556
- python -m venv .venv-smoke
557
- if [[ "$RUNNER_OS" == "Windows" ]]; then
558
- . .venv-smoke/Scripts/activate
559
- else
560
- . .venv-smoke/bin/activate
561
- fi
562
- python -m pip install --upgrade pip
563
- python -m pip install dist/*.whl
564
- python -m pip check
565
- python - <<'PY'
566
- import tomllib
567
- from importlib.metadata import entry_points, version
568
-
569
- import ctx
570
-
571
- with open("pyproject.toml", "rb") as fh:
572
- expected_scripts = set(tomllib.load(fh)["project"]["scripts"])
573
-
574
- dist_version = version("claude-ctx")
575
- if ctx.__version__ != dist_version:
576
- raise SystemExit(
577
- f"ctx.__version__={ctx.__version__!r} != metadata {dist_version!r}"
578
- )
579
-
580
- script_eps = {
581
- ep.name: ep
582
- for ep in entry_points(group="console_scripts")
583
- if ep.name == "ctx" or ep.name.startswith("ctx-")
584
- }
585
- missing = sorted(expected_scripts - set(script_eps))
586
- extra = sorted(set(script_eps) - expected_scripts)
587
- if missing or extra:
588
- raise SystemExit(
589
- "wheel console-script surface mismatch\n"
590
- f"missing: {missing}\n"
591
- f"extra: {extra}"
592
- )
593
- failures = []
594
- for ep in script_eps.values():
595
- try:
596
- ep.load()
597
- except Exception as exc:
598
- failures.append(f"{ep.name}: {exc!r}")
599
- if failures:
600
- raise SystemExit("console script load failures:\n" + "\n".join(failures))
601
-
602
- unsafe_help = {"ctx-mcp-server"}
603
- safe_help = sorted(expected_scripts - unsafe_help)
604
- with open(
605
- "ctx-console-help.txt", "w", encoding="utf-8", newline="\n"
606
- ) as fh:
607
- fh.write("\n".join(safe_help) + "\n")
608
- print(
609
- f"loaded {len(script_eps)} ctx console scripts from wheel "
610
- f"{dist_version}; help-smoke={len(safe_help)}"
611
- )
612
- PY
613
- while IFS= read -r cmd; do
614
- cmd="${cmd%$'\r'}"
615
- [[ -z "$cmd" ]] && continue
616
- echo "help smoke: $cmd"
617
- "$cmd" --help >/dev/null
618
- done < ctx-console-help.txt
619
-
620
- clean-host-contract:
621
- name: "Clean host contract"
622
- needs: classify
623
- if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true') }}
624
- runs-on: ubuntu-latest
625
- timeout-minutes: 25
626
- steps:
627
- - name: Checkout
628
- uses: actions/checkout@v5
629
- with:
630
- lfs: false
631
-
632
- - name: Set up Python 3.12
633
- uses: actions/setup-python@v6
634
- with:
635
- python-version: "3.12"
636
- cache: pip
637
- cache-dependency-path: pyproject.toml
638
-
639
- - name: Upgrade pip
640
- run: python -m pip install --upgrade pip
641
-
642
- - name: Run clean-host contract
643
- run: python scripts/clean_host_contract.py --fast
644
-
645
- no-test-no-merge:
646
- name: "Contract changes must touch tests"
647
- needs: classify
648
- runs-on: ubuntu-latest
649
- if: ${{ github.event_name == 'pull_request' && needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true' }}
650
- steps:
651
- - name: Checkout with full history
652
- uses: actions/checkout@v5
653
- with:
654
- fetch-depth: 0
655
- lfs: false
656
-
657
- - name: Enforce test-coverage-per-PR policy
658
- # Policy: any product or CI/package contract change
659
- # must be accompanied by at least one test file change in the
660
- # same PR. Exemptions:
661
- # - Pure docs / comment changes (matched by a trivial heuristic)
662
- # - Config JSON (src/config.json) — schema changes get tests
663
- # for the accessor, not the JSON itself.
664
- # - Changes ONLY inside __pycache__, .pyc files, etc.
665
- run: |
666
- set -euo pipefail
667
- BASE="${{ github.event.pull_request.base.sha }}"
668
- HEAD="${{ github.event.pull_request.head.sha }}"
669
- LABELS='${{ toJson(github.event.pull_request.labels.*.name) }}'
670
- python scripts/ci_no_test_policy.py \
671
- --base "$BASE" \
672
- --head "$HEAD" \
673
- --labels-json "$LABELS"
674
-
675
- ci-required:
676
- name: "CI required"
677
- runs-on: ubuntu-latest
678
- needs:
679
- - classify
680
- - static
681
- - unit-linux
682
- - similarity-integration
683
- - test
684
- - contract-compat
685
- - e2e-canary
686
- - docs-check
687
- - graph-check
688
- - browser-security
689
- - package-smoke
690
- - package-build
691
- - clean-host-contract
692
- - no-test-no-merge
693
- if: ${{ always() }}
694
- steps:
695
- - name: Checkout
696
- uses: actions/checkout@v5
697
- with:
698
- lfs: false
699
-
700
- - name: Check required job results
701
- env:
702
- EVENT_NAME: ${{ github.event_name }}
703
- NEEDS_JSON: ${{ toJson(needs) }}
704
- run: python scripts/ci_required.py
 
 
 
 
 
 
 
1
+ name: Tests
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ env:
10
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
11
+
12
+ permissions:
13
+ contents: read
14
+
15
+ concurrency:
16
+ group: tests-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
17
+ cancel-in-progress: true
18
+
19
+ jobs:
20
+ classify:
21
+ name: "Change classifier"
22
+ runs-on: ubuntu-latest
23
+ outputs:
24
+ browser_changed: ${{ steps.classify.outputs.browser_changed }}
25
+ ci_changed: ${{ steps.classify.outputs.ci_changed }}
26
+ docs_changed: ${{ steps.classify.outputs.docs_changed }}
27
+ docs_only: ${{ steps.classify.outputs.docs_only }}
28
+ graph_artifact_changed: ${{ steps.classify.outputs.graph_artifact_changed }}
29
+ graph_changed: ${{ steps.classify.outputs.graph_changed }}
30
+ graph_only: ${{ steps.classify.outputs.graph_only }}
31
+ package_changed: ${{ steps.classify.outputs.package_changed }}
32
+ similarity_changed: ${{ steps.classify.outputs.similarity_changed }}
33
+ source_changed: ${{ steps.classify.outputs.source_changed }}
34
+ steps:
35
+ - name: Checkout with full history
36
+ uses: actions/checkout@v5
37
+ with:
38
+ fetch-depth: 0
39
+ lfs: false
40
+
41
+ - name: Classify changed paths
42
+ id: classify
43
+ shell: bash
44
+ env:
45
+ BEFORE_SHA: ${{ github.event.before }}
46
+ EVENT_NAME: ${{ github.event_name }}
47
+ HEAD_SHA: ${{ github.sha }}
48
+ PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
49
+ run: |
50
+ set -euo pipefail
51
+ BASE="$BEFORE_SHA"
52
+ if [[ "$EVENT_NAME" == "pull_request" && -n "$PR_BASE_SHA" ]]; then
53
+ BASE="$PR_BASE_SHA"
54
+ fi
55
+ if [[ -z "$BASE" || "$BASE" =~ ^0+$ ]]; then
56
+ BASE="$(git rev-list --max-parents=0 "$HEAD_SHA")"
57
+ fi
58
+ if git cat-file -e "$BASE^{commit}" 2>/dev/null; then
59
+ git diff --name-only "$BASE" "$HEAD_SHA" > changed-files.txt
60
+ elif git cat-file -e "$HEAD_SHA^" 2>/dev/null; then
61
+ git diff --name-only "$HEAD_SHA^" "$HEAD_SHA" > changed-files.txt
62
+ else
63
+ git diff-tree --no-commit-id --name-only -r "$HEAD_SHA" > changed-files.txt
64
+ fi
65
+
66
+ python scripts/ci_classifier.py changed-files.txt
67
+
68
+ static:
69
+ name: "Static quality gates"
70
+ needs: classify
71
+ if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true') }}
72
+ runs-on: ubuntu-latest
73
+ steps:
74
+ - name: Checkout
75
+ uses: actions/checkout@v5
76
+ with:
77
+ lfs: false
78
+
79
+ - name: Set up Python 3.11
80
+ uses: actions/setup-python@v6
81
+ with:
82
+ python-version: "3.11"
83
+ cache: pip
84
+ cache-dependency-path: pyproject.toml
85
+
86
+ - name: Install dependencies
87
+ run: |
88
+ python -m pip install --upgrade pip
89
+ python -m pip install ".[dev]"
90
+
91
+ - name: Run static quality gates
92
+ run: python -m ruff check src hooks scripts && python -m mypy src && python -m pip check
93
+
94
+ unit-linux:
95
+ name: "unit-linux"
96
+ needs: classify
97
+ if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true') }}
98
+ runs-on: ubuntu-latest
99
+ steps:
100
+ - name: Checkout
101
+ uses: actions/checkout@v5
102
+ with:
103
+ lfs: false
104
+
105
+ - name: Set up Python 3.11
106
+ uses: actions/setup-python@v6
107
+ with:
108
+ python-version: "3.11"
109
+ cache: pip
110
+ cache-dependency-path: pyproject.toml
111
+
112
+ - name: Install dependencies
113
+ run: |
114
+ python -m pip install --upgrade pip
115
+ python -m pip install ".[dev]"
116
+
117
+ - name: Run tests with coverage gate
118
+ # Bump this number as the coverage sprint ships - never lower it.
119
+ run: pytest -q -m "not browser and not integration" --cov=src --cov-report=term-missing --cov-fail-under=40
120
+
121
+ - name: Upload coverage artifact
122
+ uses: actions/upload-artifact@v7
123
+ with:
124
+ name: coverage
125
+ path: .coverage
126
+ include-hidden-files: true
127
+ retention-days: 7
128
+
129
+ similarity-integration:
130
+ name: "Similarity precision/recall"
131
+ needs: classify
132
+ if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.similarity_changed == 'true') }}
133
+ runs-on: ubuntu-latest
134
+ steps:
135
+ - name: Checkout
136
+ uses: actions/checkout@v5
137
+ with:
138
+ lfs: false
139
+
140
+ - name: Set up Python 3.11
141
+ uses: actions/setup-python@v6
142
+ with:
143
+ python-version: "3.11"
144
+ cache: pip
145
+ cache-dependency-path: pyproject.toml
146
+
147
+ - name: Install embedding dependencies
148
+ run: |
149
+ python -m pip install --upgrade pip
150
+ python -m pip install ".[dev,embeddings]"
151
+
152
+ - name: Run similarity precision/recall gate
153
+ env:
154
+ CTX_REQUIRE_SIMILARITY_EVAL: "1"
155
+ run: pytest -q --no-cov -m integration src/tests/test_similarity_precision_recall.py
156
+
157
+ test:
158
+ name: pytest (${{ matrix.os }} / py${{ matrix.python-version }})
159
+ if: ${{ github.event_name != 'pull_request' }}
160
+ runs-on: ${{ matrix.os }}
161
+ strategy:
162
+ fail-fast: false
163
+ matrix:
164
+ include:
165
+ - os: ubuntu-latest
166
+ python-version: "3.12"
167
+ - os: windows-latest
168
+ python-version: "3.11"
169
+ - os: windows-latest
170
+ python-version: "3.12"
171
+ - os: macos-latest
172
+ python-version: "3.11"
173
+ - os: macos-latest
174
+ python-version: "3.12"
175
+
176
+ steps:
177
+ - name: Checkout
178
+ uses: actions/checkout@v5
179
+ with:
180
+ lfs: false
181
+
182
+ - name: Set up Python ${{ matrix.python-version }}
183
+ uses: actions/setup-python@v6
184
+ with:
185
+ python-version: ${{ matrix.python-version }}
186
+ cache: pip
187
+ cache-dependency-path: pyproject.toml
188
+
189
+ - name: Install dependencies
190
+ run: |
191
+ python -m pip install --upgrade pip
192
+ python -m pip install ".[dev]"
193
+
194
+ - name: Run tests without coverage
195
+ run: pytest -q -m "not browser and not integration" --no-cov
196
+
197
+ contract-compat:
198
+ name: "Contract compatibility (${{ matrix.os }})"
199
+ needs: classify
200
+ if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true') }}
201
+ runs-on: ${{ matrix.os }}
202
+ strategy:
203
+ fail-fast: false
204
+ matrix:
205
+ os: [windows-latest, macos-latest]
206
+
207
+ steps:
208
+ - name: Checkout
209
+ uses: actions/checkout@v5
210
+ with:
211
+ lfs: false
212
+
213
+ - name: Set up Python 3.12
214
+ uses: actions/setup-python@v6
215
+ with:
216
+ python-version: "3.12"
217
+
218
+ - name: Install dependencies
219
+ run: |
220
+ python -m pip install --upgrade pip
221
+ python -m pip install ".[dev]"
222
+
223
+ - name: Run cross-OS contract tests
224
+ run: python -m pytest -q --no-cov src/tests/test_clean_host_contract.py src/tests/test_package_scaffold.py
225
+
226
+ e2e-canary:
227
+ name: "A-Z alive-loop E2E canary"
228
+ needs: classify
229
+ if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true') }}
230
+ runs-on: ubuntu-latest
231
+ steps:
232
+ - name: Checkout
233
+ uses: actions/checkout@v5
234
+ with:
235
+ lfs: false
236
+
237
+ - name: Set up Python 3.11
238
+ uses: actions/setup-python@v6
239
+ with:
240
+ python-version: "3.11"
241
+ cache: pip
242
+ cache-dependency-path: pyproject.toml
243
+
244
+ - name: Install dependencies
245
+ run: |
246
+ python -m pip install --upgrade pip
247
+ python -m pip install ".[dev]"
248
+
249
+ - name: Run E2E + fuzz canary suite
250
+ # These two files pin the critical-path invariants:
251
+ # test_alive_loop_e2e.py: A-Z user journey (signals → bundle →
252
+ # install → unload → purge) — any handoff regression trips it.
253
+ # test_fuzz_yaml_rendering.py: property-based YAML injection
254
+ # coverage on install/enrich render_scalar.
255
+ # They live in the main matrix job already, but pulling them
256
+ # forward as a separate fail-fast canary surfaces the regression
257
+ # in seconds instead of waiting for the full test run.
258
+ run: |
259
+ pytest -q --no-cov \
260
+ src/tests/test_alive_loop_e2e.py \
261
+ src/tests/test_fuzz_yaml_rendering.py
262
+
263
+ docs-check:
264
+ name: "Docs strict build"
265
+ needs: classify
266
+ if: ${{ github.event_name == 'pull_request' && needs.classify.outputs.docs_changed == 'true' }}
267
+ runs-on: ubuntu-latest
268
+ steps:
269
+ - name: Checkout
270
+ uses: actions/checkout@v5
271
+ with:
272
+ lfs: false
273
+
274
+ - name: Set up Python 3.11
275
+ uses: actions/setup-python@v6
276
+ with:
277
+ python-version: "3.11"
278
+ cache: pip
279
+ cache-dependency-path: requirements-docs.txt
280
+
281
+ - name: Build docs strictly
282
+ run: |
283
+ python -m pip install --upgrade pip
284
+ python -m pip install -r requirements-docs.txt
285
+ python -m mkdocs build --strict
286
+
287
+ graph-check:
288
+ name: "Graph artifact check"
289
+ needs: classify
290
+ if: ${{ github.event_name == 'pull_request' && needs.classify.outputs.graph_artifact_changed == 'true' }}
291
+ runs-on: ubuntu-latest
292
+ steps:
293
+ - name: Checkout graph artifacts
294
+ uses: actions/checkout@v5
295
+ with:
296
+ lfs: false
297
+
298
+ - name: Resolve graph artifacts from release assets
299
+ shell: bash
300
+ env:
301
+ GH_TOKEN: ${{ github.token }}
302
+ run: |
303
+ set -euo pipefail
304
+ echo "Resolving graph artifacts from matching release assets to avoid Git LFS bandwidth."
305
+ python - <<'PY'
306
+ import hashlib
307
+ import json
308
+ import os
309
+ from pathlib import Path
310
+ import subprocess
311
+ import time
312
+ import urllib.request
313
+
314
+ repo = os.environ["GITHUB_REPOSITORY"]
315
+ release_asset_wait_seconds = 300
316
+ release_asset_poll_seconds = 10
317
+ expected_graph_assets = {
318
+ "graph/wiki-graph.tar.gz": {
319
+ "sha256": "91b30795e7d200cf31a62a8749969d12658f5f74636d2de06d6b2b24b393c12f",
320
+ "size": 457545675,
321
+ },
322
+ "graph/wiki-graph-runtime.tar.gz": {
323
+ "sha256": "334fb19bace3fd6e4b92087850f17297fb248032957d123f3f1432dfde2e36c0",
324
+ "size": 175773376,
325
+ },
326
+ }
327
+
328
+ def load_releases() -> list[dict]:
329
+ return json.loads(subprocess.check_output(
330
+ ["gh", "api", f"repos/{repo}/releases?per_page=50"],
331
+ text=True,
332
+ ))
333
+
334
+ def hydrate_from_release(path_name: str, hydrated_min_size: int) -> None:
335
+ graph_tar = Path(path_name)
336
+ fallback = expected_graph_assets[path_name]
337
+ expected_oid = fallback["sha256"]
338
+ expected_size = int(fallback["size"])
339
+ if graph_tar.exists():
340
+ pointer = graph_tar.read_text(encoding="utf-8", errors="replace")
341
+ for line in pointer.splitlines():
342
+ if line.startswith("oid sha256:"):
343
+ expected_oid = line.split(":", 1)[1].strip()
344
+ elif line.startswith("size "):
345
+ expected_size = int(line.split(" ", 1)[1].strip())
346
+ if not pointer.startswith("version https://git-lfs.github.com/spec/v1") and graph_tar.stat().st_size > hydrated_min_size:
347
+ print(f"{graph_tar} is already hydrated")
348
+ return
349
+
350
+ deadline = time.monotonic() + release_asset_wait_seconds
351
+ while True:
352
+ candidates = []
353
+ for release in load_releases():
354
+ tag_name = str(release.get("tag_name") or "")
355
+ is_graph_cache = tag_name.startswith("graph-artifacts-")
356
+ if release.get("draft") or (
357
+ release.get("prerelease") and not is_graph_cache
358
+ ):
359
+ continue
360
+ for asset in release.get("assets", []):
361
+ if asset.get("name") != graph_tar.name:
362
+ continue
363
+ digest = str(asset.get("digest") or "")
364
+ size = int(asset.get("size") or 0)
365
+ if size != expected_size:
366
+ continue
367
+ if digest and digest != f"sha256:{expected_oid}":
368
+ continue
369
+ candidates.append((tag_name, asset))
370
+
371
+ if candidates:
372
+ break
373
+ if time.monotonic() >= deadline:
374
+ raise SystemExit(
375
+ f"No previous release asset matches {path_name} "
376
+ f"sha256:{expected_oid} size:{expected_size}"
377
+ )
378
+ print(
379
+ f"Waiting for matching release asset {graph_tar.name} "
380
+ f"sha256:{expected_oid} size:{expected_size}"
381
+ )
382
+ time.sleep(release_asset_poll_seconds)
383
+
384
+ source_tag, asset = candidates[0]
385
+ tmp = graph_tar.with_name(f"{graph_tar.name}.download")
386
+ sha = hashlib.sha256()
387
+ total = 0
388
+ with urllib.request.urlopen(asset["browser_download_url"], timeout=300) as resp: # noqa: S310
389
+ with tmp.open("wb") as fh:
390
+ while True:
391
+ chunk = resp.read(1024 * 1024)
392
+ if not chunk:
393
+ break
394
+ sha.update(chunk)
395
+ total += len(chunk)
396
+ fh.write(chunk)
397
+ actual_oid = sha.hexdigest()
398
+ if actual_oid != expected_oid or total != expected_size:
399
+ tmp.unlink(missing_ok=True)
400
+ raise SystemExit(
401
+ f"Downloaded {path_name} does not match LFS pointer: "
402
+ f"sha256:{actual_oid} size:{total}"
403
+ )
404
+ tmp.replace(graph_tar)
405
+ print(
406
+ f"Hydrated {path_name} from {source_tag} release asset "
407
+ f"sha256:{actual_oid} size:{total}"
408
+ )
409
+
410
+ hydrate_from_release("graph/wiki-graph.tar.gz", 100_000_000)
411
+ hydrate_from_release("graph/wiki-graph-runtime.tar.gz", 10_000_000)
412
+ PY
413
+
414
+ - name: Validate shipped graph artifacts
415
+ run: |
416
+ python src/validate_graph_artifacts.py \
417
+ --graph-dir graph \
418
+ --deep \
419
+ --min-nodes 100000 \
420
+ --min-edges 2000000 \
421
+ --min-skills-sh-nodes 89000 \
422
+ --min-semantic-edges 1000000 \
423
+ --expected-nodes 102928 \
424
+ --expected-edges 2913960 \
425
+ --expected-semantic-edges 1683193 \
426
+ --expected-harness-nodes 207 \
427
+ --expected-skills-sh-nodes 89471 \
428
+ --expected-skills-sh-catalog-entries 89465 \
429
+ --expected-skills-sh-converted 89465 \
430
+ --expected-skill-pages 91464 \
431
+ --expected-agent-pages 467 \
432
+ --expected-mcp-pages 10790 \
433
+ --expected-harness-pages 207 \
434
+ --line-threshold 180 \
435
+ --max-stage-lines 40
436
+
437
+ browser-security:
438
+ name: "Browser monitor security"
439
+ needs: classify
440
+ if: ${{ github.event_name == 'push' || needs.classify.outputs.browser_changed == 'true' }}
441
+ runs-on: ubuntu-latest
442
+ steps:
443
+ - name: Checkout
444
+ uses: actions/checkout@v5
445
+ with:
446
+ lfs: false
447
+
448
+ - name: Set up Python 3.12
449
+ uses: actions/setup-python@v6
450
+ with:
451
+ python-version: "3.12"
452
+ cache: pip
453
+ cache-dependency-path: pyproject.toml
454
+
455
+ - name: Install browser Python dependencies
456
+ run: |
457
+ python -m pip install --upgrade pip
458
+ python -m pip install ".[dev,browser]"
459
+
460
+ - name: Detect Playwright version
461
+ id: playwright
462
+ run: |
463
+ python - <<'PY' >> "$GITHUB_OUTPUT"
464
+ from importlib.metadata import version
465
+
466
+ print(f"version={version('playwright')}")
467
+ PY
468
+
469
+ - name: Cache Playwright browsers
470
+ uses: actions/cache@v4
471
+ with:
472
+ path: ~/.cache/ms-playwright
473
+ key: playwright-${{ runner.os }}-${{ steps.playwright.outputs.version }}
474
+
475
+ - name: Install browser runtime
476
+ run: |
477
+ python -m playwright install-deps chromium
478
+ python -m playwright install chromium
479
+
480
+ - name: Run browser security tests
481
+ run: pytest -q --no-cov -m browser src/tests/test_ctx_monitor_browser.py
482
+
483
+ package-build:
484
+ name: "Build wheel package"
485
+ needs: classify
486
+ if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true') }}
487
+ runs-on: ubuntu-latest
488
+ steps:
489
+ - name: Checkout
490
+ uses: actions/checkout@v5
491
+ with:
492
+ lfs: false
493
+
494
+ - name: Set up Python 3.12
495
+ uses: actions/setup-python@v6
496
+ with:
497
+ python-version: "3.12"
498
+ cache: pip
499
+ cache-dependency-path: pyproject.toml
500
+
501
+ - name: Build and inspect wheel
502
+ run: |
503
+ python -m pip install --upgrade pip
504
+ python -m pip install build twine
505
+ python -m build
506
+ python -m twine check dist/*
507
+ python - <<'PY'
508
+ from pathlib import Path
509
+
510
+ wheels = sorted(Path("dist").glob("*.whl"))
511
+ if len(wheels) != 1:
512
+ raise SystemExit(f"expected exactly one wheel, found {len(wheels)}")
513
+ wheel = wheels[0]
514
+ if not wheel.name.endswith("-py3-none-any.whl"):
515
+ message = f"expected a universal pure-Python wheel, got {wheel.name}"
516
+ raise SystemExit(message)
517
+ print(f"built package-smoke wheel: {wheel.name}")
518
+ PY
519
+
520
+ - name: Upload wheel artifact
521
+ uses: actions/upload-artifact@v7
522
+ with:
523
+ name: package-smoke-wheel
524
+ path: dist/*.whl
525
+ retention-days: 7
526
+
527
+ package-smoke:
528
+ name: "Wheel package smoke (${{ matrix.os }})"
529
+ needs:
530
+ - classify
531
+ - package-build
532
+ if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true') }}
533
+ runs-on: ${{ matrix.os }}
534
+ strategy:
535
+ fail-fast: false
536
+ matrix:
537
+ os: [ubuntu-latest, windows-latest, macos-latest]
538
+ defaults:
539
+ run:
540
+ shell: bash
541
+ steps:
542
+ - name: Checkout
543
+ uses: actions/checkout@v5
544
+ with:
545
+ lfs: false
546
+
547
+ - name: Set up Python 3.12
548
+ uses: actions/setup-python@v6
549
+ with:
550
+ python-version: "3.12"
551
+ cache: pip
552
+ cache-dependency-path: pyproject.toml
553
+
554
+ - name: Download wheel artifact
555
+ uses: actions/download-artifact@v7
556
+ with:
557
+ name: package-smoke-wheel
558
+ path: dist
559
+
560
+ - name: Install wheel in clean venv
561
+ run: |
562
+ python -m venv .venv-smoke
563
+ if [[ "$RUNNER_OS" == "Windows" ]]; then
564
+ . .venv-smoke/Scripts/activate
565
+ else
566
+ . .venv-smoke/bin/activate
567
+ fi
568
+ python -m pip install --upgrade pip
569
+ python -m pip install dist/*.whl
570
+ python -m pip check
571
+ python - <<'PY'
572
+ import tomllib
573
+ from importlib.metadata import entry_points, version
574
+
575
+ import ctx
576
+
577
+ with open("pyproject.toml", "rb") as fh:
578
+ expected_scripts = set(tomllib.load(fh)["project"]["scripts"])
579
+
580
+ dist_version = version("claude-ctx")
581
+ if ctx.__version__ != dist_version:
582
+ raise SystemExit(
583
+ f"ctx.__version__={ctx.__version__!r} != metadata {dist_version!r}"
584
+ )
585
+
586
+ script_eps = {
587
+ ep.name: ep
588
+ for ep in entry_points(group="console_scripts")
589
+ if ep.name == "ctx" or ep.name.startswith("ctx-")
590
+ }
591
+ missing = sorted(expected_scripts - set(script_eps))
592
+ extra = sorted(set(script_eps) - expected_scripts)
593
+ if missing or extra:
594
+ raise SystemExit(
595
+ "wheel console-script surface mismatch\n"
596
+ f"missing: {missing}\n"
597
+ f"extra: {extra}"
598
+ )
599
+ failures = []
600
+ for ep in script_eps.values():
601
+ try:
602
+ ep.load()
603
+ except Exception as exc:
604
+ failures.append(f"{ep.name}: {exc!r}")
605
+ if failures:
606
+ raise SystemExit("console script load failures:\n" + "\n".join(failures))
607
+
608
+ unsafe_help = {"ctx-mcp-server"}
609
+ safe_help = sorted(expected_scripts - unsafe_help)
610
+ with open(
611
+ "ctx-console-help.txt", "w", encoding="utf-8", newline="\n"
612
+ ) as fh:
613
+ fh.write("\n".join(safe_help) + "\n")
614
+ print(
615
+ f"loaded {len(script_eps)} ctx console scripts from wheel "
616
+ f"{dist_version}; help-smoke={len(safe_help)}"
617
+ )
618
+ PY
619
+ while IFS= read -r cmd; do
620
+ cmd="${cmd%$'\r'}"
621
+ [[ -z "$cmd" ]] && continue
622
+ echo "help smoke: $cmd"
623
+ "$cmd" --help >/dev/null
624
+ done < ctx-console-help.txt
625
+
626
+ clean-host-contract:
627
+ name: "Clean host contract"
628
+ needs: classify
629
+ if: ${{ github.event_name != 'pull_request' || (needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true') }}
630
+ runs-on: ubuntu-latest
631
+ timeout-minutes: 25
632
+ steps:
633
+ - name: Checkout
634
+ uses: actions/checkout@v5
635
+ with:
636
+ lfs: false
637
+
638
+ - name: Set up Python 3.12
639
+ uses: actions/setup-python@v6
640
+ with:
641
+ python-version: "3.12"
642
+ cache: pip
643
+ cache-dependency-path: pyproject.toml
644
+
645
+ - name: Upgrade pip
646
+ run: python -m pip install --upgrade pip
647
+
648
+ - name: Run clean-host contract
649
+ run: python scripts/clean_host_contract.py --fast
650
+
651
+ no-test-no-merge:
652
+ name: "Contract changes must touch tests"
653
+ needs: classify
654
+ runs-on: ubuntu-latest
655
+ if: ${{ github.event_name == 'pull_request' && needs.classify.outputs.docs_only != 'true' && needs.classify.outputs.graph_only != 'true' }}
656
+ steps:
657
+ - name: Checkout with full history
658
+ uses: actions/checkout@v5
659
+ with:
660
+ fetch-depth: 0
661
+ lfs: false
662
+
663
+ - name: Enforce test-coverage-per-PR policy
664
+ # Policy: any product or CI/package contract change
665
+ # must be accompanied by at least one test file change in the
666
+ # same PR. Exemptions:
667
+ # - Pure docs / comment changes (matched by a trivial heuristic)
668
+ # - Config JSON (src/config.json) — schema changes get tests
669
+ # for the accessor, not the JSON itself.
670
+ # - Changes ONLY inside __pycache__, .pyc files, etc.
671
+ run: |
672
+ set -euo pipefail
673
+ BASE="${{ github.event.pull_request.base.sha }}"
674
+ HEAD="${{ github.event.pull_request.head.sha }}"
675
+ LABELS='${{ toJson(github.event.pull_request.labels.*.name) }}'
676
+ python scripts/ci_no_test_policy.py \
677
+ --base "$BASE" \
678
+ --head "$HEAD" \
679
+ --labels-json "$LABELS"
680
+
681
+ ci-required:
682
+ name: "CI required"
683
+ runs-on: ubuntu-latest
684
+ needs:
685
+ - classify
686
+ - static
687
+ - unit-linux
688
+ - similarity-integration
689
+ - test
690
+ - contract-compat
691
+ - e2e-canary
692
+ - docs-check
693
+ - graph-check
694
+ - browser-security
695
+ - package-smoke
696
+ - package-build
697
+ - clean-host-contract
698
+ - no-test-no-merge
699
+ if: ${{ always() }}
700
+ steps:
701
+ - name: Checkout
702
+ uses: actions/checkout@v5
703
+ with:
704
+ lfs: false
705
+
706
+ - name: Check required job results
707
+ env:
708
+ EVENT_NAME: ${{ github.event_name }}
709
+ NEEDS_JSON: ${{ toJson(needs) }}
710
+ run: python scripts/ci_required.py
.github/workflows/xdist-experiment.yml CHANGED
@@ -1,90 +1,90 @@
1
- name: Xdist experiment
2
-
3
- on:
4
- workflow_dispatch:
5
- pull_request:
6
- branches: [main]
7
- paths:
8
- - ".github/workflows/xdist-experiment.yml"
9
-
10
- env:
11
- FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
12
-
13
- concurrency:
14
- group: xdist-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
15
- cancel-in-progress: true
16
-
17
- permissions:
18
- contents: read
19
-
20
- jobs:
21
- xdist:
22
- name: xdist (${{ matrix.os }} / py${{ matrix.python-version }})
23
- runs-on: ${{ matrix.os }}
24
- strategy:
25
- fail-fast: false
26
- matrix:
27
- os: [ubuntu-latest, windows-latest, macos-latest]
28
- python-version: ["3.12"]
29
- defaults:
30
- run:
31
- shell: bash
32
- steps:
33
- - name: Checkout
34
- uses: actions/checkout@v5
35
- with:
36
- lfs: false
37
-
38
- - name: Set up Python ${{ matrix.python-version }}
39
- uses: actions/setup-python@v6
40
- with:
41
- python-version: ${{ matrix.python-version }}
42
- cache: pip
43
- cache-dependency-path: pyproject.toml
44
-
45
- - name: Install experiment dependencies
46
- run: |
47
- python -m pip install --upgrade pip
48
- python -m pip install ".[dev]" pytest-xdist
49
-
50
- - name: Run xdist experiment
51
- run: |
52
- set +e
53
- start="$(python - <<'PY'
54
- import time
55
- print(time.monotonic())
56
- PY
57
- )"
58
- python -m pytest -q -m "not browser" --no-cov \
59
- -n 2 \
60
- --dist=loadfile \
61
- --max-worker-restart=0 \
62
- --durations=25
63
- status="$?"
64
- end="$(python - <<'PY'
65
- import time
66
- print(time.monotonic())
67
- PY
68
- )"
69
- elapsed="$(python - "$start" "$end" <<'PY'
70
- import sys
71
- start = float(sys.argv[1])
72
- end = float(sys.argv[2])
73
- print(f"{end - start:.1f}")
74
- PY
75
- )"
76
-
77
- {
78
- echo "## pytest-xdist experiment"
79
- echo ""
80
- echo "- OS: $RUNNER_OS"
81
- echo "- Python: ${{ matrix.python-version }}"
82
- echo "- Command: \`python -m pytest -q -m \"not browser\" --no-cov -n 2 --dist=loadfile --max-worker-restart=0 --durations=25\`"
83
- echo "- Exit code: $status"
84
- echo "- Elapsed seconds: $elapsed"
85
- } >> "$GITHUB_STEP_SUMMARY"
86
-
87
- if [ "$status" -ne 0 ]; then
88
- echo "::warning::xdist experiment failed on $RUNNER_OS with exit code $status"
89
- fi
90
- exit "$status"
 
1
+ name: Xdist experiment
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ pull_request:
6
+ branches: [main]
7
+ paths:
8
+ - ".github/workflows/xdist-experiment.yml"
9
+
10
+ env:
11
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
12
+
13
+ concurrency:
14
+ group: xdist-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
15
+ cancel-in-progress: true
16
+
17
+ permissions:
18
+ contents: read
19
+
20
+ jobs:
21
+ xdist:
22
+ name: xdist (${{ matrix.os }} / py${{ matrix.python-version }})
23
+ runs-on: ${{ matrix.os }}
24
+ strategy:
25
+ fail-fast: false
26
+ matrix:
27
+ os: [ubuntu-latest, windows-latest, macos-latest]
28
+ python-version: ["3.12"]
29
+ defaults:
30
+ run:
31
+ shell: bash
32
+ steps:
33
+ - name: Checkout
34
+ uses: actions/checkout@v5
35
+ with:
36
+ lfs: false
37
+
38
+ - name: Set up Python ${{ matrix.python-version }}
39
+ uses: actions/setup-python@v6
40
+ with:
41
+ python-version: ${{ matrix.python-version }}
42
+ cache: pip
43
+ cache-dependency-path: pyproject.toml
44
+
45
+ - name: Install experiment dependencies
46
+ run: |
47
+ python -m pip install --upgrade pip
48
+ python -m pip install ".[dev]" pytest-xdist
49
+
50
+ - name: Run xdist experiment
51
+ run: |
52
+ set +e
53
+ start="$(python - <<'PY'
54
+ import time
55
+ print(time.monotonic())
56
+ PY
57
+ )"
58
+ python -m pytest -q -m "not browser" --no-cov \
59
+ -n 2 \
60
+ --dist=loadfile \
61
+ --max-worker-restart=0 \
62
+ --durations=25
63
+ status="$?"
64
+ end="$(python - <<'PY'
65
+ import time
66
+ print(time.monotonic())
67
+ PY
68
+ )"
69
+ elapsed="$(python - "$start" "$end" <<'PY'
70
+ import sys
71
+ start = float(sys.argv[1])
72
+ end = float(sys.argv[2])
73
+ print(f"{end - start:.1f}")
74
+ PY
75
+ )"
76
+
77
+ {
78
+ echo "## pytest-xdist experiment"
79
+ echo ""
80
+ echo "- OS: $RUNNER_OS"
81
+ echo "- Python: ${{ matrix.python-version }}"
82
+ echo "- Command: \`python -m pytest -q -m \"not browser\" --no-cov -n 2 --dist=loadfile --max-worker-restart=0 --durations=25\`"
83
+ echo "- Exit code: $status"
84
+ echo "- Elapsed seconds: $elapsed"
85
+ } >> "$GITHUB_STEP_SUMMARY"
86
+
87
+ if [ "$status" -ne 0 ]; then
88
+ echo "::warning::xdist experiment failed on $RUNNER_OS with exit code $status"
89
+ fi
90
+ exit "$status"
docs/SKILL.md CHANGED
@@ -1,303 +1,303 @@
1
- ---
2
- name: skill-router
3
- description: "Repo-aware recommendation manager for ctx. Scans the active repository, identifies stack and workflow signals, recommends a capped set of skills, agents, and MCP servers, and unloads helpers that no longer match the current work after user confirmation. Harnesses are recommended by the custom-model onboarding flow and then attach to the same recommendation layer."
4
- ---
5
-
6
- # Skill Router
7
-
8
- Scan a repo. Know what the current work needs. Recommend only that. Keep the
9
- wiki and graph as the durable catalog behind the decision.
10
-
11
- ## Scope
12
-
13
- The router manages runtime recommendations for:
14
-
15
- - skills
16
- - agents
17
- - MCP servers
18
-
19
- Harnesses are separate catalog entities. They are recommended when a user wants
20
- to run ctx with a non-Claude-Code host, local model, or API model. Once attached,
21
- the harness calls the same skills/agents/MCP recommendation engine.
22
-
23
- ## Problem
24
-
25
- Every loaded helper costs tokens, attention, and operational surface area. Most
26
- sessions need a small top-scored bundle from the shipped graph, not every entity
27
- ctx knows about. Loading too much:
28
-
29
- - wastes context on irrelevant instructions,
30
- - causes misfires when a helper matches the wrong task,
31
- - slows the agent loop, and
32
- - creates conflicting instructions.
33
-
34
- ## Architecture
35
-
36
- ```text
37
- ctx/
38
- |-- src/scan_repo.py # Repo scanner -> stack profile
39
- |-- src/ctx/core/resolve/resolve_skills.py # Profile -> load/unload manifest
40
- |-- src/ctx/core/resolve/recommendations.py # Shared scoring/ranking engine
41
- |-- src/ctx/adapters/ # Claude Code hooks + generic tools
42
- |-- src/harness_install.py # Custom-model harness install flow
43
- `-- graph/wiki-graph-runtime.tar.gz # Shipped graph/wiki runtime
44
- ```
45
-
46
- The router has three halves:
47
-
48
- 1. **Scanner** - analyzes a repo and produces stack/task evidence.
49
- 2. **Resolver** - scores graph/wiki entities and emits a capped manifest.
50
- 3. **Wiki/graph** - persistent catalog of entities, usage, quality, and links.
51
-
52
- ## Startup Flow
53
-
54
- 1. Read the shipped graph/wiki metadata and local user overrides.
55
- 2. Run `ctx-scan-repo --repo . --recommend` for the active repo.
56
- 3. Resolve a load/unload manifest with the shared recommendation engine.
57
- 4. Present changes with reasons and require confirmation unless the user enabled
58
- automatic mode.
59
- 5. Record usage/quality changes after the user accepts or rejects suggestions.
60
-
61
- ## Scanner
62
-
63
- The scanner reads repo structure and files to produce a stack profile. Detection
64
- is evidence-based: every claim should map to a file, dependency, config value, or
65
- import pattern.
66
-
67
- ### Detection Categories
68
-
69
- - **Languages** - file extensions, shebangs, lock files.
70
- - **Frameworks and libraries** - package manifests, imports, config files.
71
- - **Infrastructure and DevOps** - Docker, CI/CD, IaC, cloud, Kubernetes.
72
- - **Data and storage** - databases, migrations, queues, pipelines.
73
- - **Documentation and content** - MkDocs, Docusaurus, Sphinx, API specs.
74
- - **Testing and quality** - pytest, Jest, Playwright, Ruff, mypy, TypeScript.
75
- - **AI and agent tooling** - MCP configs, LangGraph, CrewAI, prompt dirs, model
76
- config names.
77
- - **Build and package** - package managers, build tools, monorepos.
78
-
79
- ### Scanning Rules
80
-
81
- 1. Start with filenames and config files. Read source only when needed to
82
- disambiguate.
83
- 2. Do not include speculative signals below the configured confidence floor.
84
- 3. Skip generated/vendor directories such as `.git`, `node_modules`,
85
- `__pycache__`, `venv`, and `.venv`.
86
- 4. Keep initial scans bounded for large repos.
87
- 5. Redact secret values; only record secret/key names as evidence.
88
-
89
- ## Resolver
90
-
91
- The resolver produces a manifest containing the exact helper set to load or
92
- unload.
93
-
94
- ```json
95
- {
96
- "generated_at": "ISO-8601",
97
- "repo_path": "/absolute/path",
98
- "profile_hash": "sha256 of stack profile",
99
- "load": [
100
- {
101
- "name": "fastapi",
102
- "type": "skill",
103
- "reason": "FastAPI detected in pyproject.toml dependencies",
104
- "score": 0.94
105
- }
106
- ],
107
- "unload": [
108
- {
109
- "name": "react",
110
- "type": "skill",
111
- "reason": "No active frontend signal in the current repo window"
112
- }
113
- ],
114
- "suggestions": [
115
- {
116
- "name": "github",
117
- "type": "mcp",
118
- "reason": ".github/workflows exists and the repo uses GitHub Actions",
119
- "install_command": "ctx-mcp-add ..."
120
- }
121
- ],
122
- "warnings": []
123
- }
124
- ```
125
-
126
- ### Ranking Signals
127
-
128
- Candidates can be scored by:
129
-
130
- - tag/category/subcategory match
131
- - semantic similarity edge weight
132
- - direct wiki links
133
- - source overlap
134
- - type affinity
135
- - usage score
136
- - quality/security score
137
- - user overrides (`always_load`, `never_load`)
138
- - configured caps and minimum score gates
139
-
140
- Recommendations are capped. ctx should not recommend at all costs; below-threshold
141
- candidates should be withheld and the gap should be explained.
142
-
143
- ## Wiki And Graph Contract
144
-
145
- The wiki follows a Karpathy-style durable memory pattern: schema, purpose, index,
146
- log, lint, review items, and entity pages that are machine-readable.
147
-
148
- ```text
149
- llm-wiki/
150
- |-- SCHEMA.md
151
- |-- index.md
152
- |-- log.md
153
- |-- raw/
154
- | |-- scans/
155
- | `-- external-catalogs/
156
- |-- entities/
157
- | |-- skills/
158
- | |-- agents/
159
- | |-- mcp-servers/
160
- | `-- harnesses/
161
- |-- concepts/
162
- |-- comparisons/
163
- `-- queries/
164
- ```
165
-
166
- Entity pages use YAML frontmatter with at least:
167
-
168
- ```yaml
169
- title: Entity Name
170
- type: skill | agent | mcp-server | harness | external-catalog
171
- status: installed | available | deprecated | broken
172
- tags: []
173
- source: local | shipped | github | curated
174
- source_url: ""
175
- path: ""
176
- quality_score: null
177
- usage_score: 0
178
- last_used: null
179
- always_load: false
180
- never_load: false
181
- ```
182
-
183
- ## Entity Sources
184
-
185
- Entity sources include shipped skill/MCP/harness sources, GitHub
186
- entity repositories, and local user assets. The public reference page is
187
- [`marketplace-registry.md`](marketplace-registry.md), kept under that filename
188
- for backwards-compatible links.
189
-
190
- Source rules:
191
-
192
- 1. Search the shipped graph/wiki first.
193
- 2. Use additional sources only when the local graph is missing or stale.
194
- 3. Deduplicate before adding.
195
- 4. If an entity exists, emit an update review instead of replacing it.
196
- 5. Run security checks before promotion.
197
- 6. Rebuild and validate graph/wiki artifacts before shipping.
198
-
199
- ## Micro-Skill Gate
200
-
201
- Every added or updated skill must pass the configured line-count gate before it
202
- is packed into the shipped wiki. The default threshold is 180 lines, read from
203
- ctx config. Skills above the threshold are converted into a short orchestrator
204
- plus staged reference files. Local `.original` backups may be preserved for
205
- traceability, but packaged runtime archives must omit those backups.
206
-
207
- ## Core Operations
208
-
209
- ### Full Scan
210
-
211
- Triggers: repo open, repo switch, `ctx-scan-repo --repo . --recommend`, or explicit user
212
- request.
213
-
214
- 1. Read wiki orientation and local overrides.
215
- 2. Scan the target repo.
216
- 3. Save the scan result.
217
- 4. Resolve load/unload recommendations.
218
- 5. Present reasons, scores, and install/update commands.
219
- 6. Apply only after confirmation unless configured otherwise.
220
- 7. Record usage and decisions.
221
-
222
- ### Incremental Scan
223
-
224
- Triggers: changed config files, new dependencies, new MCP config, new tests, new
225
- infrastructure files, or user task change.
226
-
227
- If a helper is no longer useful, ctx should suggest unloading it and ask for
228
- confirmation. If the user asks to skip unload prompts, ctx should respect that
229
- preference.
230
-
231
- ### Manual Override
232
-
233
- - "Always load the docker skill" -> set `always_load: true`.
234
- - "Never load the react skill" -> set `never_load: true`.
235
- - "Load the terraform skill for this session" -> temporary load.
236
- - "What is loaded?" -> show current manifest with reasons.
237
-
238
- ### Discovery
239
-
240
- When the user asks what exists for a task:
241
-
242
- 1. Search graph/wiki entity pages by tags and text.
243
- 2. Use `find-skills` and configured sources for remote freshness when needed.
244
- 3. Show status, score, source, and risk notes.
245
- 4. Suggest install/update commands, not silent installs.
246
- 5. Log the query.
247
-
248
- ## Maintenance Checks
249
-
250
- - **Stale installed helpers** - used rarely or not used recently.
251
- - **Ghost helpers** - installed status but missing local path.
252
- - **Orphan local helpers** - present locally but missing entity page.
253
- - **Skill index freshness** - shipped skill snapshot older than policy.
254
- - **Conflicts** - overlapping helpers both marked `always_load`.
255
- - **Usage cold spots** - low usage/quality score candidates for unload review.
256
- - **Wiki lint** - broken links, missing frontmatter, index drift.
257
-
258
- ## Reporting
259
-
260
- After a scan, report only actionable details:
261
-
262
- ```text
263
- Skill Router Report - repo-name
264
- Scanned: YYYY-MM-DD HH:MM
265
-
266
- Loaded:
267
- 1. fastapi skill - score 0.94 - pyproject.toml dependency
268
- 2. github MCP - score 0.91 - GitHub Actions workflows detected
269
-
270
- Unload candidates:
271
- 1. react skill - no active frontend signal
272
-
273
- Suggestions:
274
- 1. openapi-generator skill - OpenAPI spec found
275
-
276
- Warnings:
277
- None
278
- ```
279
-
280
- ## Configuration
281
-
282
- Router behavior is controlled by ctx config and user overrides. Important knobs:
283
-
284
- ```yaml
285
- recommendations:
286
- max_total: 5
287
- min_score: 0.85
288
- micro_skills:
289
- max_lines: 180
290
- router:
291
- auto_scan: true
292
- auto_apply: false
293
- ask_before_unload: true
294
- ```
295
-
296
- ## Pitfalls
297
-
298
- - Never load all helpers just in case.
299
- - Never replace an existing entity without an update review.
300
- - Never execute external repo scripts while cataloging.
301
- - Never treat conversation history as the source of workflow state.
302
- - Never ship graph/wiki artifacts before validation passes.
303
- - Respect `never_load` and user rejection history.
 
1
+ ---
2
+ name: skill-router
3
+ description: "Repo-aware recommendation manager for ctx. Scans the active repository, identifies stack and workflow signals, recommends a capped set of skills, agents, and MCP servers, and unloads helpers that no longer match the current work after user confirmation. Harnesses are recommended by the custom-model onboarding flow and then attach to the same recommendation layer."
4
+ ---
5
+
6
+ # Skill Router
7
+
8
+ Scan a repo. Know what the current work needs. Recommend only that. Keep the
9
+ wiki and graph as the durable catalog behind the decision.
10
+
11
+ ## Scope
12
+
13
+ The router manages runtime recommendations for:
14
+
15
+ - skills
16
+ - agents
17
+ - MCP servers
18
+
19
+ Harnesses are separate catalog entities. They are recommended when a user wants
20
+ to run ctx with a non-Claude-Code host, local model, or API model. Once attached,
21
+ the harness calls the same skills/agents/MCP recommendation engine.
22
+
23
+ ## Problem
24
+
25
+ Every loaded helper costs tokens, attention, and operational surface area. Most
26
+ sessions need a small top-scored bundle from the shipped graph, not every entity
27
+ ctx knows about. Loading too much:
28
+
29
+ - wastes context on irrelevant instructions,
30
+ - causes misfires when a helper matches the wrong task,
31
+ - slows the agent loop, and
32
+ - creates conflicting instructions.
33
+
34
+ ## Architecture
35
+
36
+ ```text
37
+ ctx/
38
+ |-- src/scan_repo.py # Repo scanner -> stack profile
39
+ |-- src/ctx/core/resolve/resolve_skills.py # Profile -> load/unload manifest
40
+ |-- src/ctx/core/resolve/recommendations.py # Shared scoring/ranking engine
41
+ |-- src/ctx/adapters/ # Claude Code hooks + generic tools
42
+ |-- src/harness_install.py # Custom-model harness install flow
43
+ `-- graph/wiki-graph-runtime.tar.gz # Shipped graph/wiki runtime
44
+ ```
45
+
46
+ The router has three halves:
47
+
48
+ 1. **Scanner** - analyzes a repo and produces stack/task evidence.
49
+ 2. **Resolver** - scores graph/wiki entities and emits a capped manifest.
50
+ 3. **Wiki/graph** - persistent catalog of entities, usage, quality, and links.
51
+
52
+ ## Startup Flow
53
+
54
+ 1. Read the shipped graph/wiki metadata and local user overrides.
55
+ 2. Run `ctx-scan-repo --repo . --recommend` for the active repo.
56
+ 3. Resolve a load/unload manifest with the shared recommendation engine.
57
+ 4. Present changes with reasons and require confirmation unless the user enabled
58
+ automatic mode.
59
+ 5. Record usage/quality changes after the user accepts or rejects suggestions.
60
+
61
+ ## Scanner
62
+
63
+ The scanner reads repo structure and files to produce a stack profile. Detection
64
+ is evidence-based: every claim should map to a file, dependency, config value, or
65
+ import pattern.
66
+
67
+ ### Detection Categories
68
+
69
+ - **Languages** - file extensions, shebangs, lock files.
70
+ - **Frameworks and libraries** - package manifests, imports, config files.
71
+ - **Infrastructure and DevOps** - Docker, CI/CD, IaC, cloud, Kubernetes.
72
+ - **Data and storage** - databases, migrations, queues, pipelines.
73
+ - **Documentation and content** - MkDocs, Docusaurus, Sphinx, API specs.
74
+ - **Testing and quality** - pytest, Jest, Playwright, Ruff, mypy, TypeScript.
75
+ - **AI and agent tooling** - MCP configs, LangGraph, CrewAI, prompt dirs, model
76
+ config names.
77
+ - **Build and package** - package managers, build tools, monorepos.
78
+
79
+ ### Scanning Rules
80
+
81
+ 1. Start with filenames and config files. Read source only when needed to
82
+ disambiguate.
83
+ 2. Do not include speculative signals below the configured confidence floor.
84
+ 3. Skip generated/vendor directories such as `.git`, `node_modules`,
85
+ `__pycache__`, `venv`, and `.venv`.
86
+ 4. Keep initial scans bounded for large repos.
87
+ 5. Redact secret values; only record secret/key names as evidence.
88
+
89
+ ## Resolver
90
+
91
+ The resolver produces a manifest containing the exact helper set to load or
92
+ unload.
93
+
94
+ ```json
95
+ {
96
+ "generated_at": "ISO-8601",
97
+ "repo_path": "/absolute/path",
98
+ "profile_hash": "sha256 of stack profile",
99
+ "load": [
100
+ {
101
+ "name": "fastapi",
102
+ "type": "skill",
103
+ "reason": "FastAPI detected in pyproject.toml dependencies",
104
+ "score": 0.94
105
+ }
106
+ ],
107
+ "unload": [
108
+ {
109
+ "name": "react",
110
+ "type": "skill",
111
+ "reason": "No active frontend signal in the current repo window"
112
+ }
113
+ ],
114
+ "suggestions": [
115
+ {
116
+ "name": "github",
117
+ "type": "mcp",
118
+ "reason": ".github/workflows exists and the repo uses GitHub Actions",
119
+ "install_command": "ctx-mcp-add ..."
120
+ }
121
+ ],
122
+ "warnings": []
123
+ }
124
+ ```
125
+
126
+ ### Ranking Signals
127
+
128
+ Candidates can be scored by:
129
+
130
+ - tag/category/subcategory match
131
+ - semantic similarity edge weight
132
+ - direct wiki links
133
+ - source overlap
134
+ - type affinity
135
+ - usage score
136
+ - quality/security score
137
+ - user overrides (`always_load`, `never_load`)
138
+ - configured caps and minimum score gates
139
+
140
+ Recommendations are capped. ctx should not recommend at all costs; below-threshold
141
+ candidates should be withheld and the gap should be explained.
142
+
143
+ ## Wiki And Graph Contract
144
+
145
+ The wiki follows a Karpathy-style durable memory pattern: schema, purpose, index,
146
+ log, lint, review items, and entity pages that are machine-readable.
147
+
148
+ ```text
149
+ llm-wiki/
150
+ |-- SCHEMA.md
151
+ |-- index.md
152
+ |-- log.md
153
+ |-- raw/
154
+ | |-- scans/
155
+ | `-- external-catalogs/
156
+ |-- entities/
157
+ | |-- skills/
158
+ | |-- agents/
159
+ | |-- mcp-servers/
160
+ | `-- harnesses/
161
+ |-- concepts/
162
+ |-- comparisons/
163
+ `-- queries/
164
+ ```
165
+
166
+ Entity pages use YAML frontmatter with at least:
167
+
168
+ ```yaml
169
+ title: Entity Name
170
+ type: skill | agent | mcp-server | harness | external-catalog
171
+ status: installed | available | deprecated | broken
172
+ tags: []
173
+ source: local | shipped | github | curated
174
+ source_url: ""
175
+ path: ""
176
+ quality_score: null
177
+ usage_score: 0
178
+ last_used: null
179
+ always_load: false
180
+ never_load: false
181
+ ```
182
+
183
+ ## Entity Sources
184
+
185
+ Entity sources include shipped skill/MCP/harness sources, GitHub
186
+ entity repositories, and local user assets. The public reference page is
187
+ [`marketplace-registry.md`](marketplace-registry.md), kept under that filename
188
+ for backwards-compatible links.
189
+
190
+ Source rules:
191
+
192
+ 1. Search the shipped graph/wiki first.
193
+ 2. Use additional sources only when the local graph is missing or stale.
194
+ 3. Deduplicate before adding.
195
+ 4. If an entity exists, emit an update review instead of replacing it.
196
+ 5. Run security checks before promotion.
197
+ 6. Rebuild and validate graph/wiki artifacts before shipping.
198
+
199
+ ## Micro-Skill Gate
200
+
201
+ Every added or updated skill must pass the configured line-count gate before it
202
+ is packed into the shipped wiki. The default threshold is 180 lines, read from
203
+ ctx config. Skills above the threshold are converted into a short orchestrator
204
+ plus staged reference files. Local `.original` backups may be preserved for
205
+ traceability, but packaged runtime archives must omit those backups.
206
+
207
+ ## Core Operations
208
+
209
+ ### Full Scan
210
+
211
+ Triggers: repo open, repo switch, `ctx-scan-repo --repo . --recommend`, or explicit user
212
+ request.
213
+
214
+ 1. Read wiki orientation and local overrides.
215
+ 2. Scan the target repo.
216
+ 3. Save the scan result.
217
+ 4. Resolve load/unload recommendations.
218
+ 5. Present reasons, scores, and install/update commands.
219
+ 6. Apply only after confirmation unless configured otherwise.
220
+ 7. Record usage and decisions.
221
+
222
+ ### Incremental Scan
223
+
224
+ Triggers: changed config files, new dependencies, new MCP config, new tests, new
225
+ infrastructure files, or user task change.
226
+
227
+ If a helper is no longer useful, ctx should suggest unloading it and ask for
228
+ confirmation. If the user asks to skip unload prompts, ctx should respect that
229
+ preference.
230
+
231
+ ### Manual Override
232
+
233
+ - "Always load the docker skill" -> set `always_load: true`.
234
+ - "Never load the react skill" -> set `never_load: true`.
235
+ - "Load the terraform skill for this session" -> temporary load.
236
+ - "What is loaded?" -> show current manifest with reasons.
237
+
238
+ ### Discovery
239
+
240
+ When the user asks what exists for a task:
241
+
242
+ 1. Search graph/wiki entity pages by tags and text.
243
+ 2. Use `find-skills` and configured sources for remote freshness when needed.
244
+ 3. Show status, score, source, and risk notes.
245
+ 4. Suggest install/update commands, not silent installs.
246
+ 5. Log the query.
247
+
248
+ ## Maintenance Checks
249
+
250
+ - **Stale installed helpers** - used rarely or not used recently.
251
+ - **Ghost helpers** - installed status but missing local path.
252
+ - **Orphan local helpers** - present locally but missing entity page.
253
+ - **Skill index freshness** - shipped skill snapshot older than policy.
254
+ - **Conflicts** - overlapping helpers both marked `always_load`.
255
+ - **Usage cold spots** - low usage/quality score candidates for unload review.
256
+ - **Wiki lint** - broken links, missing frontmatter, index drift.
257
+
258
+ ## Reporting
259
+
260
+ After a scan, report only actionable details:
261
+
262
+ ```text
263
+ Skill Router Report - repo-name
264
+ Scanned: YYYY-MM-DD HH:MM
265
+
266
+ Loaded:
267
+ 1. fastapi skill - score 0.94 - pyproject.toml dependency
268
+ 2. github MCP - score 0.91 - GitHub Actions workflows detected
269
+
270
+ Unload candidates:
271
+ 1. react skill - no active frontend signal
272
+
273
+ Suggestions:
274
+ 1. openapi-generator skill - OpenAPI spec found
275
+
276
+ Warnings:
277
+ None
278
+ ```
279
+
280
+ ## Configuration
281
+
282
+ Router behavior is controlled by ctx config and user overrides. Important knobs:
283
+
284
+ ```yaml
285
+ recommendations:
286
+ max_total: 5
287
+ min_score: 0.85
288
+ micro_skills:
289
+ max_lines: 180
290
+ router:
291
+ auto_scan: true
292
+ auto_apply: false
293
+ ask_before_unload: true
294
+ ```
295
+
296
+ ## Pitfalls
297
+
298
+ - Never load all helpers just in case.
299
+ - Never replace an existing entity without an update review.
300
+ - Never execute external repo scripts while cataloging.
301
+ - Never treat conversation history as the source of workflow state.
302
+ - Never ship graph/wiki artifacts before validation passes.
303
+ - Respect `never_load` and user rejection history.
docs/assets/javascripts/repo-stats-refresh.js CHANGED
@@ -1,120 +1,120 @@
1
- (function () {
2
- "use strict";
3
-
4
- var REPO_URL = "https://github.com/stevesolun/ctx";
5
- var REPO_API_URL = "https://api.github.com/repos/stevesolun/ctx";
6
- var MATERIAL_SOURCE_CACHE_KEY = "__source";
7
-
8
- function isCtxSource(anchor) {
9
- var href = anchor.getAttribute("href") || "";
10
- return href.replace(/\/$/, "") === REPO_URL;
11
- }
12
-
13
- function formatCount(value) {
14
- return new Intl.NumberFormat("en", {
15
- maximumFractionDigits: 1,
16
- notation: value >= 10000 ? "compact" : "standard",
17
- })
18
- .format(value)
19
- .toLowerCase();
20
- }
21
-
22
- function createFact(kind, value) {
23
- var item = document.createElement("li");
24
- item.className = "md-source__fact md-source__fact--" + kind;
25
- item.textContent = formatCount(value);
26
- return item;
27
- }
28
-
29
- function clearRenderedFacts(source) {
30
- source.querySelectorAll(".md-source__facts").forEach(function (facts) {
31
- facts.remove();
32
- });
33
-
34
- var repository = source.querySelector(".md-source__repository");
35
- if (repository) {
36
- repository.classList.remove("md-source__repository--active");
37
- }
38
- }
39
-
40
- function renderStats(stats) {
41
- document.querySelectorAll(".md-source").forEach(function (source) {
42
- if (!(source instanceof HTMLAnchorElement) || !isCtxSource(source)) {
43
- return;
44
- }
45
-
46
- clearRenderedFacts(source);
47
-
48
- var repository = source.querySelector(".md-source__repository");
49
- if (!repository) {
50
- return;
51
- }
52
-
53
- var facts = document.createElement("ul");
54
- facts.className = "md-source__facts";
55
- facts.appendChild(createFact("stars", stats.stars));
56
- facts.appendChild(createFact("forks", stats.forks));
57
-
58
- repository.appendChild(facts);
59
- repository.classList.add("md-source__repository--active");
60
- });
61
- }
62
-
63
- function clearStaleStats() {
64
- document.querySelectorAll(".md-source").forEach(function (source) {
65
- if (source instanceof HTMLAnchorElement && isCtxSource(source)) {
66
- clearRenderedFacts(source);
67
- }
68
- });
69
- }
70
-
71
- function updateMaterialCache(stats) {
72
- try {
73
- sessionStorage.setItem(
74
- MATERIAL_SOURCE_CACHE_KEY,
75
- JSON.stringify({ stars: stats.stars, forks: stats.forks })
76
- );
77
- } catch (error) {
78
- /* Browser storage may be disabled. The visible header is still updated. */
79
- }
80
- }
81
-
82
- async function fetchStats() {
83
- var response = await fetch(REPO_API_URL, {
84
- cache: "no-store",
85
- headers: { Accept: "application/vnd.github+json" },
86
- });
87
-
88
- if (!response.ok) {
89
- throw new Error("GitHub repository stats request failed");
90
- }
91
-
92
- var data = await response.json();
93
- return {
94
- forks: Number(data.forks_count || 0),
95
- stars: Number(data.stargazers_count || 0),
96
- };
97
- }
98
-
99
- async function refreshRepoStats() {
100
- clearStaleStats();
101
-
102
- try {
103
- var stats = await fetchStats();
104
- updateMaterialCache(stats);
105
- renderStats(stats);
106
- } catch (error) {
107
- clearStaleStats();
108
- }
109
- }
110
-
111
- if (document.readyState === "loading") {
112
- document.addEventListener("DOMContentLoaded", refreshRepoStats, { once: true });
113
- } else {
114
- refreshRepoStats();
115
- }
116
-
117
- if (window.document$ && typeof window.document$.subscribe === "function") {
118
- window.document$.subscribe(refreshRepoStats);
119
- }
120
- })();
 
1
+ (function () {
2
+ "use strict";
3
+
4
+ var REPO_URL = "https://github.com/stevesolun/ctx";
5
+ var REPO_API_URL = "https://api.github.com/repos/stevesolun/ctx";
6
+ var MATERIAL_SOURCE_CACHE_KEY = "__source";
7
+
8
+ function isCtxSource(anchor) {
9
+ var href = anchor.getAttribute("href") || "";
10
+ return href.replace(/\/$/, "") === REPO_URL;
11
+ }
12
+
13
+ function formatCount(value) {
14
+ return new Intl.NumberFormat("en", {
15
+ maximumFractionDigits: 1,
16
+ notation: value >= 10000 ? "compact" : "standard",
17
+ })
18
+ .format(value)
19
+ .toLowerCase();
20
+ }
21
+
22
+ function createFact(kind, value) {
23
+ var item = document.createElement("li");
24
+ item.className = "md-source__fact md-source__fact--" + kind;
25
+ item.textContent = formatCount(value);
26
+ return item;
27
+ }
28
+
29
+ function clearRenderedFacts(source) {
30
+ source.querySelectorAll(".md-source__facts").forEach(function (facts) {
31
+ facts.remove();
32
+ });
33
+
34
+ var repository = source.querySelector(".md-source__repository");
35
+ if (repository) {
36
+ repository.classList.remove("md-source__repository--active");
37
+ }
38
+ }
39
+
40
+ function renderStats(stats) {
41
+ document.querySelectorAll(".md-source").forEach(function (source) {
42
+ if (!(source instanceof HTMLAnchorElement) || !isCtxSource(source)) {
43
+ return;
44
+ }
45
+
46
+ clearRenderedFacts(source);
47
+
48
+ var repository = source.querySelector(".md-source__repository");
49
+ if (!repository) {
50
+ return;
51
+ }
52
+
53
+ var facts = document.createElement("ul");
54
+ facts.className = "md-source__facts";
55
+ facts.appendChild(createFact("stars", stats.stars));
56
+ facts.appendChild(createFact("forks", stats.forks));
57
+
58
+ repository.appendChild(facts);
59
+ repository.classList.add("md-source__repository--active");
60
+ });
61
+ }
62
+
63
+ function clearStaleStats() {
64
+ document.querySelectorAll(".md-source").forEach(function (source) {
65
+ if (source instanceof HTMLAnchorElement && isCtxSource(source)) {
66
+ clearRenderedFacts(source);
67
+ }
68
+ });
69
+ }
70
+
71
+ function updateMaterialCache(stats) {
72
+ try {
73
+ sessionStorage.setItem(
74
+ MATERIAL_SOURCE_CACHE_KEY,
75
+ JSON.stringify({ stars: stats.stars, forks: stats.forks })
76
+ );
77
+ } catch (error) {
78
+ /* Browser storage may be disabled. The visible header is still updated. */
79
+ }
80
+ }
81
+
82
+ async function fetchStats() {
83
+ var response = await fetch(REPO_API_URL, {
84
+ cache: "no-store",
85
+ headers: { Accept: "application/vnd.github+json" },
86
+ });
87
+
88
+ if (!response.ok) {
89
+ throw new Error("GitHub repository stats request failed");
90
+ }
91
+
92
+ var data = await response.json();
93
+ return {
94
+ forks: Number(data.forks_count || 0),
95
+ stars: Number(data.stargazers_count || 0),
96
+ };
97
+ }
98
+
99
+ async function refreshRepoStats() {
100
+ clearStaleStats();
101
+
102
+ try {
103
+ var stats = await fetchStats();
104
+ updateMaterialCache(stats);
105
+ renderStats(stats);
106
+ } catch (error) {
107
+ clearStaleStats();
108
+ }
109
+ }
110
+
111
+ if (document.readyState === "loading") {
112
+ document.addEventListener("DOMContentLoaded", refreshRepoStats, { once: true });
113
+ } else {
114
+ refreshRepoStats();
115
+ }
116
+
117
+ if (window.document$ && typeof window.document$.subscribe === "function") {
118
+ window.document$.subscribe(refreshRepoStats);
119
+ }
120
+ })();
docs/backup-hook-install.md CHANGED
@@ -1,224 +1,224 @@
1
- # Change-triggered backup — hook install
2
-
3
- One page on wiring the `backup_on_change.py` PostToolUse hook into Claude
4
- Code so a new snapshot fires automatically whenever you edit a tracked
5
- config file (`~/.claude/settings.json`, agents, skills, top-level
6
- manifests, etc.).
7
-
8
- ## What it does
9
-
10
- On every `Edit` / `Write` / `MultiEdit` tool call, the hook:
11
-
12
- 1. Reads the tool payload from stdin.
13
- 2. Resolves `tool_input.file_path` and checks if it sits under
14
- `~/.claude` in a file/tree/memory path tracked by `BackupConfig`.
15
- 3. If tracked, shells out to
16
- `python <repo>/src/backup_mirror.py snapshot-if-changed --reason <tool>:<basename>`.
17
- 4. `snapshot-if-changed` hashes every tracked file, compares against the
18
- most recent snapshot's `manifest.json`, and only creates a new folder
19
- when at least one SHA differs.
20
-
21
- No-op edits don't create folders. The hook always exits 0 so a bug in
22
- the backup layer cannot stall a Claude session.
23
-
24
- ## Register the hook
25
-
26
- Edit `~/.claude/settings.json` and add the following under `hooks` (keep
27
- any existing entries alongside it). Replace `<REPO>` with the absolute
28
- path to this checkout — on Windows this is a path like
29
- `C:/Steves_Files/Work/Research_and_Papers/ctx`.
30
-
31
- ```json
32
- {
33
- "hooks": {
34
- "PostToolUse": [
35
- {
36
- "matcher": "Edit|Write|MultiEdit",
37
- "hooks": [
38
- {
39
- "type": "command",
40
- "command": "python <REPO>/hooks/backup_on_change.py"
41
- }
42
- ]
43
- }
44
- ]
45
- }
46
- }
47
- ```
48
-
49
- Notes:
50
-
51
- - The `matcher` is a regex against the tool name — the three names above
52
- are the only tools that touch files.
53
- - Use forward slashes in the path even on Windows.
54
- - If `python` on your PATH is not the interpreter you want, give the
55
- absolute path instead (e.g.
56
- `C:/Users/you/.pyenv/pyenv-win/versions/3.13.2/python.exe`).
57
-
58
- ## Verify it works
59
-
60
- 1. Reload Claude Code (the hook registration is read at session start).
61
- 2. Edit a tracked file, e.g. `~/.claude/CLAUDE.md`.
62
- 3. Watch `~/.claude/backups/` — a new folder named
63
- `<timestamp>__edit-claude-md` should appear within a second.
64
- 4. Edit the same file again with identical content — no new folder
65
- appears (SHA is unchanged).
66
-
67
- If nothing shows up, run the verb manually to isolate the failure:
68
-
69
- ```bash
70
- python -m backup_mirror snapshot-if-changed --reason smoke-test --json
71
- ```
72
-
73
- The JSON output tells you which files the detector considered new,
74
- changed, or removed.
75
-
76
- ## What gets backed up
77
-
78
- See `src/backup_config.py` and the `backup` section of
79
- `src/config.json` for the current defaults:
80
-
81
- - **top_files** — `settings.json`, `skill-manifest.json`,
82
- `pending-skills.json`, `CLAUDE.md`, `AGENTS.md`, `user-profile.json`,
83
- `skill-system-config.json`, `skill-registry.json`.
84
- - **trees** — `agents/`, `skills/`.
85
- - **memory** — `projects/*/memory/**` when `memory_glob` is true.
86
- - **always excluded** — `.credentials.json`, `claude.json`, token
87
- caches; these are dropped even if a user config lists them.
88
-
89
- To override per user, drop a partial config at
90
- `~/.claude/backup-config.json`. Fields you omit fall back to the repo
91
- default. Example:
92
-
93
- ```json
94
- {
95
- "retention": { "keep_latest": 100 },
96
- "top_files": ["settings.json", "CLAUDE.md"]
97
- }
98
- ```
99
-
100
- ## Manual CLI
101
-
102
- The same verb is available as a one-shot command:
103
-
104
- ```bash
105
- # snapshot only when something changed
106
- python -m backup_mirror snapshot-if-changed --reason manual-check
107
-
108
- # force an unconditional snapshot with a reason label
109
- python -m backup_mirror create --reason pre-upgrade
110
- ```
111
-
112
- Both land under `~/.claude/backups/<timestamp>__<reason>/` and write a
113
- `manifest.json` that records the reason alongside every file's SHA-256.
114
-
115
- ## Watchdog — snapshot on changes outside a Claude session
116
-
117
- The PostToolUse hook only fires on `Edit` / `Write` / `MultiEdit` tool
118
- calls *inside* a Claude session. If you edit `~/.claude/settings.json`
119
- in VS Code, or a `git pull` updates an agent file, the hook never
120
- sees it.
121
-
122
- For that gap, run the polling watchdog — a simple loop that calls
123
- `snapshot-if-changed` every N seconds:
124
-
125
- ```bash
126
- python -m backup_mirror watchdog --interval 60
127
- ```
128
-
129
- Flags:
130
-
131
- | Flag | Meaning |
132
- | --- | --- |
133
- | `--interval N` | Seconds between polls. Clamped to `[5, 3600]`. Default 60. |
134
- | `--reason-prefix LBL` | Prefix used for each snapshot's `--reason` label. Default `watchdog`. |
135
- | `--once` | Run exactly one tick and exit. Useful for cron / Task Scheduler. |
136
- | `--json` | Emit run stats as JSON on exit. |
137
-
138
- Because change detection is SHA-gated, polling is cheap — a tick with
139
- no real changes does zero disk writes.
140
-
141
- ### Running it as a background service
142
-
143
- Ready-to-use service manifests live under
144
- [`docs/services/`](https://github.com/stevesolun/ctx/tree/main/docs/services).
145
- Each one expects you to edit a handful of paths — there's no installer
146
- that guesses where you keep the checkout.
147
-
148
- - **Linux (systemd user unit)** —
149
- [`docs/services/systemd/claude-backup-watchdog.service`](https://github.com/stevesolun/ctx/blob/main/docs/services/systemd/claude-backup-watchdog.service).
150
- Copy to `~/.config/systemd/user/`, set `CTX_REPO`, then
151
- `systemctl --user enable --now claude-backup-watchdog.service`.
152
- - **macOS (launchd agent)** —
153
- [`docs/services/macos/com.claude.backup.watchdog.plist`](https://github.com/stevesolun/ctx/blob/main/docs/services/macos/com.claude.backup.watchdog.plist).
154
- Edit the `ProgramArguments` paths, drop into
155
- `~/Library/LaunchAgents/`, then
156
- `launchctl load -w ~/Library/LaunchAgents/com.claude.backup.watchdog.plist`.
157
- - **Windows (Task Scheduler installer)** —
158
- [`docs/services/windows/install-backup-watchdog.ps1`](https://github.com/stevesolun/ctx/blob/main/docs/services/windows/install-backup-watchdog.ps1).
159
- Run `pwsh -File docs/services/windows/install-backup-watchdog.ps1`
160
- from the repo root; it detects Python on PATH, registers a
161
- `ClaudeBackupWatchdog` scheduled task that runs at logon, and kicks
162
- off the first tick. `-Uninstall` removes it.
163
-
164
- All three manifests assume the watchdog runs as an **unprivileged
165
- user** — no admin/root — because it only reads `~/.claude/` and writes
166
- `~/.claude/backups/`.
167
-
168
- The watchdog stops cleanly on SIGINT/SIGTERM, flushes its stats line
169
- to stderr, and exits 0. Pair it with the hook: the hook handles
170
- in-session edits in real time; the watchdog catches everything else.
171
-
172
- ## Retention — how old snapshots get pruned
173
-
174
- Auto-pruning runs after every successful `snapshot-if-changed`, so the
175
- hook cannot fill the disk. The active policy comes from
176
- `BackupRetention` in `src/backup_config.py` (or your user override):
177
-
178
- | Field | Default | Meaning |
179
- | --- | --- | --- |
180
- | `keep_latest` | `50` | Always keep the N most-recent snapshots. |
181
- | `keep_daily` | `14` | For the M most-recent UTC days that have snapshots, keep the newest snapshot from each. |
182
-
183
- A snapshot survives the sweep iff it's in the **union** of those two
184
- sets. Snapshots whose `manifest.json` has a missing or zero
185
- `created_at` are always protected — we never silently delete something
186
- we can't place in time.
187
-
188
- To override per user, add a partial config at
189
- `~/.claude/backup-config.json`:
190
-
191
- ```json
192
- {
193
- "retention": { "keep_latest": 100, "keep_daily": 30 }
194
- }
195
- ```
196
-
197
- ### Manual prune
198
-
199
- ```bash
200
- # Dry-run the configured policy — no deletions, JSON report.
201
- python -m backup_mirror prune --policy --dry-run --json
202
-
203
- # Apply the configured policy for real.
204
- python -m backup_mirror prune --policy
205
-
206
- # Legacy mode (still works): keep only the N newest.
207
- python -m backup_mirror prune --keep 20
208
- ```
209
-
210
- The policy output tells you which snapshots were kept by `keep_latest`
211
- versus `keep_daily`, so a surprising retention decision is easy to
212
- audit.
213
-
214
- ## Troubleshooting
215
-
216
- | Symptom | Likely cause |
217
- | --- | --- |
218
- | Hook never fires | Settings not reloaded, or `matcher` typo. |
219
- | Snapshot folder with no `reason` suffix | Called `create` without `--reason`. |
220
- | Hook fires but no folder appears | Content hash matched — nothing actually changed. |
221
- | Credentials appear in a snapshot | User put them in `top_files`; the `ALWAYS_EXCLUDE` filter would drop them — check you're on the current `backup_config.py`. |
222
- | `ImportError: backup_config` from the hook | Repo moved; update the path in `settings.json`. |
223
- | Snapshots pile up forever | `retention.keep_latest` / `keep_daily` too high. Run `prune --policy --dry-run --json` to see what the current policy would do, then lower the caps in `~/.claude/backup-config.json`. |
224
- | Prune removed too much | Run `prune --policy --dry-run` *before* committing to a new policy. A snapshot with a missing/zero `created_at` is always protected, so if it's getting deleted the manifest is probably fine and the policy is genuinely too aggressive. |
 
1
+ # Change-triggered backup — hook install
2
+
3
+ One page on wiring the `backup_on_change.py` PostToolUse hook into Claude
4
+ Code so a new snapshot fires automatically whenever you edit a tracked
5
+ config file (`~/.claude/settings.json`, agents, skills, top-level
6
+ manifests, etc.).
7
+
8
+ ## What it does
9
+
10
+ On every `Edit` / `Write` / `MultiEdit` tool call, the hook:
11
+
12
+ 1. Reads the tool payload from stdin.
13
+ 2. Resolves `tool_input.file_path` and checks if it sits under
14
+ `~/.claude` in a file/tree/memory path tracked by `BackupConfig`.
15
+ 3. If tracked, shells out to
16
+ `python <repo>/src/backup_mirror.py snapshot-if-changed --reason <tool>:<basename>`.
17
+ 4. `snapshot-if-changed` hashes every tracked file, compares against the
18
+ most recent snapshot's `manifest.json`, and only creates a new folder
19
+ when at least one SHA differs.
20
+
21
+ No-op edits don't create folders. The hook always exits 0 so a bug in
22
+ the backup layer cannot stall a Claude session.
23
+
24
+ ## Register the hook
25
+
26
+ Edit `~/.claude/settings.json` and add the following under `hooks` (keep
27
+ any existing entries alongside it). Replace `<REPO>` with the absolute
28
+ path to this checkout — on Windows this is a path like
29
+ `C:/Steves_Files/Work/Research_and_Papers/ctx`.
30
+
31
+ ```json
32
+ {
33
+ "hooks": {
34
+ "PostToolUse": [
35
+ {
36
+ "matcher": "Edit|Write|MultiEdit",
37
+ "hooks": [
38
+ {
39
+ "type": "command",
40
+ "command": "python <REPO>/hooks/backup_on_change.py"
41
+ }
42
+ ]
43
+ }
44
+ ]
45
+ }
46
+ }
47
+ ```
48
+
49
+ Notes:
50
+
51
+ - The `matcher` is a regex against the tool name — the three names above
52
+ are the only tools that touch files.
53
+ - Use forward slashes in the path even on Windows.
54
+ - If `python` on your PATH is not the interpreter you want, give the
55
+ absolute path instead (e.g.
56
+ `C:/Users/you/.pyenv/pyenv-win/versions/3.13.2/python.exe`).
57
+
58
+ ## Verify it works
59
+
60
+ 1. Reload Claude Code (the hook registration is read at session start).
61
+ 2. Edit a tracked file, e.g. `~/.claude/CLAUDE.md`.
62
+ 3. Watch `~/.claude/backups/` — a new folder named
63
+ `<timestamp>__edit-claude-md` should appear within a second.
64
+ 4. Edit the same file again with identical content — no new folder
65
+ appears (SHA is unchanged).
66
+
67
+ If nothing shows up, run the verb manually to isolate the failure:
68
+
69
+ ```bash
70
+ python -m backup_mirror snapshot-if-changed --reason smoke-test --json
71
+ ```
72
+
73
+ The JSON output tells you which files the detector considered new,
74
+ changed, or removed.
75
+
76
+ ## What gets backed up
77
+
78
+ See `src/backup_config.py` and the `backup` section of
79
+ `src/config.json` for the current defaults:
80
+
81
+ - **top_files** — `settings.json`, `skill-manifest.json`,
82
+ `pending-skills.json`, `CLAUDE.md`, `AGENTS.md`, `user-profile.json`,
83
+ `skill-system-config.json`, `skill-registry.json`.
84
+ - **trees** — `agents/`, `skills/`.
85
+ - **memory** — `projects/*/memory/**` when `memory_glob` is true.
86
+ - **always excluded** — `.credentials.json`, `claude.json`, token
87
+ caches; these are dropped even if a user config lists them.
88
+
89
+ To override per user, drop a partial config at
90
+ `~/.claude/backup-config.json`. Fields you omit fall back to the repo
91
+ default. Example:
92
+
93
+ ```json
94
+ {
95
+ "retention": { "keep_latest": 100 },
96
+ "top_files": ["settings.json", "CLAUDE.md"]
97
+ }
98
+ ```
99
+
100
+ ## Manual CLI
101
+
102
+ The same verb is available as a one-shot command:
103
+
104
+ ```bash
105
+ # snapshot only when something changed
106
+ python -m backup_mirror snapshot-if-changed --reason manual-check
107
+
108
+ # force an unconditional snapshot with a reason label
109
+ python -m backup_mirror create --reason pre-upgrade
110
+ ```
111
+
112
+ Both land under `~/.claude/backups/<timestamp>__<reason>/` and write a
113
+ `manifest.json` that records the reason alongside every file's SHA-256.
114
+
115
+ ## Watchdog — snapshot on changes outside a Claude session
116
+
117
+ The PostToolUse hook only fires on `Edit` / `Write` / `MultiEdit` tool
118
+ calls *inside* a Claude session. If you edit `~/.claude/settings.json`
119
+ in VS Code, or a `git pull` updates an agent file, the hook never
120
+ sees it.
121
+
122
+ For that gap, run the polling watchdog — a simple loop that calls
123
+ `snapshot-if-changed` every N seconds:
124
+
125
+ ```bash
126
+ python -m backup_mirror watchdog --interval 60
127
+ ```
128
+
129
+ Flags:
130
+
131
+ | Flag | Meaning |
132
+ | --- | --- |
133
+ | `--interval N` | Seconds between polls. Clamped to `[5, 3600]`. Default 60. |
134
+ | `--reason-prefix LBL` | Prefix used for each snapshot's `--reason` label. Default `watchdog`. |
135
+ | `--once` | Run exactly one tick and exit. Useful for cron / Task Scheduler. |
136
+ | `--json` | Emit run stats as JSON on exit. |
137
+
138
+ Because change detection is SHA-gated, polling is cheap — a tick with
139
+ no real changes does zero disk writes.
140
+
141
+ ### Running it as a background service
142
+
143
+ Ready-to-use service manifests live under
144
+ [`docs/services/`](https://github.com/stevesolun/ctx/tree/main/docs/services).
145
+ Each one expects you to edit a handful of paths — there's no installer
146
+ that guesses where you keep the checkout.
147
+
148
+ - **Linux (systemd user unit)** —
149
+ [`docs/services/systemd/claude-backup-watchdog.service`](https://github.com/stevesolun/ctx/blob/main/docs/services/systemd/claude-backup-watchdog.service).
150
+ Copy to `~/.config/systemd/user/`, set `CTX_REPO`, then
151
+ `systemctl --user enable --now claude-backup-watchdog.service`.
152
+ - **macOS (launchd agent)** —
153
+ [`docs/services/macos/com.claude.backup.watchdog.plist`](https://github.com/stevesolun/ctx/blob/main/docs/services/macos/com.claude.backup.watchdog.plist).
154
+ Edit the `ProgramArguments` paths, drop into
155
+ `~/Library/LaunchAgents/`, then
156
+ `launchctl load -w ~/Library/LaunchAgents/com.claude.backup.watchdog.plist`.
157
+ - **Windows (Task Scheduler installer)** —
158
+ [`docs/services/windows/install-backup-watchdog.ps1`](https://github.com/stevesolun/ctx/blob/main/docs/services/windows/install-backup-watchdog.ps1).
159
+ Run `pwsh -File docs/services/windows/install-backup-watchdog.ps1`
160
+ from the repo root; it detects Python on PATH, registers a
161
+ `ClaudeBackupWatchdog` scheduled task that runs at logon, and kicks
162
+ off the first tick. `-Uninstall` removes it.
163
+
164
+ All three manifests assume the watchdog runs as an **unprivileged
165
+ user** — no admin/root — because it only reads `~/.claude/` and writes
166
+ `~/.claude/backups/`.
167
+
168
+ The watchdog stops cleanly on SIGINT/SIGTERM, flushes its stats line
169
+ to stderr, and exits 0. Pair it with the hook: the hook handles
170
+ in-session edits in real time; the watchdog catches everything else.
171
+
172
+ ## Retention — how old snapshots get pruned
173
+
174
+ Auto-pruning runs after every successful `snapshot-if-changed`, so the
175
+ hook cannot fill the disk. The active policy comes from
176
+ `BackupRetention` in `src/backup_config.py` (or your user override):
177
+
178
+ | Field | Default | Meaning |
179
+ | --- | --- | --- |
180
+ | `keep_latest` | `50` | Always keep the N most-recent snapshots. |
181
+ | `keep_daily` | `14` | For the M most-recent UTC days that have snapshots, keep the newest snapshot from each. |
182
+
183
+ A snapshot survives the sweep iff it's in the **union** of those two
184
+ sets. Snapshots whose `manifest.json` has a missing or zero
185
+ `created_at` are always protected — we never silently delete something
186
+ we can't place in time.
187
+
188
+ To override per user, add a partial config at
189
+ `~/.claude/backup-config.json`:
190
+
191
+ ```json
192
+ {
193
+ "retention": { "keep_latest": 100, "keep_daily": 30 }
194
+ }
195
+ ```
196
+
197
+ ### Manual prune
198
+
199
+ ```bash
200
+ # Dry-run the configured policy — no deletions, JSON report.
201
+ python -m backup_mirror prune --policy --dry-run --json
202
+
203
+ # Apply the configured policy for real.
204
+ python -m backup_mirror prune --policy
205
+
206
+ # Legacy mode (still works): keep only the N newest.
207
+ python -m backup_mirror prune --keep 20
208
+ ```
209
+
210
+ The policy output tells you which snapshots were kept by `keep_latest`
211
+ versus `keep_daily`, so a surprising retention decision is easy to
212
+ audit.
213
+
214
+ ## Troubleshooting
215
+
216
+ | Symptom | Likely cause |
217
+ | --- | --- |
218
+ | Hook never fires | Settings not reloaded, or `matcher` typo. |
219
+ | Snapshot folder with no `reason` suffix | Called `create` without `--reason`. |
220
+ | Hook fires but no folder appears | Content hash matched — nothing actually changed. |
221
+ | Credentials appear in a snapshot | User put them in `top_files`; the `ALWAYS_EXCLUDE` filter would drop them — check you're on the current `backup_config.py`. |
222
+ | `ImportError: backup_config` from the hook | Repo moved; update the path in `settings.json`. |
223
+ | Snapshots pile up forever | `retention.keep_latest` / `keep_daily` too high. Run `prune --policy --dry-run --json` to see what the current policy would do, then lower the caps in `~/.claude/backup-config.json`. |
224
+ | Prune removed too much | Run `prune --policy --dry-run` *before* committing to a new policy. A snapshot with a missing/zero `created_at` is always protected, so if it's getting deleted the manifest is probably fine and the policy is genuinely too aggressive. |
docs/dashboard.md CHANGED
@@ -1,325 +1,347 @@
1
- # Dashboard (`ctx-monitor`)
2
-
3
- Local HTTP dashboard for ctx's currently supported live observables:
4
- loaded skills, agents, MCP servers, and installed harness records; session timelines; the
5
- knowledge graph; the LLM-wiki browser; quality grades + scores;
6
- durable queue state; graph/wiki artifact versions; filterable audit
7
- logs; generic-harness validation/escalation state; a live event stream;
8
- and harness wiki/graph browsing.
9
-
10
- ```bash
11
- ctx-monitor serve # http://127.0.0.1:8765
12
- ctx-monitor serve --port 8888 # custom port
13
- ctx-monitor serve --host 0.0.0.0 --port 8888 # LAN read-only with startup token URL
14
- ```
15
-
16
- Zero Python dependencies added by the dashboard. Everything runs on
17
- stdlib `http.server`, using daemon request threads so a live
18
- `/api/events.stream` client cannot block normal dashboard or JSON API
19
- requests. The graph page uses a built-in list renderer and does not load
20
- third-party JavaScript.
21
-
22
- ## Usage
23
-
24
- Every page in the dashboard has the same top nav, so getting around
25
- is `Home -> jump anywhere`. The dashboard indexes skills, agents, MCP
26
- servers, and harness pages in wiki/graph views. Harness installation,
27
- update, and uninstall run through `ctx-harness-install`; dashboard
28
- load/unload POSTs reject harnesses with the exact dry-run command to use.
29
- Quality scoring is shown for sidecar-backed skills, agents, and MCP servers.
30
- Generic/API/local harnesses that call ctx-core validation tools write to
31
- the runtime lifecycle ledger. The dashboard exposes that ledger at
32
- `/runtime` and as JSON at `/api/runtime.json`.
33
-
34
- ### Check queue and artifact state - `/status`
35
-
36
- The status tab shows the durable wiki/graph maintenance queue and the
37
- generated graph/wiki artifacts that ctx can ship or consume. It reports:
38
-
39
- - queue DB availability and job counts by state (`pending`, `running`,
40
- `succeeded`, `failed`, `cancelled`)
41
- - the 20 most recent queue jobs with kind, attempts, source, worker, and
42
- last error; counts and the recent-job window are bounded in the queue DB,
43
- not by loading the whole queue into dashboard memory
44
- - explicit crash recovery state: expired leases are requeued until their
45
- retry budget is exhausted; exhausted leases become `failed`; operator
46
- cancellations become terminal `cancelled` jobs
47
- - a visible queue DB error callout when the queue file exists but cannot be
48
- opened or queried
49
- - artifact presence and byte size for generated
50
- `~/.claude/skill-wiki/graphify-out/{graph.json,graph-delta.json,communities.json}`
51
- plus the runtime skill index, falling back to the repo `graph/`
52
- directory during source checkouts. The status page also reports the full
53
- `wiki-graph.tar.gz` artifact when present.
54
- - artifact promotion metadata, including the latest promoted hash when
55
- the crash-safe promotion path has recorded it
56
-
57
- ### Browse the LLM wiki — `/wiki`
58
-
59
- The wiki tab requires full wiki markdown content from
60
- `ctx-init --graph --graph-install-mode full` or local/private wiki entities.
61
- The default runtime graph install powers recommendations and graph stats but
62
- does not expand every entity page. When entity pages exist, the wiki tab is a
63
- filterable card grid over a deterministic, bounded dashboard sample:
64
- up to 500 pages per dashboard-supported entity type under
65
- `~/.claude/skill-wiki/entities/{skills,agents,mcp-servers,harnesses}/`.
66
- MCP server pages use the sharded layout
67
- `entities/mcp-servers/<first-char-or-0-9>/<slug>.md`; the dashboard
68
- routes `/wiki/<slug>` to the same shard convention. Harness pages use
69
- the flat `entities/harnesses/<slug>.md` layout. Each card shows:
70
-
71
- - the slug (click to open `/wiki/<slug>?type=<entity>`)
72
- - the quality grade pill (A/B/C/D/F) when the entity has a sidecar,
73
- otherwise a `skill`, `agent`, `mcp-server`, or `harness` type badge
74
- - the frontmatter `description`
75
- - up to 6 tags
76
-
77
- The **left sidebar** has a text search over the visible sample that
78
- matches slug, description, and tags, plus skill/agent/MCP/harness type
79
- checkboxes. Pair them to
80
- answer questions like "show me all grade-B agents related to
81
- testing" check `agent`, type `testing` in the search box.
82
-
83
- Dashboard-supported entity pages (`/wiki/<slug>?type=<entity>`) render a
84
- bounded markdown preview and a bounded frontmatter table on the right, plus a
85
- quality banner with deep links to `/skill/<slug>` (sidecar detail) and
86
- `/graph?slug=<slug>&type=<entity>` (1-hop neighborhood). Long body previews and
87
- frontmatter values are visibly marked as truncated.
88
-
89
- ### Explore the knowledge graph — `/graph`
90
-
91
- The graph tab is a built-in list view over the dashboard-supported
92
- skill/agent/MCP/harness graph. Imported skills are normal `skill`
93
- nodes in the graph. Harness nodes are browsable and filterable here;
94
- install/update actions remain in `ctx-harness-install`.
95
- When you arrive with no
96
- slug selected, the page shows:
97
-
98
- - a stats line with the total node + edge counts
99
- - a **Popular seed slugs** panel the 18 highest-degree entities
100
- rendered as clickable entity-type chips.
101
- Click a chip to explore that entity's 1-hop neighborhood
102
- - a search box type any valid skill, agent, MCP, or harness slug and press
103
- `explore` (or hit Enter)
104
- - the graph list panel itself, which activates as soon as you pick a
105
- seed
106
-
107
- Inside the graph list view, entity pills identify the node type. The
108
- focus row has `depth=0` in the page data, and neighbor rows are filterable
109
- by entity type and shared tag/token text.
110
-
111
- The JSON endpoint still includes blended graph edge weights, combining
112
- semantic similarity, explicit tag overlap, and slug-token overlap where
113
- available. **Tap any row** to
114
- navigate to that entity's wiki page. The type checkboxes hide or show
115
- skills, agents, MCP servers, and harnesses without reloading the graph.
116
-
117
- ### Read the quality KPIs — `/kpi`
118
-
119
- The KPI tab is the browser equivalent of `python -m kpi_dashboard
120
- render`. It aggregates the quality + lifecycle sidecars under
121
- `~/.claude/skill-quality/` into a single page with six tables:
122
-
123
- 1. **Header banner** total entity count, subject breakdown, grade
124
- pill counts, link to the raw `/api/kpi.json` payload, link back to
125
- `/skills`.
126
- 2. **Grade distribution** A/B/C/D/F count and share.
127
- 3. **Lifecycle tiers** — counts for `active`, `watch`, `demote`,
128
- `archive`.
129
- 4. **Hard floors active** which override reasons are currently
130
- pinning entities to F (`never_loaded_stale`, `intake_fail`, etc.)
131
- and how many entities each one catches.
132
- 5. **By category** — per-category count, average score, and full
133
- A/B/C/D/F mix. This is the row most useful for "where are my D/F
134
- skills concentrated?"
135
- 6. **Top demotion candidates** — up to 25 active-or-watch entities
136
- graded D/F, sorted by consecutive-D streak desc then raw score
137
- asc. Click a slug to jump to its sidecar.
138
- 7. **Archived** — slugs currently in the archive tier, with their
139
- last-known grade.
140
-
141
- If the quality sidecar directory is empty (no scoring has happened
142
- yet), the page shows a helpful empty-state pointing at
143
- `ctx-skill-quality recompute --all`.
144
-
145
- ## Routes
146
-
147
- ### Top navigation
148
-
149
- Every page shows the same nav bar. The eleven tabs cover the
150
- dashboard-supported observable surface of ctx:
151
-
152
- ```
153
- Home · Loaded · Skills · Wiki · Graph · Manage · Harness Setup · Docs · Config · Status · KPIs · Runtime · Sessions · Logs · Live
154
- ```
155
-
156
- ### HTML views
157
-
158
- Harness catalog entries are visible in wiki and graph routes. `/loaded` shows
159
- installed harness records from `~/.claude/harness-installs/*.json`, not the
160
- full catalog. Harness installation, update, and uninstall remain
161
- `ctx-harness-install` workflows, while harness scoring is not exposed in the
162
- dashboard yet.
163
- Dashboard POST actions are available only from loopback clients and require the
164
- per-process monitor token injected into the rendered page.
165
-
166
- | Route | What it shows |
167
- |---|---|
168
- | `/` | Home: seven stat cards (loaded, sidecars, wiki entities, graph nodes, runtime checks, audit events, sessions), grade distribution pills, recent sessions table, recent audit events |
169
- | `/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 |
170
- | `/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 |
171
- | `/skill/<slug>` | Full sidecar breakdown: four-signal score (telemetry · intake · graph · routing), hard-floor reason, computed_at timestamp, per-skill audit timeline |
172
- | `/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. |
173
- | `/wiki/<slug>?type=<entity>` | 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`. |
174
- | `/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 built-in graph list panel. Clicking a seed chip navigates to `/graph?slug=<slug>&type=<entity>`. |
175
- | `/graph?slug=<slug>&type=<entity>` | **Built-in** 1-hop neighborhood around the target skill/agent/MCP/harness slug. Entity pills identify skill, agent, MCP server, and harness rows. Tap any node to navigate to that entity's typed wiki page. Type and tag filters run client-side. |
176
- | `/manage` | Search, inspect, edit, delete, and manually import skill/agent/MCP/harness wiki entities through the same safe-name and mutation-token checks as live load/unload. |
177
- | `/harness` | Harness Setup wizard for non-Claude/custom API/local model users: collects model, goals, tool needs, safety constraints, and shows the harness recommendation/install path. |
178
- | `/docs` | Local repo docs rendered inside the dashboard with MkDocs-like tabs, sidebar table of contents, in-dashboard search, and source links. |
179
- | `/config` | Effective ctx config with defaults, required markers, field explanations, and editable user overrides where supported. |
180
- | `/status` | Durable queue and artifact status: job counts by state, recent queue jobs, graph/wiki artifact sizes, and crash-safe promotion metadata. |
181
- | `/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 |
182
- | `/runtime` | Generic harness runtime ledger from `CTX_RUNTIME_LIFECYCLE_DIR` or `~/.ctx/runtime/events.jsonl`: validation totals, failed/error checks, recent validation rows, and open escalations. |
183
- | `/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 |
184
- | `/session/<id>` | Per-session audit timeline showing the load → score_updated → unload triad with timestamps |
185
- | `/logs` | Last 500 audit events in a filterable table (client-side filter on event name, subject, session id) |
186
- | `/events` | Live SSE stream of new audit events |
187
-
188
- ### JSON API
189
-
190
- | Route | Returns |
191
- |---|---|
192
- | `GET /api/sessions.json` | All sessions with aggregated counts |
193
- | `GET /api/manifest.json` | Raw `skill-manifest.json` passthrough |
194
- | `GET /api/status.json` | `{queue, artifacts}` payload: durable queue counts/recent jobs plus graph/wiki artifact file status and promotion metadata |
195
- | `GET /api/skill/<slug>.json` | Raw sidecar for one slug |
196
- | `GET /api/graph/<slug>.json?type=<entity>&hops=1&limit=40` | Dashboard-shaped skill/agent/MCP/harness `{nodes, edges, center}`; `type` is optional but recommended for duplicate slugs, `hops` is [1, 3], `limit` is [5, 150]. |
197
- | `GET /api/kpi.json` | `DashboardSummary` passthrough `{total, by_subject, grade_counts, lifecycle_counts, category_breakdown, hard_floor_counts, low_quality_candidates, archived, generated_at}`. Returns `{total: 0, detail: "no sidecars yet"}` when the quality directory is empty |
198
- | `GET /api/runtime.json` | Runtime lifecycle summary: source path, validation count, failed/error count, open-escalation count, latest validation, recent validations, open escalations, and session IDs. |
199
- | `GET /api/config.json` | Effective/default/user config payload used by the Config tab. |
200
- | `GET /api/entities/search.json?q=<text>&type=<entity>&limit=80` | Wiki entity search results for Manage, Config, and entity picker flows. |
201
- | `GET /api/entity/<slug>.json?type=<entity>` | Frontmatter and Markdown body for one wiki entity. |
202
- | `GET /api/events.stream` | Server-sent events tail of `~/.claude/ctx-audit.jsonl` |
203
-
204
- ### Mutation endpoints
205
-
206
- Dashboard GET views are read-only. When `ctx-monitor` is bound to a
207
- non-loopback host, HTML, `/api/*` JSON, and SSE routes require the
208
- read-token URL printed by `ctx-monitor`; the first successful token URL
209
- sets an HttpOnly same-site cookie for dashboard navigation. Keep the
210
- default loopback bind for local automation. POST endpoints enforce
211
- same-origin (browser tab open on another origin can't forge a request), require the per-process
212
- `X-CTX-Monitor-Token` injected into the dashboard page, and reject any
213
- slug failing the shared safe-name validator. That validator blocks path
214
- separators, Windows drive-relative strings, malformed names, and Windows
215
- reserved device names such as `con.txt` and `nul.`. There is no harness
216
- load/unload mutation endpoint yet.
217
-
218
- | Route | Body | Calls |
219
- |---|---|---|
220
- | `POST /api/load` | `{"slug": "...", "entity_type": "skill"}` | `skill_install.install_skill(slug)` |
221
- | `POST /api/load` | `{"slug": "...", "entity_type": "agent"}` | `agent_install.install_agent(slug)` |
222
- | `POST /api/load` | `{"slug": "...", "entity_type": "mcp-server"}` | `mcp_install.install_mcp(slug, command?, json_config?, auto=True)` |
223
- | `POST /api/unload` | `{"slug": "...", "entity_type": "skill"}` | `skill_unload.unload_from_session([slug])` |
224
- | `POST /api/unload` | `{"slug": "...", "entity_type": "agent"}` | remove the agent row from `skill-manifest.json` and append an unload row |
225
- | `POST /api/unload` | `{"slug": "...", "entity_type": "mcp-server"}` | `mcp_install.uninstall_mcp(slug, wiki_dir=...)` |
226
- | `POST /api/config` | `{"updates": {...}}` | persist supported user config overrides after validation |
227
- | `POST /api/entity/upsert` | entity metadata/body payload | write or update a wiki entity, then attach graph/recommendation metadata |
228
- | `POST /api/entity/delete` | `{"slug": "...", "entity_type": "skill"}` | remove a dashboard-supported wiki entity after safe-name validation |
229
-
230
- Harness load/unload POSTs are rejected with the exact
231
- `ctx-harness-install ... --dry-run` command to run instead. Skill rows emit
232
- `skill.loaded` / `skill.unloaded`, agent rows emit `agent.loaded` /
233
- `agent.unloaded`, and MCP rows emit `toolbox.triggered` with
234
- `meta.entity_type="mcp-server"` and `meta.action` set to `loaded` or
235
- `unloaded`. All dashboard-driven rows use `actor=user` and
236
- `meta.via="ctx-monitor"` so they appear in the session timeline.
237
-
238
- ## KPIs, measures, scores
239
-
240
- The dashboard surfaces every quality signal ctx currently computes for
241
- sidecar-backed skills, agents, and MCP servers. Harness scoring is not
242
- yet exposed in the dashboard. Nothing is aggregated-only you can
243
- always drill from a headline number to the raw sidecar that produced it.
244
-
245
- ### On the home page
246
-
247
- | Card | What it means |
248
- |---|---|
249
- | **Currently loaded** | Count of entries in `skill-manifest.json[load]`. Clicking the card drills to `/loaded` |
250
- | **Sidecars** | Total sidecars in `~/.claude/skill-quality/` |
251
- | **Wiki entities** | Count of dashboard-supported wiki pages (skills + agents + MCP servers + harnesses) |
252
- | **Knowledge graph** | Dashboard-supported skill/agent/MCP/harness node count + edge count from `graphify-out/graph.json` |
253
- | **Runtime checks** | Validation totals, failed/error checks, and open escalations from the generic runtime lifecycle ledger |
254
- | **Audit events** | Line count of `~/.claude/ctx-audit.jsonl` |
255
- | **Sessions** | Unique session IDs seen across audit + events |
256
- | **Grade pills** | A / B / C / D / F counts across all sidecars, colored |
257
-
258
- ### On `/skills`
259
-
260
- Every card shows:
261
-
262
- - **grade** A / B / C / D / F pill (A=green, F=red)
263
- - **raw score** float in [0, 1] before the hard-floor override
264
- - **subject_type** skill, agent, or mcp-server
265
- - **hard floor reason** `never_loaded_stale`, `intake_fail`, etc.
266
- when the floor is active
267
-
268
- Cards sorted by `(grade, -raw_score)` so high-scoring A's come first.
269
-
270
- ### On `/skill/<slug>`
271
-
272
- The full four-signal breakdown from the sidecar:
273
-
274
- | Signal | Weight (default) | What it measures |
275
- |---|---:|---|
276
- | **Telemetry** | 0.40 | Load frequency + recency from `skill-events.jsonl`. Rewards skills that are actually used. |
277
- | **Intake** | 0.20 | Structural health: frontmatter fields present, H1 present, minimum body length, description length. Zero if `intake_fail` floor is active. |
278
- | **Graph** | 0.25 | Connectivity in the knowledge graph: degree, average edge weight, community size |
279
- | **Routing** | 0.15 | Router hit rate from `~/.claude/router-trace.jsonl`: how often this skill was among the top-K recommendations when surfaced |
280
-
281
- The final score is `sum(weight[i] * signal[i])`. A hard floor
282
- (`never_loaded_stale`, `intake_fail`) can override the score to
283
- force an F grade regardless of other signals.
284
-
285
- The skill detail page also shows the audit timeline for this slug
286
- specifically: every `skill.loaded`, `skill.unloaded`,
287
- `skill.score_updated` row with its session_id, so you can trace
288
- exactly why the score changed when it did.
289
-
290
- ### On `/session/<id>`
291
-
292
- The per-session view lets you watch a skill's lifecycle inside one
293
- session:
294
-
295
- ```
296
- skill.loaded fastapi-pro session-abc @ 10:23:05
297
- skill.score_updated fastapi-pro session-abc @ 10:31:47 grade C->B
298
- skill.unloaded fastapi-pro session-abc @ 11:04:02
299
- ```
300
-
301
- The `load score_updated unload` triad is the canonical
302
- observability proof that ctx's telemetry pipeline is live.
303
-
304
- ## Security
305
-
306
- - **Binds to 127.0.0.1 by default**. Use `--host 0.0.0.0` only if
307
- you actually want LAN-visible read-only access. The startup output
308
- prints a one-process read-token URL; without that token or the cookie
309
- it sets, LAN HTML/API/SSE requests return 403. Mutations remain
310
- disabled on non-loopback binds.
311
- - **Same-origin gating on mutation**. Any POST with an `Origin`
312
- header that doesn't match `Host` returns 403. Curl and direct
313
- tool calls are allowed (no Origin header at all).
314
- - **Slug allowlist on all paths**. Anywhere the dashboard resolves
315
- a skill, agent, MCP, or harness slug to a file path (`/wiki/<slug>`,
316
- `/graph?slug=<slug>&type=<entity>`, `/api/graph/<slug>.json`), the slug is
317
- validated through the shared
318
- safe-name helper — no path traversal, no absolute paths, no UNC
319
- shares, no Windows reserved device names.
320
-
321
- ## Stopping
322
-
323
- Ctrl+C in the terminal. Request handling is threaded for local dashboard
324
- responsiveness, and shutdown signals any open SSE workers. The monitor is
325
- still not suitable for shared/production serving.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dashboard (`ctx-monitor`)
2
+
3
+ Local HTTP dashboard for ctx's currently supported live observables:
4
+ loaded skills, agents, MCP servers, and installed harness records; session timelines; the
5
+ knowledge graph; the LLM-wiki browser; quality grades + scores;
6
+ durable queue state; graph/wiki artifact versions; filterable audit
7
+ logs; generic-harness validation/escalation state; a live event stream;
8
+ and harness wiki/graph browsing.
9
+
10
+ ```bash
11
+ ctx-monitor serve # http://127.0.0.1:8765
12
+ ctx-monitor serve --port 8888 # custom port
13
+ ctx-monitor serve --host 0.0.0.0 --port 8888 # LAN read-only with startup token URL
14
+ ```
15
+
16
+ Zero Python dependencies added by the dashboard. Everything runs on
17
+ stdlib `http.server`, using daemon request threads so a live
18
+ `/api/events.stream` client cannot block normal dashboard or JSON API
19
+ requests. The graph page uses a built-in list renderer and does not load
20
+ third-party JavaScript.
21
+
22
+ ## Usage
23
+
24
+ Every page in the dashboard has the same top nav, so getting around
25
+ is `Home -> jump anywhere`. The dashboard indexes skills, agents, MCP
26
+ servers, and harness pages in wiki/graph views. Harness installation,
27
+ update, and uninstall run through `ctx-harness-install`; dashboard
28
+ load/unload POSTs reject harnesses with the exact dry-run command to use.
29
+ Quality scoring is shown for sidecar-backed skills, agents, and MCP servers.
30
+ Generic/API/local harnesses that call ctx-core validation tools write to
31
+ the runtime lifecycle ledger. The dashboard exposes that ledger at
32
+ `/runtime` and as JSON at `/api/runtime.json`.
33
+
34
+ ### Check queue and artifact state - `/status`
35
+
36
+ The status tab shows the durable wiki/graph maintenance queue and the
37
+ generated graph/wiki artifacts that ctx can ship or consume. It reports:
38
+
39
+ - queue DB availability and job counts by state (`pending`, `running`,
40
+ `succeeded`, `failed`, `cancelled`)
41
+ - the 20 most recent queue jobs with kind, attempts, source, worker, and
42
+ last error; counts and the recent-job window are bounded in the queue DB,
43
+ not by loading the whole queue into dashboard memory
44
+ - explicit crash recovery state: expired leases are requeued until their
45
+ retry budget is exhausted; exhausted leases become `failed`; operator
46
+ cancellations become terminal `cancelled` jobs
47
+ - a visible queue DB error callout when the queue file exists but cannot be
48
+ opened or queried
49
+ - artifact presence and byte size for generated
50
+ `~/.claude/skill-wiki/graphify-out/{graph.json,graph-delta.json,communities.json}`
51
+ plus the runtime skill index, falling back to the repo `graph/`
52
+ directory during source checkouts. The status page also reports the full
53
+ `wiki-graph.tar.gz` artifact when present.
54
+ - artifact promotion metadata, including the latest promoted hash when
55
+ the crash-safe promotion path has recorded it
56
+
57
+ ### Browse the LLM wiki — `/wiki`
58
+
59
+ #### Catalog badge links
60
+
61
+ The README entity badges open this public docs section so they never point at a
62
+ dead `127.0.0.1` URL from GitHub, PyPI, or Hugging Face. To open the live
63
+ searchable tile catalog, install the full wiki pages and start the local
64
+ dashboard:
65
+
66
+ ```bash
67
+ ctx-init --graph --graph-install-mode full --model-mode skip
68
+ ctx-monitor serve
69
+ ```
70
+
71
+ Then use:
72
+
73
+ - Skills: `http://127.0.0.1:8765/wiki?type=skill`
74
+ - Agents: `http://127.0.0.1:8765/wiki?type=agent`
75
+ - MCP servers: `http://127.0.0.1:8765/wiki?type=mcp-server`
76
+ - Harnesses: `http://127.0.0.1:8765/wiki?type=harness`
77
+
78
+ The local catalog includes search, browser autocomplete suggestions, type
79
+ filters, tile cards, and click-through detail pages for each entity.
80
+
81
+ The wiki tab requires full wiki markdown content from
82
+ `ctx-init --graph --graph-install-mode full` or local/private wiki entities.
83
+ The default runtime graph install powers recommendations and graph stats but
84
+ does not expand every entity page. When entity pages exist, the wiki tab is a
85
+ filterable card grid over a deterministic, bounded dashboard sample:
86
+ up to 500 pages per dashboard-supported entity type under
87
+ `~/.claude/skill-wiki/entities/{skills,agents,mcp-servers,harnesses}/`.
88
+ MCP server pages use the sharded layout
89
+ `entities/mcp-servers/<first-char-or-0-9>/<slug>.md`; the dashboard
90
+ routes `/wiki/<slug>` to the same shard convention. Harness pages use
91
+ the flat `entities/harnesses/<slug>.md` layout. Each card shows:
92
+
93
+ - the slug (click to open `/wiki/<slug>?type=<entity>`)
94
+ - the quality grade pill (A/B/C/D/F) when the entity has a sidecar,
95
+ otherwise a `skill`, `agent`, `mcp-server`, or `harness` type badge
96
+ - the frontmatter `description`
97
+ - up to 6 tags
98
+
99
+ The **left sidebar** has a text search over the visible sample that
100
+ matches slug, description, and tags, plus skill/agent/MCP/harness type
101
+ checkboxes. Pair them to
102
+ answer questions like "show me all grade-B agents related to
103
+ testing" — check `agent`, type `testing` in the search box.
104
+
105
+ Dashboard-supported entity pages (`/wiki/<slug>?type=<entity>`) render a
106
+ bounded markdown preview and a bounded frontmatter table on the right, plus a
107
+ quality banner with deep links to `/skill/<slug>` (sidecar detail) and
108
+ `/graph?slug=<slug>&type=<entity>` (1-hop neighborhood). Long body previews and
109
+ frontmatter values are visibly marked as truncated.
110
+
111
+ ### Explore the knowledge graph `/graph`
112
+
113
+ The graph tab is a built-in list view over the dashboard-supported
114
+ skill/agent/MCP/harness graph. Imported skills are normal `skill`
115
+ nodes in the graph. Harness nodes are browsable and filterable here;
116
+ install/update actions remain in `ctx-harness-install`.
117
+ When you arrive with no
118
+ slug selected, the page shows:
119
+
120
+ - a stats line with the total node + edge counts
121
+ - a **Popular seed slugs** panel — the 18 highest-degree entities
122
+ rendered as clickable entity-type chips.
123
+ Click a chip to explore that entity's 1-hop neighborhood
124
+ - a search box type any valid skill, agent, MCP, or harness slug and press
125
+ `explore` (or hit Enter)
126
+ - the graph list panel itself, which activates as soon as you pick a
127
+ seed
128
+
129
+ Inside the graph list view, entity pills identify the node type. The
130
+ focus row has `depth=0` in the page data, and neighbor rows are filterable
131
+ by entity type and shared tag/token text.
132
+
133
+ The JSON endpoint still includes blended graph edge weights, combining
134
+ semantic similarity, explicit tag overlap, and slug-token overlap where
135
+ available. **Tap any row** to
136
+ navigate to that entity's wiki page. The type checkboxes hide or show
137
+ skills, agents, MCP servers, and harnesses without reloading the graph.
138
+
139
+ ### Read the quality KPIs — `/kpi`
140
+
141
+ The KPI tab is the browser equivalent of `python -m kpi_dashboard
142
+ render`. It aggregates the quality + lifecycle sidecars under
143
+ `~/.claude/skill-quality/` into a single page with six tables:
144
+
145
+ 1. **Header banner** — total entity count, subject breakdown, grade
146
+ pill counts, link to the raw `/api/kpi.json` payload, link back to
147
+ `/skills`.
148
+ 2. **Grade distribution** — A/B/C/D/F count and share.
149
+ 3. **Lifecycle tiers** counts for `active`, `watch`, `demote`,
150
+ `archive`.
151
+ 4. **Hard floors active** — which override reasons are currently
152
+ pinning entities to F (`never_loaded_stale`, `intake_fail`, etc.)
153
+ and how many entities each one catches.
154
+ 5. **By category** — per-category count, average score, and full
155
+ A/B/C/D/F mix. This is the row most useful for "where are my D/F
156
+ skills concentrated?"
157
+ 6. **Top demotion candidates** — up to 25 active-or-watch entities
158
+ graded D/F, sorted by consecutive-D streak desc then raw score
159
+ asc. Click a slug to jump to its sidecar.
160
+ 7. **Archived** slugs currently in the archive tier, with their
161
+ last-known grade.
162
+
163
+ If the quality sidecar directory is empty (no scoring has happened
164
+ yet), the page shows a helpful empty-state pointing at
165
+ `ctx-skill-quality recompute --all`.
166
+
167
+ ## Routes
168
+
169
+ ### Top navigation
170
+
171
+ Every page shows the same nav bar. The eleven tabs cover the
172
+ dashboard-supported observable surface of ctx:
173
+
174
+ ```
175
+ Home · Loaded · Skills · Wiki · Graph · Manage · Harness Setup · Docs · Config · Status · KPIs · Runtime · Sessions · Logs · Live
176
+ ```
177
+
178
+ ### HTML views
179
+
180
+ Harness catalog entries are visible in wiki and graph routes. `/loaded` shows
181
+ installed harness records from `~/.claude/harness-installs/*.json`, not the
182
+ full catalog. Harness installation, update, and uninstall remain
183
+ `ctx-harness-install` workflows, while harness scoring is not exposed in the
184
+ dashboard yet.
185
+ Dashboard POST actions are available only from loopback clients and require the
186
+ per-process monitor token injected into the rendered page.
187
+
188
+ | Route | What it shows |
189
+ |---|---|
190
+ | `/` | Home: seven stat cards (loaded, sidecars, wiki entities, graph nodes, runtime checks, audit events, sessions), grade distribution pills, recent sessions table, recent audit events |
191
+ | `/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 |
192
+ | `/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 |
193
+ | `/skill/<slug>` | Full sidecar breakdown: four-signal score (telemetry · intake · graph · routing), hard-floor reason, computed_at timestamp, per-skill audit timeline |
194
+ | `/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. |
195
+ | `/wiki/<slug>?type=<entity>` | 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`. |
196
+ | `/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 built-in graph list panel. Clicking a seed chip navigates to `/graph?slug=<slug>&type=<entity>`. |
197
+ | `/graph?slug=<slug>&type=<entity>` | **Built-in** 1-hop neighborhood around the target skill/agent/MCP/harness slug. Entity pills identify skill, agent, MCP server, and harness rows. Tap any node to navigate to that entity's typed wiki page. Type and tag filters run client-side. |
198
+ | `/manage` | Search, inspect, edit, delete, and manually import skill/agent/MCP/harness wiki entities through the same safe-name and mutation-token checks as live load/unload. |
199
+ | `/harness` | Harness Setup wizard for non-Claude/custom API/local model users: collects model, goals, tool needs, safety constraints, and shows the harness recommendation/install path. |
200
+ | `/docs` | Local repo docs rendered inside the dashboard with MkDocs-like tabs, sidebar table of contents, in-dashboard search, and source links. |
201
+ | `/config` | Effective ctx config with defaults, required markers, field explanations, and editable user overrides where supported. |
202
+ | `/status` | Durable queue and artifact status: job counts by state, recent queue jobs, graph/wiki artifact sizes, and crash-safe promotion metadata. |
203
+ | `/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 |
204
+ | `/runtime` | Generic harness runtime ledger from `CTX_RUNTIME_LIFECYCLE_DIR` or `~/.ctx/runtime/events.jsonl`: validation totals, failed/error checks, recent validation rows, and open escalations. |
205
+ | `/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 |
206
+ | `/session/<id>` | Per-session audit timeline showing the load → score_updated → unload triad with timestamps |
207
+ | `/logs` | Last 500 audit events in a filterable table (client-side filter on event name, subject, session id) |
208
+ | `/events` | Live SSE stream of new audit events |
209
+
210
+ ### JSON API
211
+
212
+ | Route | Returns |
213
+ |---|---|
214
+ | `GET /api/sessions.json` | All sessions with aggregated counts |
215
+ | `GET /api/manifest.json` | Raw `skill-manifest.json` passthrough |
216
+ | `GET /api/status.json` | `{queue, artifacts}` payload: durable queue counts/recent jobs plus graph/wiki artifact file status and promotion metadata |
217
+ | `GET /api/skill/<slug>.json` | Raw sidecar for one slug |
218
+ | `GET /api/graph/<slug>.json?type=<entity>&hops=1&limit=40` | Dashboard-shaped skill/agent/MCP/harness `{nodes, edges, center}`; `type` is optional but recommended for duplicate slugs, `hops` is [1, 3], `limit` is [5, 150]. |
219
+ | `GET /api/kpi.json` | `DashboardSummary` passthrough — `{total, by_subject, grade_counts, lifecycle_counts, category_breakdown, hard_floor_counts, low_quality_candidates, archived, generated_at}`. Returns `{total: 0, detail: "no sidecars yet"}` when the quality directory is empty |
220
+ | `GET /api/runtime.json` | Runtime lifecycle summary: source path, validation count, failed/error count, open-escalation count, latest validation, recent validations, open escalations, and session IDs. |
221
+ | `GET /api/config.json` | Effective/default/user config payload used by the Config tab. |
222
+ | `GET /api/entities/search.json?q=<text>&type=<entity>&limit=80` | Wiki entity search results for Manage, Config, and entity picker flows. |
223
+ | `GET /api/entity/<slug>.json?type=<entity>` | Frontmatter and Markdown body for one wiki entity. |
224
+ | `GET /api/events.stream` | Server-sent events tail of `~/.claude/ctx-audit.jsonl` |
225
+
226
+ ### Mutation endpoints
227
+
228
+ Dashboard GET views are read-only. When `ctx-monitor` is bound to a
229
+ non-loopback host, HTML, `/api/*` JSON, and SSE routes require the
230
+ read-token URL printed by `ctx-monitor`; the first successful token URL
231
+ sets an HttpOnly same-site cookie for dashboard navigation. Keep the
232
+ default loopback bind for local automation. POST endpoints enforce
233
+ same-origin (browser tab open on another origin can't forge a request), require the per-process
234
+ `X-CTX-Monitor-Token` injected into the dashboard page, and reject any
235
+ slug failing the shared safe-name validator. That validator blocks path
236
+ separators, Windows drive-relative strings, malformed names, and Windows
237
+ reserved device names such as `con.txt` and `nul.`. There is no harness
238
+ load/unload mutation endpoint yet.
239
+
240
+ | Route | Body | Calls |
241
+ |---|---|---|
242
+ | `POST /api/load` | `{"slug": "...", "entity_type": "skill"}` | `skill_install.install_skill(slug)` |
243
+ | `POST /api/load` | `{"slug": "...", "entity_type": "agent"}` | `agent_install.install_agent(slug)` |
244
+ | `POST /api/load` | `{"slug": "...", "entity_type": "mcp-server"}` | `mcp_install.install_mcp(slug, command?, json_config?, auto=True)` |
245
+ | `POST /api/unload` | `{"slug": "...", "entity_type": "skill"}` | `skill_unload.unload_from_session([slug])` |
246
+ | `POST /api/unload` | `{"slug": "...", "entity_type": "agent"}` | remove the agent row from `skill-manifest.json` and append an unload row |
247
+ | `POST /api/unload` | `{"slug": "...", "entity_type": "mcp-server"}` | `mcp_install.uninstall_mcp(slug, wiki_dir=...)` |
248
+ | `POST /api/config` | `{"updates": {...}}` | persist supported user config overrides after validation |
249
+ | `POST /api/entity/upsert` | entity metadata/body payload | write or update a wiki entity, then attach graph/recommendation metadata |
250
+ | `POST /api/entity/delete` | `{"slug": "...", "entity_type": "skill"}` | remove a dashboard-supported wiki entity after safe-name validation |
251
+
252
+ Harness load/unload POSTs are rejected with the exact
253
+ `ctx-harness-install ... --dry-run` command to run instead. Skill rows emit
254
+ `skill.loaded` / `skill.unloaded`, agent rows emit `agent.loaded` /
255
+ `agent.unloaded`, and MCP rows emit `toolbox.triggered` with
256
+ `meta.entity_type="mcp-server"` and `meta.action` set to `loaded` or
257
+ `unloaded`. All dashboard-driven rows use `actor=user` and
258
+ `meta.via="ctx-monitor"` so they appear in the session timeline.
259
+
260
+ ## KPIs, measures, scores
261
+
262
+ The dashboard surfaces every quality signal ctx currently computes for
263
+ sidecar-backed skills, agents, and MCP servers. Harness scoring is not
264
+ yet exposed in the dashboard. Nothing is aggregated-only — you can
265
+ always drill from a headline number to the raw sidecar that produced it.
266
+
267
+ ### On the home page
268
+
269
+ | Card | What it means |
270
+ |---|---|
271
+ | **Currently loaded** | Count of entries in `skill-manifest.json[load]`. Clicking the card drills to `/loaded` |
272
+ | **Sidecars** | Total sidecars in `~/.claude/skill-quality/` |
273
+ | **Wiki entities** | Count of dashboard-supported wiki pages (skills + agents + MCP servers + harnesses) |
274
+ | **Knowledge graph** | Dashboard-supported skill/agent/MCP/harness node count + edge count from `graphify-out/graph.json` |
275
+ | **Runtime checks** | Validation totals, failed/error checks, and open escalations from the generic runtime lifecycle ledger |
276
+ | **Audit events** | Line count of `~/.claude/ctx-audit.jsonl` |
277
+ | **Sessions** | Unique session IDs seen across audit + events |
278
+ | **Grade pills** | A / B / C / D / F counts across all sidecars, colored |
279
+
280
+ ### On `/skills`
281
+
282
+ Every card shows:
283
+
284
+ - **grade** — A / B / C / D / F pill (A=green, F=red)
285
+ - **raw score** float in [0, 1] before the hard-floor override
286
+ - **subject_type** skill, agent, or mcp-server
287
+ - **hard floor reason** — `never_loaded_stale`, `intake_fail`, etc.
288
+ when the floor is active
289
+
290
+ Cards sorted by `(grade, -raw_score)` so high-scoring A's come first.
291
+
292
+ ### On `/skill/<slug>`
293
+
294
+ The full four-signal breakdown from the sidecar:
295
+
296
+ | Signal | Weight (default) | What it measures |
297
+ |---|---:|---|
298
+ | **Telemetry** | 0.40 | Load frequency + recency from `skill-events.jsonl`. Rewards skills that are actually used. |
299
+ | **Intake** | 0.20 | Structural health: frontmatter fields present, H1 present, minimum body length, description length. Zero if `intake_fail` floor is active. |
300
+ | **Graph** | 0.25 | Connectivity in the knowledge graph: degree, average edge weight, community size |
301
+ | **Routing** | 0.15 | Router hit rate from `~/.claude/router-trace.jsonl`: how often this skill was among the top-K recommendations when surfaced |
302
+
303
+ The final score is `sum(weight[i] * signal[i])`. A hard floor
304
+ (`never_loaded_stale`, `intake_fail`) can override the score to
305
+ force an F grade regardless of other signals.
306
+
307
+ The skill detail page also shows the audit timeline for this slug
308
+ specifically: every `skill.loaded`, `skill.unloaded`,
309
+ `skill.score_updated` row with its session_id, so you can trace
310
+ exactly why the score changed when it did.
311
+
312
+ ### On `/session/<id>`
313
+
314
+ The per-session view lets you watch a skill's lifecycle inside one
315
+ session:
316
+
317
+ ```
318
+ skill.loaded fastapi-pro session-abc @ 10:23:05
319
+ skill.score_updated fastapi-pro session-abc @ 10:31:47 grade C->B
320
+ skill.unloaded fastapi-pro session-abc @ 11:04:02
321
+ ```
322
+
323
+ The `load score_updated unload` triad is the canonical
324
+ observability proof that ctx's telemetry pipeline is live.
325
+
326
+ ## Security
327
+
328
+ - **Binds to 127.0.0.1 by default**. Use `--host 0.0.0.0` only if
329
+ you actually want LAN-visible read-only access. The startup output
330
+ prints a one-process read-token URL; without that token or the cookie
331
+ it sets, LAN HTML/API/SSE requests return 403. Mutations remain
332
+ disabled on non-loopback binds.
333
+ - **Same-origin gating on mutation**. Any POST with an `Origin`
334
+ header that doesn't match `Host` returns 403. Curl and direct
335
+ tool calls are allowed (no Origin header at all).
336
+ - **Slug allowlist on all paths**. Anywhere the dashboard resolves
337
+ a skill, agent, MCP, or harness slug to a file path (`/wiki/<slug>`,
338
+ `/graph?slug=<slug>&type=<entity>`, `/api/graph/<slug>.json`), the slug is
339
+ validated through the shared
340
+ safe-name helper — no path traversal, no absolute paths, no UNC
341
+ shares, no Windows reserved device names.
342
+
343
+ ## Stopping
344
+
345
+ Ctrl+C in the terminal. Request handling is threaded for local dashboard
346
+ responsiveness, and shutdown signals any open SSE workers. The monitor is
347
+ still not suitable for shared/production serving.
docs/entity-onboarding.md CHANGED
@@ -1,394 +1,394 @@
1
- # Entity Onboarding
2
-
3
- ctx treats skills, agents, MCP servers, and harnesses as wiki entities that can
4
- be indexed, linked in the knowledge graph, and recommended from the same
5
- surface. The important distinction is install behavior:
6
-
7
- - Skills and agents are local Claude Code assets.
8
- - MCP servers are recorded first, then installed only when the user opts in.
9
- - Harnesses are recorded first. A harness describes the machinery around the
10
- model: runtime, tools, access boundaries, memory, verification, and approval
11
- policy. Adding one never executes upstream setup commands.
12
-
13
- After adding any entity, drain the durable wiki queue when you want the local
14
- runtime graph to see it immediately:
15
-
16
- ```bash
17
- ctx-wiki-worker --wiki ~/.claude/skill-wiki --limit 1
18
- ctx-scan-repo --repo . --recommend
19
- ```
20
-
21
- If a persisted semantic vector index exists, that worker pass also runs a
22
- best-effort incremental attach into `graphify-out/entity-overlays.jsonl` so the
23
- new entity can connect to existing graph nodes without a full all-pairs
24
- semantic rebuild. The wiki page remains the source of truth; if incremental
25
- attach is skipped or fails, the worker still queues the normal incremental
26
- graph export job.
27
-
28
- ## Updating the Graph and LLM Wiki
29
-
30
- Use this sequence for every accepted skill, agent, MCP server, or harness
31
- change. The graph and LLM-wiki are shippable artifacts, not scratch output, so
32
- the update is treated like a release step.
33
-
34
- 1. Add or update the entity through the matching command:
35
- `ctx-skill-add`, `ctx-agent-add`, `ctx-mcp-add`, or `ctx-harness-add`.
36
- 2. If the entity already exists, read the update review. It lists changed
37
- fields, likely benefits, regressions, and security findings. Do not pass
38
- `--update-existing` until those findings are acceptable.
39
- 3. Run the security/cyber check below.
40
- 4. Park heavyweight graph artifacts locally before rebuilds:
41
- `python scripts/graph_artifact_guard.py park`. This keeps background Git
42
- integrations from repeatedly LFS-cleaning the full wiki tarball while it is
43
- still changing.
44
- 5. Drain the wiki queue for local runtime use:
45
- `ctx-wiki-worker --wiki ~/.claude/skill-wiki --limit 1`. This updates the
46
- wiki index, attempts incremental ANN graph attach when a vector index exists,
47
- and queues the normal incremental graph export.
48
- 6. Rebuild the curated wiki graph with `ctx-wiki-graphify` before shipping
49
- release artifacts or when you need a full graph/export reconciliation.
50
- 7. Repack `graph/wiki-graph.tar.gz` through the artifact promotion path:
51
- write a staged tarball, validate it, atomically promote it, and keep the
52
- generated `*.promotion.json` metadata with the previous/current hashes.
53
- Never commit local review reports or raw caches.
54
- 8. Refresh the bulk skill index when shipping large skill updates.
55
- This adds first-class `skill` nodes, skill pages under `entities/skills/`, install
56
- commands, duplicate hints, and metadata-only quality/security signals:
57
-
58
- ```bash
59
- python src/import_skills_sh_catalog.py --from-api-union <raw.json> \
60
- --catalog-out graph/<skill-index>.json.gz \
61
- --wiki-tar graph/wiki-graph.tar.gz \
62
- --update-wiki-tar
63
- ```
64
- 9. Refresh published counts with `python src/update_repo_stats.py`.
65
- 10. Verify the changed entity can be recommended through
66
- `ctx-scan-repo --repo . --recommend` or `ctx__recommend_bundle`.
67
- 11. Unpark and stage the graph artifacts once the release candidate is final:
68
- `python scripts/graph_artifact_guard.py unpark`, then `git add` the graph
69
- artifacts intentionally. Run `python scripts/graph_artifact_guard.py prune`
70
- after interrupted Git/LFS runs or after release staging to clean prunable
71
- local LFS cache entries. Add `--include-git-prune` only when you explicitly
72
- want repo-wide dangling Git objects removed too.
73
-
74
- The durable wiki worker drains `entity-upsert`, `graph-export`,
75
- `skill-index-refresh`, `tar-refresh`, and `artifact-promotion` jobs. Use
76
- `ctx-wiki-worker --wiki ~/.claude/skill-wiki --limit 1` for a controlled
77
- single-job drain, or omit `--limit` to drain the ready queue.
78
-
79
- For a manual attach dry-run against an existing vector index:
80
-
81
- ```bash
82
- ctx-incremental-attach attach \
83
- --index-dir ~/.claude/skill-wiki/.embedding-cache/graph/vector-index \
84
- --overlay ~/.claude/skill-wiki/graphify-out/entity-overlays.jsonl \
85
- --node-id skill:fastapi-review \
86
- --type skill \
87
- --label fastapi-review \
88
- --text-file ~/.claude/skill-wiki/entities/skills/fastapi-review.md \
89
- --dry-run
90
- ```
91
-
92
- Use `ctx-incremental-attach calibrate --graph ~/.claude/skill-wiki/graphify-out/graph.json`
93
- to inspect the current graph's semantic and degree distributions before
94
- changing attach thresholds.
95
-
96
- Validate the attach quality before relying on a new ANN backend or changed
97
- threshold:
98
-
99
- ```bash
100
- ctx-incremental-shadow \
101
- --index-dir ~/.claude/skill-wiki/.embedding-cache/graph/vector-index \
102
- --graph ~/.claude/skill-wiki/graphify-out/graph.json \
103
- --sample-size 100 \
104
- --min-overlap 0.85
105
- ```
106
-
107
- The shadow gate pretends sampled existing nodes are new, compares incremental
108
- attach neighbors to batch graph semantic neighbors, reports precision/recall
109
- for top 5/10/20, score deltas, and bad examples, then exits non-zero if
110
- recall at the largest top-k is below the overlap floor.
111
-
112
- ## Repair Incremental Attach
113
-
114
- If the worker says `incremental attach skipped (no vector index)`, build the
115
- persisted semantic index once:
116
-
117
- ```bash
118
- ctx-wiki-graphify \
119
- --wiki-dir ~/.claude/skill-wiki \
120
- --incremental \
121
- --graph-only \
122
- --semantic-vector-index numpy-flat
123
- ```
124
-
125
- `numpy-flat` is exact and portable. `--semantic-vector-index auto` keeps the
126
- portable exact backend at this graph size and can switch to the optional ANN
127
- backend only above the configured node threshold. `hnswlib` is optional and
128
- should be shadow-gated before release use.
129
-
130
- Then process pending entity updates:
131
-
132
- ```bash
133
- ctx-wiki-worker --wiki ~/.claude/skill-wiki
134
- ```
135
-
136
- That is the supported "attach pending" flow today: the queue is durable, so
137
- failed or skipped entity-upsert jobs remain visible to the worker and can be
138
- retried after the index exists. Use manual `ctx-incremental-attach attach
139
- --dry-run` for one-off debugging, not as the normal bulk path.
140
-
141
- ## Security and Cyber Check
142
-
143
- Run this before applying `--update-existing`, before installing a harness with
144
- approved commands, and before shipping a refreshed graph tarball.
145
-
146
- - Inspect changed entity markdown and frontmatter for shell commands, setup
147
- commands, install commands, URLs, requested permissions, and model/provider
148
- access.
149
- - Treat these as manual-review blockers: `curl | sh`, `wget | bash`,
150
- `Invoke-Expression`, broad `rm -rf`, `git reset --hard`, `chmod 777`, secret
151
- upload, disabled auth/TLS/sandboxing/audit/tests, or unpinned package sources.
152
- - For MCP and harness updates, check network access, filesystem scope, auth
153
- material, command transports, and whether setup or verify commands execute
154
- remote code.
155
- - Prefer dry-run first: `ctx-harness-install <slug> --dry-run` and
156
- `ctx-harness-install <slug> --update --dry-run`.
157
- - If a candidate is useful but risky, document the safer install path or keep it
158
- as metadata instead of shipping it as an installed skill.
159
-
160
- ## Updating an Existing Entity
161
-
162
- The add commands are non-destructive by default when the target skill, agent,
163
- MCP server, or harness already exists. The first add attempt prints an update
164
- review instead of replacing files. That review lists changed fields, expected
165
- benefits, possible regressions, security findings, and a recommendation.
166
-
167
- Use this flow for every entity type:
168
-
169
- 1. Run the normal add command.
170
- 2. If ctx prints `Existing <type> already exists`, read the benefits and risks.
171
- 3. Keep the current entity by doing nothing, or re-run with `--skip-existing`
172
- in batch jobs where you do not want reviews.
173
- 4. Apply the replacement only after review with `--update-existing`.
174
- 5. Drain the queue with `ctx-wiki-worker --wiki ~/.claude/skill-wiki --limit 1`
175
- for immediate local recommendation use, or rebuild with `ctx-wiki-graphify`
176
- when the update should be reconciled into shipped graph artifacts.
177
-
178
- Examples:
179
-
180
- ```bash
181
- ctx-skill-add --skill-path ./SKILL.md --name fastapi-review
182
- ctx-skill-add --skill-path ./SKILL.md --name fastapi-review --update-existing
183
-
184
- ctx-agent-add --agent-path ./code-reviewer.md --name code-reviewer
185
- ctx-agent-add --agent-path ./code-reviewer.md --name code-reviewer --update-existing
186
-
187
- ctx-mcp-add --from-json ./github-mcp.json
188
- ctx-mcp-add --from-json ./github-mcp.json --update-existing
189
-
190
- ctx-harness-add --from-json ./text-to-cad-harness.json
191
- ctx-harness-add --from-json ./text-to-cad-harness.json --update-existing
192
- ```
193
-
194
- `ctx-harness-install --update` is different: it refreshes an installed harness
195
- checkout under `~/.claude/harnesses/<slug>`. Catalog entity replacement uses
196
- `ctx-harness-add --update-existing`.
197
-
198
- ## Removing or Retiring an Entity
199
-
200
- Removal has three separate meanings. First decide which one you need.
201
-
202
- - **Catalog removal** stops ctx from showing the entity in the wiki, graph, and
203
- recommendations. Use the dashboard: `ctx-monitor serve`, open **Manage**,
204
- search for the slug and type, then choose **Delete selected**. This deletes
205
- the wiki page and queues an `entity-upsert` delete plus `graph-export` job.
206
- - **Runtime unload** removes a currently loaded entity from the live manifest.
207
- Use the dashboard **Loaded** page. MCP unloads call the Claude MCP removal
208
- path when available; skill and agent unloads remove the manifest row.
209
- - **Installed-file removal** is type-specific. Use
210
- `ctx-harness-install <slug> --uninstall` for harness checkouts,
211
- `ctx-mcp-uninstall <slug>` for installed MCPs, and `ctx-lifecycle archive`
212
- then `ctx-lifecycle purge` for stale local skills that should be deleted
213
- after the configured grace period.
214
-
215
- After deleting an entity page, drain or rebuild before trusting recommendation
216
- results:
217
-
218
- ```bash
219
- ctx-wiki-worker --wiki ~/.claude/skill-wiki --limit 1
220
- ctx-scan-repo --repo . --recommend
221
- ```
222
-
223
- If you need an auditable manual flow without the browser, use the dashboard
224
- local API only from loopback with the per-process monitor token printed into
225
- the served page. The API route is `POST /api/entity/delete` with
226
- `{"slug": "...", "entity_type": "skill|agent|mcp-server|harness"}`.
227
-
228
- ## Add a Skill
229
-
230
- Use this when you have a local `SKILL.md` that should be installed under
231
- `~/.claude/skills/<name>/SKILL.md` and mirrored into the wiki.
232
-
233
- ```bash
234
- ctx-skill-add \
235
- --skill-path ./SKILL.md \
236
- --name fastapi-review
237
- ```
238
-
239
- What happens:
240
-
241
- 1. The name is validated.
242
- 2. Intake checks run against the markdown.
243
- 3. The skill is copied into `~/.claude/skills/`.
244
- 4. A wiki page is created under `entities/skills/`.
245
- 5. The wiki index and log are updated.
246
-
247
- ## Add an Agent
248
-
249
- Use this when you have a local Claude Code agent markdown file.
250
-
251
- ```bash
252
- ctx-agent-add \
253
- --agent-path ./code-reviewer.md \
254
- --name code-reviewer
255
- ```
256
-
257
- Batch-add every top-level `.md` file in a directory:
258
-
259
- ```bash
260
- ctx-agent-add --scan-dir ./agents --skip-existing
261
- ```
262
-
263
- Agents are copied into `~/.claude/agents/` and mirrored into
264
- `entities/agents/`. Re-run `ctx-wiki-graphify` after adding agents if you want
265
- graph recommendations to include them.
266
-
267
- ## Add an MCP Server
268
-
269
- Use this when you want the MCP server available as a recommendation before
270
- installing it into a host.
271
-
272
- Create `github-mcp.json`:
273
-
274
- ```json
275
- {
276
- "name": "GitHub MCP",
277
- "slug": "github-mcp",
278
- "description": "MCP server for GitHub repository and issue workflows.",
279
- "github_url": "https://github.com/modelcontextprotocol/servers",
280
- "sources": ["manual"],
281
- "tags": ["github", "automation", "repository"],
282
- "transports": ["stdio"]
283
- }
284
- ```
285
-
286
- Add it:
287
-
288
- ```bash
289
- ctx-mcp-add --from-json ./github-mcp.json
290
- ```
291
-
292
- MCP pages live under `entities/mcp-servers/<shard>/<slug>.md`. The add command
293
- detects existing pages by slug and, when possible, canonical GitHub URL. If a
294
- match exists, ctx prints the update review and skips replacement unless
295
- `--update-existing` is passed.
296
-
297
- ## Add a Harness
298
-
299
- Use this when a repo provides the runtime around a model rather than just a
300
- tool. Harness examples include coding-agent loops, CAD-generation runtimes,
301
- browser-automation runners, evaluation loops, and local-model workbenches.
302
-
303
- Example: add `earthtojake/text-to-cad` as a harness recommendation.
304
-
305
- ```bash
306
- ctx-harness-add \
307
- --repo https://github.com/earthtojake/text-to-cad \
308
- --name "Text to CAD" \
309
- --description "Harness for turning text prompts into CAD artifacts." \
310
- --tag cad --tag 3d --tag automation \
311
- --model-provider openai \
312
- --runtime python \
313
- --capability "Generate CAD artifacts from natural language" \
314
- --setup-command "pip install -e ." \
315
- --verify-command "pytest"
316
- ```
317
-
318
- Or load one JSON record:
319
-
320
- ```json
321
- {
322
- "repo_url": "https://github.com/earthtojake/text-to-cad",
323
- "name": "Text to CAD",
324
- "description": "Harness for turning text prompts into CAD artifacts.",
325
- "tags": ["cad", "3d", "automation"],
326
- "model_providers": ["openai"],
327
- "runtimes": ["python"],
328
- "capabilities": ["Generate CAD artifacts from natural language"],
329
- "setup_commands": ["pip install -e ."],
330
- "verify_commands": ["pytest"],
331
- "sources": ["manual"]
332
- }
333
- ```
334
-
335
- ```bash
336
- ctx-harness-add --from-json ./text-to-cad-harness.json
337
- ```
338
-
339
- Harness pages live under `entities/harnesses/<slug>.md`. Setup and verification
340
- commands are documentation only; ctx records them so the user can inspect and
341
- decide before running anything.
342
-
343
- To inspect and install a harness:
344
-
345
- ```bash
346
- ctx-harness-install text-to-cad --dry-run
347
- ctx-harness-install text-to-cad
348
- ctx-harness-install text-to-cad --update --dry-run
349
- ctx-harness-install text-to-cad --uninstall --dry-run
350
- ```
351
-
352
- The installer clones or copies the harness into `~/.claude/harnesses/<slug>` and
353
- writes `~/.claude/harness-installs/<slug>.json`. It does not run setup commands
354
- unless you pass `--approve-commands`, and it does not run verification commands
355
- unless you also pass `--run-verify`.
356
-
357
- ```bash
358
- ctx-harness-install text-to-cad --approve-commands --run-verify
359
- ctx-harness-install text-to-cad --update --approve-commands --run-verify
360
- ctx-harness-install text-to-cad --uninstall
361
- ctx-harness-install text-to-cad --uninstall --keep-files
362
- ```
363
-
364
- ## Initialize Model Choice
365
-
366
- During setup, record whether you use Claude Code or your own model. Plain
367
- `ctx-init` starts a small wizard when it is attached to an interactive
368
- terminal; use `ctx-init --wizard` to force the prompts, or pass explicit flags
369
- such as `--model-mode skip` for non-interactive automation.
370
-
371
- ```bash
372
- ctx-init
373
- ctx-init --wizard
374
- ctx-init --model-mode skip
375
- ```
376
-
377
- For Claude Code:
378
-
379
- ```bash
380
- ctx-init --model-mode claude-code --goal "maintain a FastAPI service"
381
- ```
382
-
383
- For a custom model:
384
-
385
- ```bash
386
- ctx-init \
387
- --model-mode custom \
388
- --model openai/gpt-5.5 \
389
- --goal "build CAD artifacts from text prompts"
390
- ```
391
-
392
- Add `--validate-model` only when you want `ctx-init` to make one small provider
393
- call. Without that flag, setup writes `~/.claude/ctx-model-profile.json` and
394
- prints harness recommendations without calling the model.
 
1
+ # Entity Onboarding
2
+
3
+ ctx treats skills, agents, MCP servers, and harnesses as wiki entities that can
4
+ be indexed, linked in the knowledge graph, and recommended from the same
5
+ surface. The important distinction is install behavior:
6
+
7
+ - Skills and agents are local Claude Code assets.
8
+ - MCP servers are recorded first, then installed only when the user opts in.
9
+ - Harnesses are recorded first. A harness describes the machinery around the
10
+ model: runtime, tools, access boundaries, memory, verification, and approval
11
+ policy. Adding one never executes upstream setup commands.
12
+
13
+ After adding any entity, drain the durable wiki queue when you want the local
14
+ runtime graph to see it immediately:
15
+
16
+ ```bash
17
+ ctx-wiki-worker --wiki ~/.claude/skill-wiki --limit 1
18
+ ctx-scan-repo --repo . --recommend
19
+ ```
20
+
21
+ If a persisted semantic vector index exists, that worker pass also runs a
22
+ best-effort incremental attach into `graphify-out/entity-overlays.jsonl` so the
23
+ new entity can connect to existing graph nodes without a full all-pairs
24
+ semantic rebuild. The wiki page remains the source of truth; if incremental
25
+ attach is skipped or fails, the worker still queues the normal incremental
26
+ graph export job.
27
+
28
+ ## Updating the Graph and LLM Wiki
29
+
30
+ Use this sequence for every accepted skill, agent, MCP server, or harness
31
+ change. The graph and LLM-wiki are shippable artifacts, not scratch output, so
32
+ the update is treated like a release step.
33
+
34
+ 1. Add or update the entity through the matching command:
35
+ `ctx-skill-add`, `ctx-agent-add`, `ctx-mcp-add`, or `ctx-harness-add`.
36
+ 2. If the entity already exists, read the update review. It lists changed
37
+ fields, likely benefits, regressions, and security findings. Do not pass
38
+ `--update-existing` until those findings are acceptable.
39
+ 3. Run the security/cyber check below.
40
+ 4. Park heavyweight graph artifacts locally before rebuilds:
41
+ `python scripts/graph_artifact_guard.py park`. This keeps background Git
42
+ integrations from repeatedly LFS-cleaning the full wiki tarball while it is
43
+ still changing.
44
+ 5. Drain the wiki queue for local runtime use:
45
+ `ctx-wiki-worker --wiki ~/.claude/skill-wiki --limit 1`. This updates the
46
+ wiki index, attempts incremental ANN graph attach when a vector index exists,
47
+ and queues the normal incremental graph export.
48
+ 6. Rebuild the curated wiki graph with `ctx-wiki-graphify` before shipping
49
+ release artifacts or when you need a full graph/export reconciliation.
50
+ 7. Repack `graph/wiki-graph.tar.gz` through the artifact promotion path:
51
+ write a staged tarball, validate it, atomically promote it, and keep the
52
+ generated `*.promotion.json` metadata with the previous/current hashes.
53
+ Never commit local review reports or raw caches.
54
+ 8. Refresh the bulk skill index when shipping large skill updates.
55
+ This adds first-class `skill` nodes, skill pages under `entities/skills/`, install
56
+ commands, duplicate hints, and metadata-only quality/security signals:
57
+
58
+ ```bash
59
+ python src/import_skills_sh_catalog.py --from-api-union <raw.json> \
60
+ --catalog-out graph/<skill-index>.json.gz \
61
+ --wiki-tar graph/wiki-graph.tar.gz \
62
+ --update-wiki-tar
63
+ ```
64
+ 9. Refresh published counts with `python src/update_repo_stats.py`.
65
+ 10. Verify the changed entity can be recommended through
66
+ `ctx-scan-repo --repo . --recommend` or `ctx__recommend_bundle`.
67
+ 11. Unpark and stage the graph artifacts once the release candidate is final:
68
+ `python scripts/graph_artifact_guard.py unpark`, then `git add` the graph
69
+ artifacts intentionally. Run `python scripts/graph_artifact_guard.py prune`
70
+ after interrupted Git/LFS runs or after release staging to clean prunable
71
+ local LFS cache entries. Add `--include-git-prune` only when you explicitly
72
+ want repo-wide dangling Git objects removed too.
73
+
74
+ The durable wiki worker drains `entity-upsert`, `graph-export`,
75
+ `skill-index-refresh`, `tar-refresh`, and `artifact-promotion` jobs. Use
76
+ `ctx-wiki-worker --wiki ~/.claude/skill-wiki --limit 1` for a controlled
77
+ single-job drain, or omit `--limit` to drain the ready queue.
78
+
79
+ For a manual attach dry-run against an existing vector index:
80
+
81
+ ```bash
82
+ ctx-incremental-attach attach \
83
+ --index-dir ~/.claude/skill-wiki/.embedding-cache/graph/vector-index \
84
+ --overlay ~/.claude/skill-wiki/graphify-out/entity-overlays.jsonl \
85
+ --node-id skill:fastapi-review \
86
+ --type skill \
87
+ --label fastapi-review \
88
+ --text-file ~/.claude/skill-wiki/entities/skills/fastapi-review.md \
89
+ --dry-run
90
+ ```
91
+
92
+ Use `ctx-incremental-attach calibrate --graph ~/.claude/skill-wiki/graphify-out/graph.json`
93
+ to inspect the current graph's semantic and degree distributions before
94
+ changing attach thresholds.
95
+
96
+ Validate the attach quality before relying on a new ANN backend or changed
97
+ threshold:
98
+
99
+ ```bash
100
+ ctx-incremental-shadow \
101
+ --index-dir ~/.claude/skill-wiki/.embedding-cache/graph/vector-index \
102
+ --graph ~/.claude/skill-wiki/graphify-out/graph.json \
103
+ --sample-size 100 \
104
+ --min-overlap 0.85
105
+ ```
106
+
107
+ The shadow gate pretends sampled existing nodes are new, compares incremental
108
+ attach neighbors to batch graph semantic neighbors, reports precision/recall
109
+ for top 5/10/20, score deltas, and bad examples, then exits non-zero if
110
+ recall at the largest top-k is below the overlap floor.
111
+
112
+ ## Repair Incremental Attach
113
+
114
+ If the worker says `incremental attach skipped (no vector index)`, build the
115
+ persisted semantic index once:
116
+
117
+ ```bash
118
+ ctx-wiki-graphify \
119
+ --wiki-dir ~/.claude/skill-wiki \
120
+ --incremental \
121
+ --graph-only \
122
+ --semantic-vector-index numpy-flat
123
+ ```
124
+
125
+ `numpy-flat` is exact and portable. `--semantic-vector-index auto` keeps the
126
+ portable exact backend at this graph size and can switch to the optional ANN
127
+ backend only above the configured node threshold. `hnswlib` is optional and
128
+ should be shadow-gated before release use.
129
+
130
+ Then process pending entity updates:
131
+
132
+ ```bash
133
+ ctx-wiki-worker --wiki ~/.claude/skill-wiki
134
+ ```
135
+
136
+ That is the supported "attach pending" flow today: the queue is durable, so
137
+ failed or skipped entity-upsert jobs remain visible to the worker and can be
138
+ retried after the index exists. Use manual `ctx-incremental-attach attach
139
+ --dry-run` for one-off debugging, not as the normal bulk path.
140
+
141
+ ## Security and Cyber Check
142
+
143
+ Run this before applying `--update-existing`, before installing a harness with
144
+ approved commands, and before shipping a refreshed graph tarball.
145
+
146
+ - Inspect changed entity markdown and frontmatter for shell commands, setup
147
+ commands, install commands, URLs, requested permissions, and model/provider
148
+ access.
149
+ - Treat these as manual-review blockers: `curl | sh`, `wget | bash`,
150
+ `Invoke-Expression`, broad `rm -rf`, `git reset --hard`, `chmod 777`, secret
151
+ upload, disabled auth/TLS/sandboxing/audit/tests, or unpinned package sources.
152
+ - For MCP and harness updates, check network access, filesystem scope, auth
153
+ material, command transports, and whether setup or verify commands execute
154
+ remote code.
155
+ - Prefer dry-run first: `ctx-harness-install <slug> --dry-run` and
156
+ `ctx-harness-install <slug> --update --dry-run`.
157
+ - If a candidate is useful but risky, document the safer install path or keep it
158
+ as metadata instead of shipping it as an installed skill.
159
+
160
+ ## Updating an Existing Entity
161
+
162
+ The add commands are non-destructive by default when the target skill, agent,
163
+ MCP server, or harness already exists. The first add attempt prints an update
164
+ review instead of replacing files. That review lists changed fields, expected
165
+ benefits, possible regressions, security findings, and a recommendation.
166
+
167
+ Use this flow for every entity type:
168
+
169
+ 1. Run the normal add command.
170
+ 2. If ctx prints `Existing <type> already exists`, read the benefits and risks.
171
+ 3. Keep the current entity by doing nothing, or re-run with `--skip-existing`
172
+ in batch jobs where you do not want reviews.
173
+ 4. Apply the replacement only after review with `--update-existing`.
174
+ 5. Drain the queue with `ctx-wiki-worker --wiki ~/.claude/skill-wiki --limit 1`
175
+ for immediate local recommendation use, or rebuild with `ctx-wiki-graphify`
176
+ when the update should be reconciled into shipped graph artifacts.
177
+
178
+ Examples:
179
+
180
+ ```bash
181
+ ctx-skill-add --skill-path ./SKILL.md --name fastapi-review
182
+ ctx-skill-add --skill-path ./SKILL.md --name fastapi-review --update-existing
183
+
184
+ ctx-agent-add --agent-path ./code-reviewer.md --name code-reviewer
185
+ ctx-agent-add --agent-path ./code-reviewer.md --name code-reviewer --update-existing
186
+
187
+ ctx-mcp-add --from-json ./github-mcp.json
188
+ ctx-mcp-add --from-json ./github-mcp.json --update-existing
189
+
190
+ ctx-harness-add --from-json ./text-to-cad-harness.json
191
+ ctx-harness-add --from-json ./text-to-cad-harness.json --update-existing
192
+ ```
193
+
194
+ `ctx-harness-install --update` is different: it refreshes an installed harness
195
+ checkout under `~/.claude/harnesses/<slug>`. Catalog entity replacement uses
196
+ `ctx-harness-add --update-existing`.
197
+
198
+ ## Removing or Retiring an Entity
199
+
200
+ Removal has three separate meanings. First decide which one you need.
201
+
202
+ - **Catalog removal** stops ctx from showing the entity in the wiki, graph, and
203
+ recommendations. Use the dashboard: `ctx-monitor serve`, open **Manage**,
204
+ search for the slug and type, then choose **Delete selected**. This deletes
205
+ the wiki page and queues an `entity-upsert` delete plus `graph-export` job.
206
+ - **Runtime unload** removes a currently loaded entity from the live manifest.
207
+ Use the dashboard **Loaded** page. MCP unloads call the Claude MCP removal
208
+ path when available; skill and agent unloads remove the manifest row.
209
+ - **Installed-file removal** is type-specific. Use
210
+ `ctx-harness-install <slug> --uninstall` for harness checkouts,
211
+ `ctx-mcp-uninstall <slug>` for installed MCPs, and `ctx-lifecycle archive`
212
+ then `ctx-lifecycle purge` for stale local skills that should be deleted
213
+ after the configured grace period.
214
+
215
+ After deleting an entity page, drain or rebuild before trusting recommendation
216
+ results:
217
+
218
+ ```bash
219
+ ctx-wiki-worker --wiki ~/.claude/skill-wiki --limit 1
220
+ ctx-scan-repo --repo . --recommend
221
+ ```
222
+
223
+ If you need an auditable manual flow without the browser, use the dashboard
224
+ local API only from loopback with the per-process monitor token printed into
225
+ the served page. The API route is `POST /api/entity/delete` with
226
+ `{"slug": "...", "entity_type": "skill|agent|mcp-server|harness"}`.
227
+
228
+ ## Add a Skill
229
+
230
+ Use this when you have a local `SKILL.md` that should be installed under
231
+ `~/.claude/skills/<name>/SKILL.md` and mirrored into the wiki.
232
+
233
+ ```bash
234
+ ctx-skill-add \
235
+ --skill-path ./SKILL.md \
236
+ --name fastapi-review
237
+ ```
238
+
239
+ What happens:
240
+
241
+ 1. The name is validated.
242
+ 2. Intake checks run against the markdown.
243
+ 3. The skill is copied into `~/.claude/skills/`.
244
+ 4. A wiki page is created under `entities/skills/`.
245
+ 5. The wiki index and log are updated.
246
+
247
+ ## Add an Agent
248
+
249
+ Use this when you have a local Claude Code agent markdown file.
250
+
251
+ ```bash
252
+ ctx-agent-add \
253
+ --agent-path ./code-reviewer.md \
254
+ --name code-reviewer
255
+ ```
256
+
257
+ Batch-add every top-level `.md` file in a directory:
258
+
259
+ ```bash
260
+ ctx-agent-add --scan-dir ./agents --skip-existing
261
+ ```
262
+
263
+ Agents are copied into `~/.claude/agents/` and mirrored into
264
+ `entities/agents/`. Re-run `ctx-wiki-graphify` after adding agents if you want
265
+ graph recommendations to include them.
266
+
267
+ ## Add an MCP Server
268
+
269
+ Use this when you want the MCP server available as a recommendation before
270
+ installing it into a host.
271
+
272
+ Create `github-mcp.json`:
273
+
274
+ ```json
275
+ {
276
+ "name": "GitHub MCP",
277
+ "slug": "github-mcp",
278
+ "description": "MCP server for GitHub repository and issue workflows.",
279
+ "github_url": "https://github.com/modelcontextprotocol/servers",
280
+ "sources": ["manual"],
281
+ "tags": ["github", "automation", "repository"],
282
+ "transports": ["stdio"]
283
+ }
284
+ ```
285
+
286
+ Add it:
287
+
288
+ ```bash
289
+ ctx-mcp-add --from-json ./github-mcp.json
290
+ ```
291
+
292
+ MCP pages live under `entities/mcp-servers/<shard>/<slug>.md`. The add command
293
+ detects existing pages by slug and, when possible, canonical GitHub URL. If a
294
+ match exists, ctx prints the update review and skips replacement unless
295
+ `--update-existing` is passed.
296
+
297
+ ## Add a Harness
298
+
299
+ Use this when a repo provides the runtime around a model rather than just a
300
+ tool. Harness examples include coding-agent loops, CAD-generation runtimes,
301
+ browser-automation runners, evaluation loops, and local-model workbenches.
302
+
303
+ Example: add `earthtojake/text-to-cad` as a harness recommendation.
304
+
305
+ ```bash
306
+ ctx-harness-add \
307
+ --repo https://github.com/earthtojake/text-to-cad \
308
+ --name "Text to CAD" \
309
+ --description "Harness for turning text prompts into CAD artifacts." \
310
+ --tag cad --tag 3d --tag automation \
311
+ --model-provider openai \
312
+ --runtime python \
313
+ --capability "Generate CAD artifacts from natural language" \
314
+ --setup-command "pip install -e ." \
315
+ --verify-command "pytest"
316
+ ```
317
+
318
+ Or load one JSON record:
319
+
320
+ ```json
321
+ {
322
+ "repo_url": "https://github.com/earthtojake/text-to-cad",
323
+ "name": "Text to CAD",
324
+ "description": "Harness for turning text prompts into CAD artifacts.",
325
+ "tags": ["cad", "3d", "automation"],
326
+ "model_providers": ["openai"],
327
+ "runtimes": ["python"],
328
+ "capabilities": ["Generate CAD artifacts from natural language"],
329
+ "setup_commands": ["pip install -e ."],
330
+ "verify_commands": ["pytest"],
331
+ "sources": ["manual"]
332
+ }
333
+ ```
334
+
335
+ ```bash
336
+ ctx-harness-add --from-json ./text-to-cad-harness.json
337
+ ```
338
+
339
+ Harness pages live under `entities/harnesses/<slug>.md`. Setup and verification
340
+ commands are documentation only; ctx records them so the user can inspect and
341
+ decide before running anything.
342
+
343
+ To inspect and install a harness:
344
+
345
+ ```bash
346
+ ctx-harness-install text-to-cad --dry-run
347
+ ctx-harness-install text-to-cad
348
+ ctx-harness-install text-to-cad --update --dry-run
349
+ ctx-harness-install text-to-cad --uninstall --dry-run
350
+ ```
351
+
352
+ The installer clones or copies the harness into `~/.claude/harnesses/<slug>` and
353
+ writes `~/.claude/harness-installs/<slug>.json`. It does not run setup commands
354
+ unless you pass `--approve-commands`, and it does not run verification commands
355
+ unless you also pass `--run-verify`.
356
+
357
+ ```bash
358
+ ctx-harness-install text-to-cad --approve-commands --run-verify
359
+ ctx-harness-install text-to-cad --update --approve-commands --run-verify
360
+ ctx-harness-install text-to-cad --uninstall
361
+ ctx-harness-install text-to-cad --uninstall --keep-files
362
+ ```
363
+
364
+ ## Initialize Model Choice
365
+
366
+ During setup, record whether you use Claude Code or your own model. Plain
367
+ `ctx-init` starts a small wizard when it is attached to an interactive
368
+ terminal; use `ctx-init --wizard` to force the prompts, or pass explicit flags
369
+ such as `--model-mode skip` for non-interactive automation.
370
+
371
+ ```bash
372
+ ctx-init
373
+ ctx-init --wizard
374
+ ctx-init --model-mode skip
375
+ ```
376
+
377
+ For Claude Code:
378
+
379
+ ```bash
380
+ ctx-init --model-mode claude-code --goal "maintain a FastAPI service"
381
+ ```
382
+
383
+ For a custom model:
384
+
385
+ ```bash
386
+ ctx-init \
387
+ --model-mode custom \
388
+ --model openai/gpt-5.5 \
389
+ --goal "build CAD artifacts from text prompts"
390
+ ```
391
+
392
+ Add `--validate-model` only when you want `ctx-init` to make one small provider
393
+ call. Without that flag, setup writes `~/.claude/ctx-model-profile.json` and
394
+ prints harness recommendations without calling the model.
docs/harness/attaching-to-hosts.md CHANGED
@@ -1,289 +1,289 @@
1
- # Attaching ctx to any LLM host
2
-
3
- `ctx` ships three integration surfaces. Pick based on what your host
4
- already supports:
5
-
6
- | Your host | Use |
7
- |---|---|
8
- | MCP-native (Claude Code, Claude Agent SDK, Cline, Goose, OpenHands, Continue) | **MCP server** — no Python, just spawn `ctx-mcp-server` |
9
- | Anything that isn't MCP-native but runs Python | **Python library** — `from ctx import recommend_bundle, ...` |
10
- | "I just want to run an agent and get recommendations" | **`ctx run` CLI** — our built-in harness |
11
-
12
- All three paths consume the **same** knowledge graph, llm-wiki, and
13
- quality scoring. Recommendations are identical; only the transport
14
- differs.
15
-
16
- ---
17
-
18
- ## 1. MCP server path
19
-
20
- Install ctx with the harness extras:
21
-
22
- ```bash
23
- pip install "claude-ctx[harness]"
24
- ```
25
-
26
- This puts `ctx-mcp-server` on your PATH. Then wire it into your host:
27
-
28
- ### Claude Code
29
-
30
- ```bash
31
- claude mcp add ctx-wiki -- ctx-mcp-server
32
- ```
33
-
34
- The tools `ctx__recommend_bundle`, `ctx__graph_query`, `ctx__wiki_search`,
35
- `ctx__wiki_get` appear to Claude on the next turn. Ask
36
- "What skills help with FastAPI auth?" and it will call them.
37
-
38
- ### Claude Agent SDK (Python)
39
-
40
- ```python
41
- from anthropic import Anthropic
42
- from claude_agent_sdk import ClaudeAgentOptions, McpServerConfig
43
-
44
- options = ClaudeAgentOptions(
45
- mcp_servers={
46
- "ctx-wiki": McpServerConfig(
47
- command="ctx-mcp-server",
48
- ),
49
- },
50
- )
51
- ```
52
-
53
- ### Cline / Continue.dev
54
-
55
- Add to your MCP server config (`~/.config/cline/mcp.json` or the
56
- Continue equivalent):
57
-
58
- ```json
59
- {
60
- "mcpServers": {
61
- "ctx-wiki": {
62
- "command": "ctx-mcp-server"
63
- }
64
- }
65
- }
66
- ```
67
-
68
- ### Goose
69
-
70
- `~/.config/goose/config.yaml`:
71
-
72
- ```yaml
73
- extensions:
74
- ctx-wiki:
75
- type: stdio
76
- cmd: ctx-mcp-server
77
- ```
78
-
79
- ### OpenHands
80
-
81
- OpenHands' runtime config:
82
-
83
- ```json
84
- {
85
- "mcp_servers": {
86
- "ctx-wiki": {
87
- "command": "ctx-mcp-server"
88
- }
89
- }
90
- }
91
- ```
92
-
93
- ### Any MCP-speaking harness
94
-
95
- The server reads JSON-RPC 2.0 on stdin, writes on stdout, speaks
96
- MCP protocol version `2024-11-05`. Any client that does the standard
97
- `initialize` handshake + `tools/list` + `tools/call` flow works.
98
-
99
- ### Live MCP compatibility gate
100
-
101
- The regular test suite never starts arbitrary third-party MCP servers.
102
- Those commands run as local subprocesses and can read files, use the
103
- network, and inherit whatever environment you explicitly allow.
104
-
105
- To validate a trusted server, provide a local config and opt in:
106
-
107
- ```bash
108
- python -m pytest src/tests/test_mcp_live_compat.py \
109
- --run-live-mcp \
110
- --live-mcp-config /path/to/trusted-mcp.json
111
- ```
112
-
113
- Example config:
114
-
115
- ```json
116
- {
117
- "name": "trusted-filesystem",
118
- "command": "npx",
119
- "args": ["-y", "@modelcontextprotocol/server-filesystem", "${tmp_path}"],
120
- "startup_timeout": 30,
121
- "request_timeout": 10,
122
- "inherit_env": false,
123
- "env": {},
124
- "expected_tools": ["list_directory"],
125
- "probe": {
126
- "tool": "list_directory",
127
- "arguments": {"path": "."},
128
- "expect_text_contains": ""
129
- },
130
- "trust": {
131
- "server_is_third_party_code": true,
132
- "approved_by": "your-name"
133
- }
134
- }
135
- ```
136
-
137
- `command` and `args` are passed as an argv list, not through a shell.
138
- Parent secrets are not inherited unless you set `inherit_env: true`; prefer
139
- explicit `env` keys for servers that need credentials. `${tmp_path}` expands
140
- to a pytest temporary directory so filesystem probes can avoid real user data.
141
-
142
- ---
143
-
144
- ## 2. Python library path
145
-
146
- For custom harnesses that aren't MCP-native but can import Python:
147
-
148
- ```python
149
- from ctx import (
150
- recommend_bundle, # free-text → ranked skill/agent/MCP bundle
151
- graph_query, # walk from seed entities
152
- wiki_search, # keyword search entity pages
153
- wiki_get, # fetch one entity by slug
154
- list_all_entities, # enumerate every slug
155
- )
156
-
157
- # Inside your agent loop:
158
- def on_user_turn(query: str):
159
- bundle = recommend_bundle(query, top_k=5)
160
- for entry in bundle:
161
- print(f" [{entry['type']:>11}] {entry['name']} (score {entry['score']:.1f})")
162
-
163
- # User asks about a specific slug you saw in the bundle:
164
- page = wiki_get("fastapi-pro")
165
- if page:
166
- inject_into_context(page["body"])
167
- ```
168
-
169
- The first call to any of these lazy-loads the graph + wiki once;
170
- subsequent calls are O(walk) cheap. Safe to call from inside your
171
- own while-loop on every turn.
172
-
173
- Advanced: build a `CtxCoreToolbox` directly if you need to point at
174
- a non-default wiki/graph path:
175
-
176
- ```python
177
- from pathlib import Path
178
- from ctx import CtxCoreToolbox
179
-
180
- toolbox = CtxCoreToolbox(
181
- wiki_dir=Path("/path/to/custom/wiki"),
182
- graph_path=Path("/path/to/custom/graph.json"),
183
- )
184
- for td in toolbox.tool_definitions():
185
- print(td.name, td.description[:50])
186
- ```
187
-
188
- ---
189
-
190
- ## 3. `ctx run` CLI path
191
-
192
- If you don't have your own loop yet:
193
-
194
- ```bash
195
- pip install "claude-ctx[harness]"
196
- export OPENROUTER_API_KEY=sk-or-v1-...
197
-
198
- ctx run \
199
- --model openrouter/anthropic/claude-opus-4.7 \
200
- --task "find the failing tests in this repo and fix them" \
201
- --mcp filesystem \
202
- --budget-usd 2.00
203
- ```
204
-
205
- Or offline with Ollama:
206
-
207
- ```bash
208
- ctx run \
209
- --model ollama/llama3.1:70b \
210
- --task "summarize the architecture" \
211
- --mcp filesystem
212
- ```
213
-
214
- See `ctx run --help` for the full flag set (budgets, compaction,
215
- system prompt overrides, session resume, JSON output, ...).
216
-
217
- ---
218
-
219
- ## Installed harness attachment
220
-
221
- `ctx-harness-install <slug>` creates `.ctx/attach/` inside the installed
222
- harness target. The directory contains the attach files for the modes that
223
- catalog entry supports:
224
-
225
- - `README.md` describes the supported modes and safety expectations.
226
- - `mcp.json` starts `ctx-mcp-server` for MCP-speaking hosts.
227
- - `python.py` shows the Python recommendation/wiki calls for custom loops.
228
- - `ctx-run.txt` gives a `ctx run` command template.
229
-
230
- The install command does not run the harness or store secrets in those files.
231
- Setup commands still require `--approve-commands`; verification commands still
232
- require `--run-verify`.
233
-
234
- If no catalog harness fits, generate a build handoff instead of forcing a weak
235
- match:
236
-
237
- ```bash
238
- ctx-harness-install --recommend \
239
- --goal "build a private CAD workflow with a local model" \
240
- --model-provider ollama \
241
- --model ollama/llama3.1 \
242
- --plan-on-no-fit \
243
- --plan-output custom-harness.md
244
- ```
245
-
246
- ---
247
-
248
- ## Choosing the right path
249
-
250
- | Situation | Path |
251
- |---|---|
252
- | Your host already speaks MCP | 1 (MCP server) — zero Python code on your side |
253
- | You want the alive-skill system inside your existing Python loop | 2 (library) |
254
- | You're comparing models and need a harness | 3 (CLI) |
255
- | No catalog harness fits your model/goal | generated custom harness plan |
256
- | You're building an IDE extension | 1 if the IDE speaks MCP (most do), else 2 |
257
-
258
- All three paths share `~/.claude/skill-wiki/` as the source-of-truth
259
- corpus, so your recommendations are consistent regardless of the
260
- integration you pick.
261
-
262
- ---
263
-
264
- ## Skill lifecycle
265
-
266
- Recommendations go up and down based on use automatically. `ctx`
267
- tracks:
268
-
269
- - **How recently a skill was invoked** (`telemetry_signal`).
270
- - **How broadly it's used across the graph** (`graph_signal`).
271
- - **Whether new skills are being added** (`intake_signal`).
272
-
273
- Skills that fall below a quality floor get demoted to `stale` status
274
- and de-ranked from future recommendations. This logic lives in
275
- `ctx.core.quality.quality_signals` and runs identically whether
276
- you're on the MCP path, library path, or `ctx run` CLI.
277
-
278
- To inspect lifecycle state for a specific skill:
279
-
280
- ```bash
281
- ctx-skill-quality explain fastapi-pro
282
- ```
283
-
284
- Or from Python:
285
-
286
- ```python
287
- from ctx.core.quality import quality_signals
288
- # see ctx.core.quality for the scoring API
289
- ```
 
1
+ # Attaching ctx to any LLM host
2
+
3
+ `ctx` ships three integration surfaces. Pick based on what your host
4
+ already supports:
5
+
6
+ | Your host | Use |
7
+ |---|---|
8
+ | MCP-native (Claude Code, Claude Agent SDK, Cline, Goose, OpenHands, Continue) | **MCP server** — no Python, just spawn `ctx-mcp-server` |
9
+ | Anything that isn't MCP-native but runs Python | **Python library** — `from ctx import recommend_bundle, ...` |
10
+ | "I just want to run an agent and get recommendations" | **`ctx run` CLI** — our built-in harness |
11
+
12
+ All three paths consume the **same** knowledge graph, llm-wiki, and
13
+ quality scoring. Recommendations are identical; only the transport
14
+ differs.
15
+
16
+ ---
17
+
18
+ ## 1. MCP server path
19
+
20
+ Install ctx with the harness extras:
21
+
22
+ ```bash
23
+ pip install "claude-ctx[harness]"
24
+ ```
25
+
26
+ This puts `ctx-mcp-server` on your PATH. Then wire it into your host:
27
+
28
+ ### Claude Code
29
+
30
+ ```bash
31
+ claude mcp add ctx-wiki -- ctx-mcp-server
32
+ ```
33
+
34
+ The tools `ctx__recommend_bundle`, `ctx__graph_query`, `ctx__wiki_search`,
35
+ `ctx__wiki_get` appear to Claude on the next turn. Ask
36
+ "What skills help with FastAPI auth?" and it will call them.
37
+
38
+ ### Claude Agent SDK (Python)
39
+
40
+ ```python
41
+ from anthropic import Anthropic
42
+ from claude_agent_sdk import ClaudeAgentOptions, McpServerConfig
43
+
44
+ options = ClaudeAgentOptions(
45
+ mcp_servers={
46
+ "ctx-wiki": McpServerConfig(
47
+ command="ctx-mcp-server",
48
+ ),
49
+ },
50
+ )
51
+ ```
52
+
53
+ ### Cline / Continue.dev
54
+
55
+ Add to your MCP server config (`~/.config/cline/mcp.json` or the
56
+ Continue equivalent):
57
+
58
+ ```json
59
+ {
60
+ "mcpServers": {
61
+ "ctx-wiki": {
62
+ "command": "ctx-mcp-server"
63
+ }
64
+ }
65
+ }
66
+ ```
67
+
68
+ ### Goose
69
+
70
+ `~/.config/goose/config.yaml`:
71
+
72
+ ```yaml
73
+ extensions:
74
+ ctx-wiki:
75
+ type: stdio
76
+ cmd: ctx-mcp-server
77
+ ```
78
+
79
+ ### OpenHands
80
+
81
+ OpenHands' runtime config:
82
+
83
+ ```json
84
+ {
85
+ "mcp_servers": {
86
+ "ctx-wiki": {
87
+ "command": "ctx-mcp-server"
88
+ }
89
+ }
90
+ }
91
+ ```
92
+
93
+ ### Any MCP-speaking harness
94
+
95
+ The server reads JSON-RPC 2.0 on stdin, writes on stdout, speaks
96
+ MCP protocol version `2024-11-05`. Any client that does the standard
97
+ `initialize` handshake + `tools/list` + `tools/call` flow works.
98
+
99
+ ### Live MCP compatibility gate
100
+
101
+ The regular test suite never starts arbitrary third-party MCP servers.
102
+ Those commands run as local subprocesses and can read files, use the
103
+ network, and inherit whatever environment you explicitly allow.
104
+
105
+ To validate a trusted server, provide a local config and opt in:
106
+
107
+ ```bash
108
+ python -m pytest src/tests/test_mcp_live_compat.py \
109
+ --run-live-mcp \
110
+ --live-mcp-config /path/to/trusted-mcp.json
111
+ ```
112
+
113
+ Example config:
114
+
115
+ ```json
116
+ {
117
+ "name": "trusted-filesystem",
118
+ "command": "npx",
119
+ "args": ["-y", "@modelcontextprotocol/server-filesystem", "${tmp_path}"],
120
+ "startup_timeout": 30,
121
+ "request_timeout": 10,
122
+ "inherit_env": false,
123
+ "env": {},
124
+ "expected_tools": ["list_directory"],
125
+ "probe": {
126
+ "tool": "list_directory",
127
+ "arguments": {"path": "."},
128
+ "expect_text_contains": ""
129
+ },
130
+ "trust": {
131
+ "server_is_third_party_code": true,
132
+ "approved_by": "your-name"
133
+ }
134
+ }
135
+ ```
136
+
137
+ `command` and `args` are passed as an argv list, not through a shell.
138
+ Parent secrets are not inherited unless you set `inherit_env: true`; prefer
139
+ explicit `env` keys for servers that need credentials. `${tmp_path}` expands
140
+ to a pytest temporary directory so filesystem probes can avoid real user data.
141
+
142
+ ---
143
+
144
+ ## 2. Python library path
145
+
146
+ For custom harnesses that aren't MCP-native but can import Python:
147
+
148
+ ```python
149
+ from ctx import (
150
+ recommend_bundle, # free-text → ranked skill/agent/MCP bundle
151
+ graph_query, # walk from seed entities
152
+ wiki_search, # keyword search entity pages
153
+ wiki_get, # fetch one entity by slug
154
+ list_all_entities, # enumerate every slug
155
+ )
156
+
157
+ # Inside your agent loop:
158
+ def on_user_turn(query: str):
159
+ bundle = recommend_bundle(query, top_k=5)
160
+ for entry in bundle:
161
+ print(f" [{entry['type']:>11}] {entry['name']} (score {entry['score']:.1f})")
162
+
163
+ # User asks about a specific slug you saw in the bundle:
164
+ page = wiki_get("fastapi-pro")
165
+ if page:
166
+ inject_into_context(page["body"])
167
+ ```
168
+
169
+ The first call to any of these lazy-loads the graph + wiki once;
170
+ subsequent calls are O(walk) cheap. Safe to call from inside your
171
+ own while-loop on every turn.
172
+
173
+ Advanced: build a `CtxCoreToolbox` directly if you need to point at
174
+ a non-default wiki/graph path:
175
+
176
+ ```python
177
+ from pathlib import Path
178
+ from ctx import CtxCoreToolbox
179
+
180
+ toolbox = CtxCoreToolbox(
181
+ wiki_dir=Path("/path/to/custom/wiki"),
182
+ graph_path=Path("/path/to/custom/graph.json"),
183
+ )
184
+ for td in toolbox.tool_definitions():
185
+ print(td.name, td.description[:50])
186
+ ```
187
+
188
+ ---
189
+
190
+ ## 3. `ctx run` CLI path
191
+
192
+ If you don't have your own loop yet:
193
+
194
+ ```bash
195
+ pip install "claude-ctx[harness]"
196
+ export OPENROUTER_API_KEY=sk-or-v1-...
197
+
198
+ ctx run \
199
+ --model openrouter/anthropic/claude-opus-4.7 \
200
+ --task "find the failing tests in this repo and fix them" \
201
+ --mcp filesystem \
202
+ --budget-usd 2.00
203
+ ```
204
+
205
+ Or offline with Ollama:
206
+
207
+ ```bash
208
+ ctx run \
209
+ --model ollama/llama3.1:70b \
210
+ --task "summarize the architecture" \
211
+ --mcp filesystem
212
+ ```
213
+
214
+ See `ctx run --help` for the full flag set (budgets, compaction,
215
+ system prompt overrides, session resume, JSON output, ...).
216
+
217
+ ---
218
+
219
+ ## Installed harness attachment
220
+
221
+ `ctx-harness-install <slug>` creates `.ctx/attach/` inside the installed
222
+ harness target. The directory contains the attach files for the modes that
223
+ catalog entry supports:
224
+
225
+ - `README.md` describes the supported modes and safety expectations.
226
+ - `mcp.json` starts `ctx-mcp-server` for MCP-speaking hosts.
227
+ - `python.py` shows the Python recommendation/wiki calls for custom loops.
228
+ - `ctx-run.txt` gives a `ctx run` command template.
229
+
230
+ The install command does not run the harness or store secrets in those files.
231
+ Setup commands still require `--approve-commands`; verification commands still
232
+ require `--run-verify`.
233
+
234
+ If no catalog harness fits, generate a build handoff instead of forcing a weak
235
+ match:
236
+
237
+ ```bash
238
+ ctx-harness-install --recommend \
239
+ --goal "build a private CAD workflow with a local model" \
240
+ --model-provider ollama \
241
+ --model ollama/llama3.1 \
242
+ --plan-on-no-fit \
243
+ --plan-output custom-harness.md
244
+ ```
245
+
246
+ ---
247
+
248
+ ## Choosing the right path
249
+
250
+ | Situation | Path |
251
+ |---|---|
252
+ | Your host already speaks MCP | 1 (MCP server) — zero Python code on your side |
253
+ | You want the alive-skill system inside your existing Python loop | 2 (library) |
254
+ | You're comparing models and need a harness | 3 (CLI) |
255
+ | No catalog harness fits your model/goal | generated custom harness plan |
256
+ | You're building an IDE extension | 1 if the IDE speaks MCP (most do), else 2 |
257
+
258
+ All three paths share `~/.claude/skill-wiki/` as the source-of-truth
259
+ corpus, so your recommendations are consistent regardless of the
260
+ integration you pick.
261
+
262
+ ---
263
+
264
+ ## Skill lifecycle
265
+
266
+ Recommendations go up and down based on use automatically. `ctx`
267
+ tracks:
268
+
269
+ - **How recently a skill was invoked** (`telemetry_signal`).
270
+ - **How broadly it's used across the graph** (`graph_signal`).
271
+ - **Whether new skills are being added** (`intake_signal`).
272
+
273
+ Skills that fall below a quality floor get demoted to `stale` status
274
+ and de-ranked from future recommendations. This logic lives in
275
+ `ctx.core.quality.quality_signals` and runs identically whether
276
+ you're on the MCP path, library path, or `ctx run` CLI.
277
+
278
+ To inspect lifecycle state for a specific skill:
279
+
280
+ ```bash
281
+ ctx-skill-quality explain fastapi-pro
282
+ ```
283
+
284
+ Or from Python:
285
+
286
+ ```python
287
+ from ctx.core.quality import quality_signals
288
+ # see ctx.core.quality for the scoring API
289
+ ```
docs/harness/clean-host-contract.md CHANGED
@@ -1,103 +1,103 @@
1
- # Clean Host Contract
2
-
3
- The clean-host contract is a release-hardening check for ctx. It builds the
4
- current source tree into a wheel, installs that wheel into a fresh virtualenv,
5
- redirects user-state environment variables into a temporary directory, and then
6
- drives real console scripts.
7
-
8
- It is intentionally implemented as `scripts/clean_host_contract.py`, not as a
9
- public `ctx-*` command. The runner is infrastructure for maintainers until the
10
- contract stabilizes.
11
-
12
- ## What It Proves
13
-
14
- - The source tree can build a wheel.
15
- - The built wheel installs into a clean virtualenv.
16
- - Console-script entrypoints execute from the installed wheel.
17
- - `ctx-init --hooks` writes Claude settings only under an isolated temp home.
18
- - A deterministic fake Claude host reads the generated settings and executes
19
- the installed PostToolUse and Stop hook commands without calling Anthropic
20
- APIs.
21
- - With `--run-live-claude`, a real Claude Code host can be exercised behind an
22
- explicit quota acknowledgement, non-spending preflights, and a hard budget
23
- cap. Hook execution is verified through a JSONL sentinel written by injected
24
- PostToolUse and Stop hooks under the temp root.
25
- - `ctx-scan-repo --repo <path> --recommend` can scan a tiny FastAPI-like repo from the wheel.
26
- - `ctx run` can start a session with a process-local fake LiteLLM provider.
27
- - `ctx resume` can continue that session from the same isolated session store.
28
- - `--deny-tool` blocks a model-requested ctx tool call before dispatch.
29
- - Caller `PYTHONPATH` is stripped so the contract cannot accidentally import
30
- source-tree modules instead of the installed wheel.
31
-
32
- ## What It Skips
33
-
34
- - It does not run `ctx-init --graph` by default; even the fast runtime graph
35
- install downloads or extracts a large release artifact, so it stays in
36
- dedicated public-install smoke tests.
37
- - It does not execute hooks inside a live Claude Code process by default. The
38
- live host path is opt-in because it can consume Anthropic or provider quota.
39
- - It does not connect to a real third-party MCP server.
40
- - It does not browser-test the monitor dashboard.
41
- - It does not simulate process kills or power loss during writes.
42
-
43
- Those checks stay intentionally manual or opt-in until they are stable enough
44
- for the default CI path.
45
-
46
- ## Local Usage
47
-
48
- Run from the repository root:
49
-
50
- ```bash
51
- python scripts/clean_host_contract.py --fast
52
- ```
53
-
54
- For debugging, keep the temp directory:
55
-
56
- ```bash
57
- python scripts/clean_host_contract.py --fast --keep-temp
58
- ```
59
-
60
- To force a specific temp root:
61
-
62
- ```bash
63
- python scripts/clean_host_contract.py --fast --temp-root /tmp/ctx-clean-host-debug
64
- ```
65
-
66
- To run the real Claude Code host gate, use a shell with explicit non-file auth
67
- available, acknowledge quota, and keep the budget small:
68
-
69
- ```bash
70
- CTX_LIVE_CLAUDE_ACK=uses_quota \
71
- python scripts/clean_host_contract.py --fast --run-live-claude --live-claude-max-budget-usd 0.05
72
- ```
73
-
74
- Use `--claude-bin /path/to/claude` if `claude` is not on `PATH`. The live gate
75
- runs `claude --version` and `claude auth status` before the budgeted prompt,
76
- then appends sentinel hooks to the isolated `settings.json` and requires both
77
- PostToolUse and Stop records in `live-claude-hooks.jsonl`. It intentionally
78
- does not read OAuth or keychain state from the real user home; use explicit
79
- environment/provider auth for this check.
80
-
81
- ## CI Usage
82
-
83
- The main `.github/workflows/test.yml` workflow runs this contract on pushes and
84
- pull requests. The standalone `.github/workflows/clean-host-contract.yml`
85
- workflow remains available for manual runs and weekly scheduled drift checks.
86
- CI uses the default fake-host path and does not spend model quota.
87
-
88
- ## Failure Triage
89
-
90
- - Wheel build failure: inspect package metadata and `pyproject.toml`.
91
- - Install failure: inspect dependency constraints and `pip check` output.
92
- - `ctx-init` failure: inspect packaged entrypoints and hook module paths.
93
- - Fake Claude hook-smoke failure: inspect generated `settings.json`, packaged
94
- hook module paths, and whether PostToolUse/Stop hook schemas changed.
95
- - Live Claude gate failure: inspect explicit auth env/provider credentials,
96
- `claude auth status`, the budget cap, the injected sentinel hook entries, and
97
- `live-claude-hooks.jsonl` under the temp root.
98
- - `ctx-scan-repo` failure: inspect installed flat-module entrypoints and
99
- resolver imports.
100
- - `ctx run` or `ctx resume` failure: inspect LiteLLM provider import behavior,
101
- session store paths, and CLI metadata replay.
102
- - Tool denial failure: inspect `--allow-tool`/`--deny-tool` policy handling in
103
- `src/ctx/cli/run.py` and `src/ctx/adapters/generic/loop.py`.
 
1
+ # Clean Host Contract
2
+
3
+ The clean-host contract is a release-hardening check for ctx. It builds the
4
+ current source tree into a wheel, installs that wheel into a fresh virtualenv,
5
+ redirects user-state environment variables into a temporary directory, and then
6
+ drives real console scripts.
7
+
8
+ It is intentionally implemented as `scripts/clean_host_contract.py`, not as a
9
+ public `ctx-*` command. The runner is infrastructure for maintainers until the
10
+ contract stabilizes.
11
+
12
+ ## What It Proves
13
+
14
+ - The source tree can build a wheel.
15
+ - The built wheel installs into a clean virtualenv.
16
+ - Console-script entrypoints execute from the installed wheel.
17
+ - `ctx-init --hooks` writes Claude settings only under an isolated temp home.
18
+ - A deterministic fake Claude host reads the generated settings and executes
19
+ the installed PostToolUse and Stop hook commands without calling Anthropic
20
+ APIs.
21
+ - With `--run-live-claude`, a real Claude Code host can be exercised behind an
22
+ explicit quota acknowledgement, non-spending preflights, and a hard budget
23
+ cap. Hook execution is verified through a JSONL sentinel written by injected
24
+ PostToolUse and Stop hooks under the temp root.
25
+ - `ctx-scan-repo --repo <path> --recommend` can scan a tiny FastAPI-like repo from the wheel.
26
+ - `ctx run` can start a session with a process-local fake LiteLLM provider.
27
+ - `ctx resume` can continue that session from the same isolated session store.
28
+ - `--deny-tool` blocks a model-requested ctx tool call before dispatch.
29
+ - Caller `PYTHONPATH` is stripped so the contract cannot accidentally import
30
+ source-tree modules instead of the installed wheel.
31
+
32
+ ## What It Skips
33
+
34
+ - It does not run `ctx-init --graph` by default; even the fast runtime graph
35
+ install downloads or extracts a large release artifact, so it stays in
36
+ dedicated public-install smoke tests.
37
+ - It does not execute hooks inside a live Claude Code process by default. The
38
+ live host path is opt-in because it can consume Anthropic or provider quota.
39
+ - It does not connect to a real third-party MCP server.
40
+ - It does not browser-test the monitor dashboard.
41
+ - It does not simulate process kills or power loss during writes.
42
+
43
+ Those checks stay intentionally manual or opt-in until they are stable enough
44
+ for the default CI path.
45
+
46
+ ## Local Usage
47
+
48
+ Run from the repository root:
49
+
50
+ ```bash
51
+ python scripts/clean_host_contract.py --fast
52
+ ```
53
+
54
+ For debugging, keep the temp directory:
55
+
56
+ ```bash
57
+ python scripts/clean_host_contract.py --fast --keep-temp
58
+ ```
59
+
60
+ To force a specific temp root:
61
+
62
+ ```bash
63
+ python scripts/clean_host_contract.py --fast --temp-root /tmp/ctx-clean-host-debug
64
+ ```
65
+
66
+ To run the real Claude Code host gate, use a shell with explicit non-file auth
67
+ available, acknowledge quota, and keep the budget small:
68
+
69
+ ```bash
70
+ CTX_LIVE_CLAUDE_ACK=uses_quota \
71
+ python scripts/clean_host_contract.py --fast --run-live-claude --live-claude-max-budget-usd 0.05
72
+ ```
73
+
74
+ Use `--claude-bin /path/to/claude` if `claude` is not on `PATH`. The live gate
75
+ runs `claude --version` and `claude auth status` before the budgeted prompt,
76
+ then appends sentinel hooks to the isolated `settings.json` and requires both
77
+ PostToolUse and Stop records in `live-claude-hooks.jsonl`. It intentionally
78
+ does not read OAuth or keychain state from the real user home; use explicit
79
+ environment/provider auth for this check.
80
+
81
+ ## CI Usage
82
+
83
+ The main `.github/workflows/test.yml` workflow runs this contract on pushes and
84
+ pull requests. The standalone `.github/workflows/clean-host-contract.yml`
85
+ workflow remains available for manual runs and weekly scheduled drift checks.
86
+ CI uses the default fake-host path and does not spend model quota.
87
+
88
+ ## Failure Triage
89
+
90
+ - Wheel build failure: inspect package metadata and `pyproject.toml`.
91
+ - Install failure: inspect dependency constraints and `pip check` output.
92
+ - `ctx-init` failure: inspect packaged entrypoints and hook module paths.
93
+ - Fake Claude hook-smoke failure: inspect generated `settings.json`, packaged
94
+ hook module paths, and whether PostToolUse/Stop hook schemas changed.
95
+ - Live Claude gate failure: inspect explicit auth env/provider credentials,
96
+ `claude auth status`, the budget cap, the injected sentinel hook entries, and
97
+ `live-claude-hooks.jsonl` under the temp root.
98
+ - `ctx-scan-repo` failure: inspect installed flat-module entrypoints and
99
+ resolver imports.
100
+ - `ctx run` or `ctx resume` failure: inspect LiteLLM provider import behavior,
101
+ session store paths, and CLI metadata replay.
102
+ - Tool denial failure: inspect `--allow-tool`/`--deny-tool` policy handling in
103
+ `src/ctx/cli/run.py` and `src/ctx/adapters/generic/loop.py`.
docs/huggingface-publish.md CHANGED
@@ -1,67 +1,79 @@
1
- # Hugging Face Publish
2
-
3
- ctx publishes the GitHub repository as the public Hugging Face dataset
4
- [`Stevesolun/ctx`](https://huggingface.co/datasets/Stevesolun/ctx). The
5
- dataset is a clean `git ls-files` snapshot, including the shipped graph
6
- tarball and catalog artifacts, not local review reports or ignored caches.
7
-
8
- ## What gets uploaded
9
-
10
- - Tracked source, docs, tests, and packaging files.
11
- - `graph/wiki-graph.tar.gz`.
12
- - `graph/wiki-graph-runtime.tar.gz`.
13
- - The compressed skill index under `graph/`.
14
- - Tracked graph visualizations under `graph/`.
15
-
16
- Ignored local reports, review notes, raw ingest caches, coverage files,
17
- `site/`, and `.pytest_cache/` are not uploaded because they are not tracked
18
- by git.
19
-
20
- ## Publish command
21
-
22
- Use the repository sync script. It exports only tracked files, adds the
23
- Hugging Face repo-card frontmatter to the uploaded `README.md`, and refuses to
24
- publish if the full wiki tarball, runtime wiki tarball, or compressed skill
25
- index is missing, too small, or still a Git LFS
26
- pointer.
27
-
28
- The script prefers Hugging Face's resumable large-folder uploader when the
29
- remote already has no stale paths. If the remote contains files that are not in
30
- the current git snapshot, the script falls back to a single clean replacement
31
- commit so deleted local files cannot survive remotely.
32
-
33
- Do not paste the token into a command line. Prompt for it, set it only for the
34
- current process, and clear it after the upload.
35
-
36
- ```powershell
37
- python -m pip install --upgrade huggingface_hub
38
- git lfs install
39
- git lfs pull --include="graph/wiki-graph.tar.gz,graph/wiki-graph-runtime.tar.gz"
40
-
41
- $secureToken = Read-Host "HF write token" -AsSecureString
42
- $tokenPtr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureToken)
43
- try {
44
- $env:HF_TOKEN = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($tokenPtr)
45
- python scripts/sync_huggingface.py --repo . --repo-id Stevesolun/ctx --repo-type dataset
46
- } finally {
47
- if ($tokenPtr -ne [IntPtr]::Zero) {
48
- [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($tokenPtr)
49
- }
50
- Remove-Item Env:\HF_TOKEN -ErrorAction SilentlyContinue
51
- }
52
- ```
53
-
54
- ## Verify
55
-
56
- ```powershell
57
- @'
58
- from huggingface_hub import HfApi
59
-
60
- api = HfApi()
61
- info = api.repo_info(repo_id="Stevesolun/ctx", repo_type="dataset")
62
- print(info.id, info.sha)
63
- '@ | python -
64
- ```
65
-
66
- The dataset page should show the MIT license and the tags from the metadata
67
- wrapper.
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hugging Face Publish
2
+
3
+ ctx publishes the GitHub repository as the public Hugging Face dataset
4
+ [`Stevesolun/ctx`](https://huggingface.co/datasets/Stevesolun/ctx). The
5
+ dataset is a clean `git ls-files` snapshot, including the shipped graph
6
+ tarball and catalog artifacts, not local review reports or ignored caches.
7
+
8
+ ## What gets uploaded
9
+
10
+ - Tracked source, docs, tests, and packaging files.
11
+ - `graph/wiki-graph.tar.gz`.
12
+ - `graph/wiki-graph-runtime.tar.gz`.
13
+ - The compressed skill index under `graph/`.
14
+ - Tracked graph visualizations under `graph/`.
15
+
16
+ Ignored local reports, review notes, raw ingest caches, coverage files,
17
+ `site/`, and `.pytest_cache/` are not uploaded because they are not tracked
18
+ by git.
19
+
20
+ ## Automatic publish
21
+
22
+ Every push to `main` runs `.github/workflows/huggingface-sync.yml`. The job
23
+ checks out source without spending Git LFS bandwidth, hydrates the required
24
+ graph artifacts from the latest GitHub release assets, installs the sync
25
+ dependencies, and calls `scripts/sync_huggingface.py`. It publishes only when
26
+ the repository secret `HF_TOKEN` is configured; otherwise it exits successfully
27
+ with a notice so public forks and dry repos do not fail.
28
+
29
+ The sync script is still the contract: it exports the tracked git snapshot,
30
+ adds Hugging Face repo-card metadata, validates README/docs stats, verifies the
31
+ graph artifacts are hydrated rather than LFS pointers, and refuses to publish
32
+ stale or corrupt artifacts.
33
+
34
+ ## Manual publish
35
+
36
+ Use the repository sync script. It exports tracked files plus the validated
37
+ local graph artifacts, adds the Hugging Face repo-card frontmatter to the
38
+ uploaded `README.md`, and refuses to publish if the full wiki tarball, runtime
39
+ wiki tarball, or compressed skill index is missing, too small, or still a Git
40
+ LFS pointer.
41
+
42
+ The script prefers Hugging Face's resumable large-folder uploader when the
43
+ remote already has no stale paths. If the remote contains files that are not in
44
+ the current git snapshot, the script falls back to a single clean replacement
45
+ commit so deleted local files cannot survive remotely.
46
+
47
+ Do not paste the token into a command line. Prompt for it, set it only for the
48
+ current process, and clear it after the upload.
49
+
50
+ ```powershell
51
+ python -m pip install --upgrade huggingface_hub
52
+
53
+ $secureToken = Read-Host "HF write token" -AsSecureString
54
+ $tokenPtr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureToken)
55
+ try {
56
+ $env:HF_TOKEN = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($tokenPtr)
57
+ python scripts/sync_huggingface.py --repo . --repo-id Stevesolun/ctx --repo-type dataset
58
+ } finally {
59
+ if ($tokenPtr -ne [IntPtr]::Zero) {
60
+ [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($tokenPtr)
61
+ }
62
+ Remove-Item Env:\HF_TOKEN -ErrorAction SilentlyContinue
63
+ }
64
+ ```
65
+
66
+ ## Verify
67
+
68
+ ```powershell
69
+ @'
70
+ from huggingface_hub import HfApi
71
+
72
+ api = HfApi()
73
+ info = api.repo_info(repo_id="Stevesolun/ctx", repo_type="dataset")
74
+ print(info.id, info.sha)
75
+ '@ | python -
76
+ ```
77
+
78
+ The dataset page should show the MIT license and the tags from the metadata
79
+ wrapper.
docs/index.md CHANGED
@@ -1,232 +1,232 @@
1
- ---
2
- hide:
3
- - navigation
4
- ---
5
-
6
- # ctx — Skill, Agent, MCP & Harness Recommendations
7
-
8
- [![Repo views](https://hits.sh/github.com/stevesolun/ctx.svg?label=repo%20views)](https://hits.sh/github.com/stevesolun/ctx/)
9
-
10
- Watches what you develop, walks a knowledge graph of **91,464 skill pages, 467 agents, 10,790 MCP servers, and 207 cataloged harnesses**, and recommends the
11
- right execution bundle on the fly. The live execution bundle is skills,
12
- agents, and MCP servers only; custom/API/local model users get a separate
13
- harness recommendation based on model choice and task goal. You decide
14
- what to load, install, or adopt. Powered by a Karpathy LLM wiki with persistent
15
- memory that gets smarter every session.
16
-
17
- !!! tip "Install"
18
-
19
- ```bash
20
- pip install claude-ctx
21
- ctx-init --graph --model-mode skip
22
- ```
23
-
24
- Optional extras: `pip install "claude-ctx[embeddings]"` for the
25
- semantic backend, `pip install "claude-ctx[harness]"` for local/API
26
- model harness runs, `pip install "claude-ctx[dev]"` for the
27
- pytest/mypy/ruff toolchain. After install the `ctx-scan-repo`,
28
- `ctx-skill-quality`, `ctx-skill-health`, and `ctx-toolbox` console
29
- scripts are on PATH. `ctx-init --graph` installs the fast pre-built
30
- runtime graph that powers recommendations and harness dry-runs; source checkouts use
31
- `graph/wiki-graph-runtime.tar.gz`, while pip installs download the
32
- matching GitHub release asset. Use
33
- `ctx-init --graph --graph-install-mode full` when you want the full
34
- markdown LLM-wiki expanded locally.
35
-
36
- Custom-model users can run
37
- `ctx-init --model-mode custom --model <provider/model> --goal "<task>"`
38
- to record the model profile and surface harness recommendations.
39
-
40
- !!! tip "Before pushing"
41
-
42
- ```bash
43
- python scripts/ci_preflight.py --profile pr
44
- ```
45
-
46
- The preflight uses the same changed-file classifier as GitHub Actions and
47
- runs the matching local gates before you open a PR: stats, ruff, mypy, pip
48
- check, unit coverage, canaries, package build, twine, docs, graph
49
- validation, browser, and similarity checks as needed. Use `--profile full`
50
- before release work to force the source/package gates even for docs-only or
51
- graph-only changes.
52
-
53
- ## Why this exists
54
-
55
- Claude Code skills, agents, MCP servers, and model harness profiles are
56
- powerful, but at scale they become unmanageable:
57
-
58
- - **Discovery problem** — with 91K+ skill pages, 460+ agents, 10,000+
59
- MCP servers, and 207 harnesses, how do you know which
60
- ones exist and which are relevant to your current project?
61
- - **Context budget** — loading every installable entity wastes tokens and
62
- degrades quality. You need exactly the right skills, agents, and MCP
63
- servers per session, plus a harness recommendation only when you choose
64
- a custom/API/local model path.
65
- - **Hidden connections** — a FastAPI skill is useful, but you also need
66
- the Pydantic skill, the async Python patterns skill, and the Docker
67
- skill, plus possibly a matching MCP server. If you are not using Claude
68
- Code, ctx separately suggests the model harness most likely to fit your
69
- goal.
70
- Nobody tells you that.
71
- - **Entity rot** — skills, agents, MCP servers, and harness records you
72
- added months ago and never used are cluttering your context. Stale ones
73
- should be flagged and archived.
74
-
75
- ctx solves all of these by treating your ctx inventory as a **knowledge
76
- graph with persistent memory**, not a flat directory.
77
-
78
- ## What this is
79
-
80
- ctx is not a collection of scripts. It is an agent with persistent memory
81
- and a knowledge graph.
82
-
83
- The core idea comes from Andrej Karpathy's LLM-wiki pattern: instead of
84
- re-loading everything from scratch each session, an LLM maintains a wiki
85
- it can read, write, and query. The wiki becomes the agent's long-term
86
- memory.
87
-
88
- ctx applies that pattern to entity management — and extends it with
89
- graph-based discovery:
90
-
91
- - A Karpathy 3-layer wiki at `~/.claude/skill-wiki/` is the single source
92
- of truth.
93
- - **102,928 graph nodes** for the shipped skill/agent/MCP/harness
94
- inventory, including 91,464 skill pages
95
- and 207 harness pages under `entities/harnesses/`.
96
- Each page tracks tags, status, provenance, and usage where it applies.
97
- - A **knowledge graph** (102,928 nodes, 2,913,960 edges) built from a
98
- 13,463-node core plus 89,465 body-backed skill nodes.
99
- The graph has 52 Louvain communities and blends semantic cosine,
100
- tag overlap, and slug-token overlap; 89,465 skill bodies are
101
- shipped as installable `SKILL.md` files. Entries over the configured line
102
- threshold are converted to gated micro-skill orchestrators. Full source
103
- bodies were used for semantic graphing before packaging; `SKILL.md.original`
104
- backups are not shipped in the tarball.
105
- - **52 Louvain communities** group related entities into named
106
- communities (e.g., *AI + Devops + Frontend*, *Python + API*).
107
- - PostToolUse and Stop hooks update the wiki automatically during each
108
- Claude Code session.
109
- - Hydrated skills over 180 lines are converted to gated micro-skill
110
- pipelines so the router can load them incrementally.
111
- - At session start, the skill-router scans your project and
112
- **recommends** the best-matching skills, agents, and MCP servers.
113
- - Mid-session, the context monitor watches every tool call, detects new
114
- stack signals, walks the graph, and **recommends** relevant skills,
115
- agents, and MCP servers in real time — **nothing loads or
116
- installs without your approval**.
117
- - During custom/API/local model onboarding, `ctx-init` and
118
- `ctx-harness-install` use the same graph to recommend harnesses
119
- above the configured harness match floor.
120
-
121
- The result: you always know what skills, agents, and MCP servers are available
122
- for your current task, and which harness fits when you choose your own model.
123
- The graph reveals hidden connections. The wiki learns from your usage. Stale
124
- ones are flagged. New ones self-ingest.
125
-
126
- ## Explore the docs
127
-
128
- <div class="grid cards" markdown>
129
-
130
- - **Knowledge graph**
131
-
132
- ---
133
-
134
- 102,928 shipped graph nodes: 13,463 curated skill/agent/MCP/harness nodes plus 89,465 body-backed skill nodes. The graph has
135
- 2,913,960 weighted edges and 52 Louvain communities.
136
- Ships pre-built in `graph/wiki-graph.tar.gz` and powers the
137
- graph-aware recommendations + the pre-ship `ctx-dedup-check` gate.
138
-
139
- [:octicons-arrow-right-24: Knowledge graph](knowledge-graph.md)
140
-
141
- - **Entity onboarding**
142
-
143
- ---
144
-
145
- Step-by-step commands for adding a skill, agent, MCP server, or
146
- harness to the wiki and graph. Includes the `text-to-cad` harness
147
- pattern for custom-model users.
148
-
149
- [:octicons-arrow-right-24: Entity onboarding](entity-onboarding.md)
150
-
151
- - **Dashboard**
152
-
153
- ---
154
-
155
- `ctx-monitor serve` opens a local HTTP dashboard with live graph,
156
- skill grades + four-signal scores, session timelines, one-click
157
- load/unload for skills, agents, and MCP servers, plus harness wiki
158
- and graph browsing. It is served by stdlib `http.server` and renders
159
- repo docs with MkDocs-compatible Markdown extensions.
160
-
161
- [:octicons-arrow-right-24: Dashboard reference](dashboard.md)
162
-
163
- - **Toolbox**
164
-
165
- ---
166
-
167
- Curated councils of skills and agents that fire at session-start,
168
- file-save, pre-commit, and session-end. Blocks `git commit` on
169
- HIGH/CRITICAL findings. Five starter toolboxes ship out of the box.
170
-
171
- [:octicons-arrow-right-24: Toolbox overview](toolbox/index.md) ·
172
- [Starter toolboxes](toolbox/starters.md) ·
173
- [Verdicts & guardrails](toolbox/verdicts.md)
174
-
175
- - **Skill router**
176
-
177
- ---
178
-
179
- Scans the active repo, detects the stack from file signatures, walks
180
- the stack matrix, loads exactly the skills that apply, and can
181
- recommend supporting agents and MCP servers.
182
-
183
- [:octicons-arrow-right-24: Router overview](skill-router/index.md) ·
184
- [Stack signatures](stack-signatures.md) ·
185
- [Skill-stack matrix](skill-stack-matrix.md)
186
-
187
- - **Health & quality**
188
-
189
- ---
190
-
191
- Structural health checks (missing frontmatter, orphan manifest
192
- entries, line-count drift) plus the four-signal quality score
193
- (telemetry · intake · graph · routing) that grades every skill
194
- A/B/C/D/F.
195
-
196
- [:octicons-arrow-right-24: Skill health](skills-health.md) ·
197
- [Memory anchoring](memory-anchor.md) ·
198
- [Lifecycle dashboard](skill-lifecycle-and-dashboard.md)
199
-
200
- - **Releases**
201
-
202
- ---
203
-
204
- **v1.0.11** — MIT, CI-matrixed (Ubuntu 3.12 plus Windows/macOS 3.11/3.12),
205
- 3,915 tests collected. Ships console scripts including `ctx-init`,
206
- `ctx-monitor` (local dashboard with graph + wiki + load/unload for
207
- skills, agents, and MCP servers, plus Harness Setup for user-owned LLMs),
208
- `ctx-incremental-attach`, `ctx-incremental-shadow`, `ctx-dedup-check`
209
- (pre-ship near-duplicate gate), and
210
- `ctx-tag-backfill` (entity hygiene), plus a fast runtime graph artifact
211
- and the full ~439 MiB wiki tarball with **102,928 nodes / 2,913,960 edges / 52 Louvain communities**.
212
-
213
- [:octicons-arrow-right-24: CHANGELOG](https://github.com/stevesolun/ctx/blob/main/CHANGELOG.md) ·
214
- [Repository](https://github.com/stevesolun/ctx)
215
-
216
- </div>
217
-
218
- ## Principles
219
-
220
- - **Single source of truth.** The wiki and graph drive Claude Code
221
- recommendations, custom-model harness recommendations, dashboard views,
222
- and entity update reviews.
223
- - **Explicit approval.** ctx can recommend, review, install, update, unload,
224
- or uninstall, but it does not mutate live skills, agents, MCP servers, or
225
- harness installs without a command or approval path.
226
- - **Configurable gates.** Recommendation floors, semantic edge thresholds,
227
- micro-skill line limits, and harness match floors live in config so teams
228
- can tune behavior without forking the code.
229
- - **Evidence over opinion.** Suggestions cite real usage data plus
230
- knowledge-graph edges. No black-box prompts.
231
- - **Token discipline.** Every council run honors `max_tokens` /
232
- `max_seconds` budgets.
 
1
+ ---
2
+ hide:
3
+ - navigation
4
+ ---
5
+
6
+ # ctx — Skill, Agent, MCP & Harness Recommendations
7
+
8
+ [![Repo views](https://hits.sh/github.com/stevesolun/ctx.svg?label=repo%20views)](https://hits.sh/github.com/stevesolun/ctx/)
9
+
10
+ Watches what you develop, walks a knowledge graph of **91,464 skill pages, 467 agents, 10,790 MCP servers, and 207 cataloged harnesses**, and recommends the
11
+ right execution bundle on the fly. The live execution bundle is skills,
12
+ agents, and MCP servers only; custom/API/local model users get a separate
13
+ harness recommendation based on model choice and task goal. You decide
14
+ what to load, install, or adopt. Powered by a Karpathy LLM wiki with persistent
15
+ memory that gets smarter every session.
16
+
17
+ !!! tip "Install"
18
+
19
+ ```bash
20
+ pip install claude-ctx
21
+ ctx-init --graph --model-mode skip
22
+ ```
23
+
24
+ Optional extras: `pip install "claude-ctx[embeddings]"` for the
25
+ semantic backend, `pip install "claude-ctx[harness]"` for local/API
26
+ model harness runs, `pip install "claude-ctx[dev]"` for the
27
+ pytest/mypy/ruff toolchain. After install the `ctx-scan-repo`,
28
+ `ctx-skill-quality`, `ctx-skill-health`, and `ctx-toolbox` console
29
+ scripts are on PATH. `ctx-init --graph` installs the fast pre-built
30
+ runtime graph that powers recommendations and harness dry-runs; source checkouts use
31
+ `graph/wiki-graph-runtime.tar.gz`, while pip installs download the
32
+ matching GitHub release asset. Use
33
+ `ctx-init --graph --graph-install-mode full` when you want the full
34
+ markdown LLM-wiki expanded locally.
35
+
36
+ Custom-model users can run
37
+ `ctx-init --model-mode custom --model <provider/model> --goal "<task>"`
38
+ to record the model profile and surface harness recommendations.
39
+
40
+ !!! tip "Before pushing"
41
+
42
+ ```bash
43
+ python scripts/ci_preflight.py --profile pr
44
+ ```
45
+
46
+ The preflight uses the same changed-file classifier as GitHub Actions and
47
+ runs the matching local gates before you open a PR: stats, ruff, mypy, pip
48
+ check, unit coverage, canaries, package build, twine, docs, graph
49
+ validation, browser, and similarity checks as needed. Use `--profile full`
50
+ before release work to force the source/package gates even for docs-only or
51
+ graph-only changes.
52
+
53
+ ## Why this exists
54
+
55
+ Claude Code skills, agents, MCP servers, and model harness profiles are
56
+ powerful, but at scale they become unmanageable:
57
+
58
+ - **Discovery problem** — with 91K+ skill pages, 460+ agents, 10,000+
59
+ MCP servers, and 207 harnesses, how do you know which
60
+ ones exist and which are relevant to your current project?
61
+ - **Context budget** — loading every installable entity wastes tokens and
62
+ degrades quality. You need exactly the right skills, agents, and MCP
63
+ servers per session, plus a harness recommendation only when you choose
64
+ a custom/API/local model path.
65
+ - **Hidden connections** — a FastAPI skill is useful, but you also need
66
+ the Pydantic skill, the async Python patterns skill, and the Docker
67
+ skill, plus possibly a matching MCP server. If you are not using Claude
68
+ Code, ctx separately suggests the model harness most likely to fit your
69
+ goal.
70
+ Nobody tells you that.
71
+ - **Entity rot** — skills, agents, MCP servers, and harness records you
72
+ added months ago and never used are cluttering your context. Stale ones
73
+ should be flagged and archived.
74
+
75
+ ctx solves all of these by treating your ctx inventory as a **knowledge
76
+ graph with persistent memory**, not a flat directory.
77
+
78
+ ## What this is
79
+
80
+ ctx is not a collection of scripts. It is an agent with persistent memory
81
+ and a knowledge graph.
82
+
83
+ The core idea comes from Andrej Karpathy's LLM-wiki pattern: instead of
84
+ re-loading everything from scratch each session, an LLM maintains a wiki
85
+ it can read, write, and query. The wiki becomes the agent's long-term
86
+ memory.
87
+
88
+ ctx applies that pattern to entity management — and extends it with
89
+ graph-based discovery:
90
+
91
+ - A Karpathy 3-layer wiki at `~/.claude/skill-wiki/` is the single source
92
+ of truth.
93
+ - **102,928 graph nodes** for the shipped skill/agent/MCP/harness
94
+ inventory, including 91,464 skill pages
95
+ and 207 harness pages under `entities/harnesses/`.
96
+ Each page tracks tags, status, provenance, and usage where it applies.
97
+ - A **knowledge graph** (102,928 nodes, 2,913,960 edges) built from a
98
+ 13,463-node core plus 89,465 body-backed skill nodes.
99
+ The graph has 52 Louvain communities and blends semantic cosine,
100
+ tag overlap, and slug-token overlap; 89,465 skill bodies are
101
+ shipped as installable `SKILL.md` files. Entries over the configured line
102
+ threshold are converted to gated micro-skill orchestrators. Full source
103
+ bodies were used for semantic graphing before packaging; `SKILL.md.original`
104
+ backups are not shipped in the tarball.
105
+ - **52 Louvain communities** group related entities into named
106
+ communities (e.g., *AI + Devops + Frontend*, *Python + API*).
107
+ - PostToolUse and Stop hooks update the wiki automatically during each
108
+ Claude Code session.
109
+ - Hydrated skills over 180 lines are converted to gated micro-skill
110
+ pipelines so the router can load them incrementally.
111
+ - At session start, the skill-router scans your project and
112
+ **recommends** the best-matching skills, agents, and MCP servers.
113
+ - Mid-session, the context monitor watches every tool call, detects new
114
+ stack signals, walks the graph, and **recommends** relevant skills,
115
+ agents, and MCP servers in real time — **nothing loads or
116
+ installs without your approval**.
117
+ - During custom/API/local model onboarding, `ctx-init` and
118
+ `ctx-harness-install` use the same graph to recommend harnesses
119
+ above the configured harness match floor.
120
+
121
+ The result: you always know what skills, agents, and MCP servers are available
122
+ for your current task, and which harness fits when you choose your own model.
123
+ The graph reveals hidden connections. The wiki learns from your usage. Stale
124
+ ones are flagged. New ones self-ingest.
125
+
126
+ ## Explore the docs
127
+
128
+ <div class="grid cards" markdown>
129
+
130
+ - **Knowledge graph**
131
+
132
+ ---
133
+
134
+ 102,928 shipped graph nodes: 13,463 curated skill/agent/MCP/harness nodes plus 89,465 body-backed skill nodes. The graph has
135
+ 2,913,960 weighted edges and 52 Louvain communities.
136
+ Ships pre-built in `graph/wiki-graph.tar.gz` and powers the
137
+ graph-aware recommendations + the pre-ship `ctx-dedup-check` gate.
138
+
139
+ [:octicons-arrow-right-24: Knowledge graph](knowledge-graph.md)
140
+
141
+ - **Entity onboarding**
142
+
143
+ ---
144
+
145
+ Step-by-step commands for adding a skill, agent, MCP server, or
146
+ harness to the wiki and graph. Includes the `text-to-cad` harness
147
+ pattern for custom-model users.
148
+
149
+ [:octicons-arrow-right-24: Entity onboarding](entity-onboarding.md)
150
+
151
+ - **Dashboard**
152
+
153
+ ---
154
+
155
+ `ctx-monitor serve` opens a local HTTP dashboard with live graph,
156
+ skill grades + four-signal scores, session timelines, one-click
157
+ load/unload for skills, agents, and MCP servers, plus harness wiki
158
+ and graph browsing. It is served by stdlib `http.server` and renders
159
+ repo docs with MkDocs-compatible Markdown extensions.
160
+
161
+ [:octicons-arrow-right-24: Dashboard reference](dashboard.md)
162
+
163
+ - **Toolbox**
164
+
165
+ ---
166
+
167
+ Curated councils of skills and agents that fire at session-start,
168
+ file-save, pre-commit, and session-end. Blocks `git commit` on
169
+ HIGH/CRITICAL findings. Five starter toolboxes ship out of the box.
170
+
171
+ [:octicons-arrow-right-24: Toolbox overview](toolbox/index.md) ·
172
+ [Starter toolboxes](toolbox/starters.md) ·
173
+ [Verdicts & guardrails](toolbox/verdicts.md)
174
+
175
+ - **Skill router**
176
+
177
+ ---
178
+
179
+ Scans the active repo, detects the stack from file signatures, walks
180
+ the stack matrix, loads exactly the skills that apply, and can
181
+ recommend supporting agents and MCP servers.
182
+
183
+ [:octicons-arrow-right-24: Router overview](skill-router/index.md) ·
184
+ [Stack signatures](stack-signatures.md) ·
185
+ [Skill-stack matrix](skill-stack-matrix.md)
186
+
187
+ - **Health & quality**
188
+
189
+ ---
190
+
191
+ Structural health checks (missing frontmatter, orphan manifest
192
+ entries, line-count drift) plus the four-signal quality score
193
+ (telemetry · intake · graph · routing) that grades every skill
194
+ A/B/C/D/F.
195
+
196
+ [:octicons-arrow-right-24: Skill health](skills-health.md) ·
197
+ [Memory anchoring](memory-anchor.md) ·
198
+ [Lifecycle dashboard](skill-lifecycle-and-dashboard.md)
199
+
200
+ - **Releases**
201
+
202
+ ---
203
+
204
+ **v1.0.11** — MIT, CI-matrixed (Ubuntu 3.12 plus Windows/macOS 3.11/3.12),
205
+ 3,923 tests collected. Ships console scripts including `ctx-init`,
206
+ `ctx-monitor` (local dashboard with graph + wiki + load/unload for
207
+ skills, agents, and MCP servers, plus Harness Setup for user-owned LLMs),
208
+ `ctx-incremental-attach`, `ctx-incremental-shadow`, `ctx-dedup-check`
209
+ (pre-ship near-duplicate gate), and
210
+ `ctx-tag-backfill` (entity hygiene), plus a fast runtime graph artifact
211
+ and the full ~439 MiB wiki tarball with **102,928 nodes / 2,913,960 edges / 52 Louvain communities**.
212
+
213
+ [:octicons-arrow-right-24: CHANGELOG](https://github.com/stevesolun/ctx/blob/main/CHANGELOG.md) ·
214
+ [Repository](https://github.com/stevesolun/ctx)
215
+
216
+ </div>
217
+
218
+ ## Principles
219
+
220
+ - **Single source of truth.** The wiki and graph drive Claude Code
221
+ recommendations, custom-model harness recommendations, dashboard views,
222
+ and entity update reviews.
223
+ - **Explicit approval.** ctx can recommend, review, install, update, unload,
224
+ or uninstall, but it does not mutate live skills, agents, MCP servers, or
225
+ harness installs without a command or approval path.
226
+ - **Configurable gates.** Recommendation floors, semantic edge thresholds,
227
+ micro-skill line limits, and harness match floors live in config so teams
228
+ can tune behavior without forking the code.
229
+ - **Evidence over opinion.** Suggestions cite real usage data plus
230
+ knowledge-graph edges. No black-box prompts.
231
+ - **Token discipline.** Every council run honors `max_tokens` /
232
+ `max_seconds` budgets.
docs/knowledge-graph.md CHANGED
@@ -1,359 +1,359 @@
1
- # Knowledge graph
2
-
3
- A pre-built weighted graph of skills, agents, MCP servers, and
4
- harnesses in the ctx ecosystem, shipped as `graph/wiki-graph.tar.gz`.
5
- The on-disk JSON and `resolve_graph` Python API are harness-aware, including
6
- plain-slug graph walks from `harness:<slug>` nodes. `ctx-monitor`
7
- exposes skill/agent/MCP/harness wiki and graph views. Harness installation,
8
- update, and uninstall are handled by `ctx-harness-install`; dashboard
9
- load/unload POSTs deliberately reject harnesses and return the dry-run CLI
10
- command to use instead. Quality scoring is exposed for sidecar-backed skills,
11
- agents, and MCP servers.
12
-
13
- ## What's in it
14
-
15
- Authoritative numbers from the shipped tarball. The curated-core snapshot
16
- is **13,463 nodes** (1,999 curated skills + 467 agents + 10,790 MCP servers + 207 harnesses). Harness pages under `entities/harnesses/` are ingested into
17
- local rebuilds and the separate harness recommendation path. The
18
- tarball also carries **91,464 skill pages**; **89,465**
19
- skill bodies are hydrated as installable `SKILL.md` files under
20
- `converted/`; the **28,612** entries over the configured line
21
- limit were converted to gated micro-skill orchestrators. Full original bodies
22
- are used during graph rebuilds for semantic similarity, but
23
- `SKILL.md.original` backups, transient `.lock` files, and `.ctx/` queue state
24
- are omitted from the shipped tarball.
25
-
26
- | | Count |
27
- |---|---:|
28
- | Total nodes | **102,928** |
29
- | Curated core nodes | **13,463** (1,999 skills + 467 agents + 10,790 MCP servers + 207 harnesses) |
30
- | Body-backed skill nodes | **89,465** hydrated installable skill entries |
31
- | Total edges | **2,913,960** |
32
- | Hydrated skill incident edges | **2,605,721** |
33
- | Hydrated skill semantic incident edges | **1,500,648** |
34
- | Communities | **52** (Louvain) |
35
- | Edge sources (overlap-deduped) | semantic 1,683,193 - tag 897,784 - token 433,245 |
36
- | Cross-type edges (skill <-> agent) | ~66,799 |
37
- | Cross-type edges (skill <-> MCP) | ~41,521 |
38
- | Cross-type edges (agent <-> MCP) | ~229 |
39
- | Harness edges | **6,576** |
40
- | Shipped skill index | **89,465** observed body-backed skill entries |
41
-
42
- ## Install
43
-
44
- Use `ctx-init --graph` to install the fast runtime graph. Source checkouts use
45
- `graph/wiki-graph-runtime.tar.gz`; pip installs download the matching GitHub
46
- release asset for the installed package version. This installs
47
- `graphify-out/*`, the skill index used by recommendations, and
48
- the harness pages used by `ctx-harness-install`:
49
-
50
- ```bash
51
- ctx-init --graph
52
- ```
53
-
54
- To expand every shipped skill/agent/MCP entity page, harness page,
55
- skill page, concept page, converted micro-skill pipeline,
56
- and Obsidian vault metadata, request the full wiki artifact explicitly:
57
-
58
- ```bash
59
- ctx-init --graph --graph-install-mode full
60
- ```
61
-
62
- Manual extraction is still supported for offline/source installs. Extract the
63
- full tarball into your `~/.claude/skill-wiki/` when you want local markdown
64
- wiki browsing:
65
-
66
- ```bash
67
- mkdir -p ~/.claude/skill-wiki
68
- tar xzf graph/wiki-graph.tar.gz -C ~/.claude/skill-wiki/
69
- ```
70
-
71
- On Windows PowerShell, create the target and use the built-in `tar.exe`
72
- without `--force-local`:
73
-
74
- ```powershell
75
- New-Item -ItemType Directory -Force "$env:USERPROFILE\.claude\skill-wiki" | Out-Null
76
- tar -xzf graph\wiki-graph.tar.gz -C "$env:USERPROFILE\.claude\skill-wiki"
77
- ```
78
-
79
- The extracted tree also opens directly as an Obsidian vault — the
80
- `.obsidian/` config ships inside the tarball — so you can use
81
- Obsidian's native graph view if you prefer it to the web dashboard.
82
-
83
- ## How edges are built
84
-
85
- Edges are built and explained by the `ctx-wiki-graphify` console script
86
- (`ctx.core.wiki.wiki_graphify`). A pair must first have at least one base
87
- signal:
88
-
89
- 1. **Semantic cosine** — when the embedding backend is available, entity
90
- text is embedded and semantic neighbors above the configured build floor
91
- contribute weighted edges.
92
- 2. **Explicit frontmatter tags** — each entity page's YAML `tags:`
93
- list contributes edges between every pair of entities that share
94
- a tag. Popular tags capped at 500 nodes to avoid noise-floor
95
- "everything connects to everything" mega-buckets like `typescript`
96
- or `frontend`.
97
- 3. **Slug-token pseudo-tags** — each hyphenated slug contributes its
98
- tokens as implicit tags. `fastapi-pro` contributes `fastapi`;
99
- `python-patterns` contributes `python` and `patterns`. A stop-word
100
- filter drops generic tokens like `skill`, `agent`, `pro`, `expert`,
101
- `core` so they don't over-connect the graph.
102
- 4. **Source overlap** — pages with the same high-specificity source URL,
103
- repository URL, homepage, detail URL, or package URL can connect even
104
- when their tags differ. Dense source buckets are skipped.
105
- 5. **Direct wikilinks** — explicit entity links such as
106
- `[[entities/agents/code-reviewer]]` create a direct graph edge.
107
-
108
- Edge `weight` is the final blended strength. Semantic, tag, and token
109
- weights form the base blend from `config.json`; source overlap and direct
110
- links add configured boosts. Existing edges can also receive explainable
111
- ranking boosts from Adamic-Adar shared-neighbor structure, type affinity,
112
- usage telemetry, and quality scores. Those boost-only signals do not create
113
- edges by themselves. The shipped default `graph.min_edge_weight` is `0.03`;
114
- calibration against the 2026-05 shipped graph showed this is the highest
115
- floor with zero edge loss, while `0.05` would remove roughly 29.7% of edges.
116
-
117
- Edge metadata keeps the ingredients explainable: `semantic_sim`,
118
- `shared_tags`, `shared_tokens`, `shared_sources`, `direct_link`,
119
- `adamic_adar`, `type_affinity`, `usage_score`, `quality_score`,
120
- `edge_reasons`, and `score_components`. Hydrated skill records use their
121
- full source bodies during graph rebuilds, so long converted entries keep
122
- full-body similarity even though the shipped installable `SKILL.md` files are
123
- short gated loaders. The raw `SKILL.md.original` backups are build inputs, not
124
- tarball members.
125
-
126
- ## Communities
127
-
128
- After edges are built, `wiki_graphify` runs NetworkX's Louvain
129
- community detection (`resolution=1.2`, `seed=42` for determinism).
130
- The result is **52 communities** ranging from single-member isolated
131
- specialists to several thousand members in broad clusters like
132
- `Community + Official + AI`. Each community also gets an auto-generated
133
- `concepts/<community>.md` wiki page summarizing its members and top
134
- shared tags.
135
-
136
- The legacy CNM ("greedy modularity") algorithm is still available
137
- behind `CTX_GRAPH_COMMUNITY=cnm` — it's deterministic but O(n²) on
138
- dense graphs and hangs on the live 13K-node dataset (~50min run was
139
- killed on 2026-04-27 inside the priority-queue siftup). Louvain is
140
- the default because it finishes in seconds and produces equivalent
141
- quality clusters for the recommendation use case.
142
-
143
- ## Querying the graph
144
-
145
- ### Via the dashboard
146
-
147
- ```bash
148
- ctx-monitor serve # http://127.0.0.1:8765
149
- ```
150
-
151
- Then open `/graph?slug=<entity-slug>&type=<entity-type>` for a
152
- cytoscape neighborhood view, or
153
- `/api/graph/<slug>.json?type=<entity-type>&hops=1&limit=40` for the
154
- dashboard-shaped JSON. The `type` query is optional for unique slugs and
155
- recommended for duplicate slugs such as `langgraph`. See the
156
- [dashboard reference](dashboard.md) for the full route catalogue.
157
-
158
- ### Via Python
159
-
160
- ```python
161
- import json
162
- from pathlib import Path
163
- from networkx.readwrite import node_link_graph
164
-
165
- raw = json.loads(
166
- Path("~/.claude/skill-wiki/graphify-out/graph.json").expanduser().read_text()
167
- )
168
- edges_key = "links" if "links" in raw else "edges"
169
- G = node_link_graph(raw, edges=edges_key)
170
-
171
- # 102,928 nodes, 2,913,960 edges
172
- print(G.number_of_nodes(), G.number_of_edges())
173
-
174
- # Find entities related to 'fastapi-pro' by edge weight
175
- seed = "skill:fastapi-pro"
176
- neighbors = sorted(
177
- G.neighbors(seed),
178
- key=lambda n: G[seed][n]["weight"],
179
- reverse=True,
180
- )[:10]
181
- for n in neighbors:
182
- shared = G[seed][n].get("shared_tags", [])
183
- print(f" w={G[seed][n]['weight']:>2} {G.nodes[n]['label']:<40} {shared[:3]}")
184
- ```
185
-
186
- The node-link JSON schema's edges key is auto-detected (legacy
187
- NetworkX 2.x used `"links"`; current versions default to `"edges"`).
188
- The helper `resolve_graph.load_graph()` does this for you.
189
-
190
- ### Via recommendation paths
191
-
192
- The graph backs two recommendation paths:
193
-
194
- - Execution recommendation surfaces (`ctx.recommend_bundle`, MCP
195
- `ctx__recommend_bundle`, generic harness tools, Claude Code hook
196
- suggestions, and repo-scan advisory output) share
197
- `ctx.core.resolve.recommendations.recommend_by_tags` for skills,
198
- agents, and MCP servers. That engine ranks candidates by
199
- slug-token matches, tag overlap, graph degree, and semantic-cache
200
- signals when available. Imported skill results are normal `skill` nodes with
201
- detail URLs, install commands, duplicate
202
- hints, gated micro-skill loaders when over the line threshold, and
203
- quality/security metadata. If an older
204
- extracted wiki has the skill index JSON but no graph nodes for
205
- those records, the same recommender falls back to the index file.
206
- - Harness recommendations are a separate path for custom/API/local
207
- model onboarding (`ctx-init --model-mode custom ...`) and
208
- `ctx-harness-install`. They use the same graph filtered to
209
- `harness` nodes and the higher harness match floor from `config.json`.
210
- - Repository scans still start from stack detections, then turn that profile
211
- into the same tag/query bundle used by the execution recommender. If a
212
- shipped graph is unavailable, scan output falls back to the legacy installed
213
- skill resolver so a plain profile scan remains useful. Harnesses are
214
- intentionally not emitted from repo scans or Claude Code hook bundles.
215
-
216
- This split is intentional: execution surfaces need identical ranking and a
217
- small top-K, while harness choice changes the model runtime itself and belongs
218
- in an explicit onboarding/install flow.
219
-
220
- ### LLM-wiki design references
221
-
222
- ctx follows Karpathy's LLM-wiki pattern. We also reviewed
223
- [`nashsu/llm_wiki`](https://github.com/nashsu/llm_wiki) as a design reference
224
- for source traceability, persistent ingest queues, graph insights, and
225
- budgeted token/vector/graph retrieval. That repository is GPLv3, while ctx is
226
- MIT, so ctx can use those ideas as product inspiration but must not copy or
227
- vendor its code or assets.
228
-
229
- ## Rebuilding
230
-
231
- After you add a skill, agent, MCP server, or harness entity page:
232
-
233
- ```bash
234
- ctx-wiki-worker --wiki ~/.claude/skill-wiki --limit 1
235
- ```
236
-
237
- The `entity-upsert` worker path validates the queued page hash, updates the
238
- wiki index, and, when a persisted semantic vector index exists, runs a
239
- best-effort ANN attach into `graphify-out/entity-overlays.jsonl`. That overlay
240
- lets the runtime resolver connect a new or updated entity to existing graph
241
- neighbors without recomputing global all-pairs similarity. The worker still
242
- queues the normal incremental `graph-export` job, and the entity markdown page
243
- remains the source of truth.
244
-
245
- For manual review or debugging:
246
-
247
- ```bash
248
- ctx-incremental-attach calibrate \
249
- --graph ~/.claude/skill-wiki/graphify-out/graph.json
250
-
251
- ctx-incremental-attach attach \
252
- --index-dir ~/.claude/skill-wiki/.embedding-cache/graph/vector-index \
253
- --overlay ~/.claude/skill-wiki/graphify-out/entity-overlays.jsonl \
254
- --node-id skill:fastapi-review \
255
- --type skill \
256
- --label fastapi-review \
257
- --text-file ~/.claude/skill-wiki/entities/skills/fastapi-review.md \
258
- --dry-run
259
- ```
260
-
261
- Shadow-gate a persisted index before trusting a new ANN backend, changed
262
- thresholds, or a large attach workflow:
263
-
264
- ```bash
265
- ctx-incremental-shadow \
266
- --index-dir ~/.claude/skill-wiki/.embedding-cache/graph/vector-index \
267
- --graph ~/.claude/skill-wiki/graphify-out/graph.json \
268
- --sample-size 100 \
269
- --min-overlap 0.85
270
- ```
271
-
272
- The shadow command pretends sampled existing nodes are new, compares the
273
- incremental attach result to batch graph semantic neighbors, and reports
274
- precision, recall, top-5/top-10/top-20 agreement, score deltas, and bad
275
- examples. A failing gate means either tune thresholds or use a full graph
276
- rebuild before shipping.
277
-
278
- If the vector index is missing, rebuild it without repacking artifacts:
279
-
280
- ```bash
281
- ctx-wiki-graphify \
282
- --wiki-dir ~/.claude/skill-wiki \
283
- --incremental \
284
- --graph-only \
285
- --semantic-vector-index numpy-flat
286
- ```
287
-
288
- Then drain pending entity-upsert work with `ctx-wiki-worker --wiki
289
- ~/.claude/skill-wiki`. This is the current repair path for "build index" and
290
- "attach pending" without adding another command surface.
291
-
292
- Before publishing graph artifacts, run the full rebuild/export path:
293
-
294
- ```bash
295
- ctx-wiki-graphify # rebuild entity graph + communities
296
- ```
297
-
298
- The pre-commit hook (`.githooks/pre-commit`) does **not** rebuild or
299
- repack graph artifacts from `~/.claude/skill-wiki/`; that local wiki can
300
- contain private entities. It refreshes cheap README stats when relevant
301
- checked-in files are staged and warns when entity sources changed. Run
302
- `ctx-wiki-graphify`, validate, repack, and stage the artifacts explicitly
303
- for skill, agent, MCP server, or harness releases.
304
-
305
- Graphify exports stage and validate each generated artifact before atomic
306
- promotion. `graph.json`, `graph-delta.json`, `communities.json`,
307
- `graph-report.md`, and `graph-export-manifest.json` each get a sibling
308
- `*.promotion.json` file with candidate, current, and `last_good` hashes plus
309
- rollback metadata. The manifest is promoted last, so a crash between artifact
310
- promotion and manifest promotion is detected as an incomplete export and the
311
- next run rebuilds instead of trusting mixed graph files.
312
-
313
- ## Edge-count history
314
-
315
- | Version | Edges | Note |
316
- |---|---|---|
317
- | v0.5.x | 642K (stale) / 861 (live) | Bundle had stale 642K; live rebuild silently produced 861 because `DENSE_TAG_THRESHOLD=20` dropped every popular tag. |
318
- | v0.6.0 | 454,719 | Threshold raised to 500, multi-line YAML lists parsed, slug-token pseudo-tags added. |
319
- | v0.7.x | 847,207 | Pulsemcp ingest added 10,786 MCP server nodes; sentence-embedding semantic edges added. |
320
- | 2026-04-27 graph rebuild pass | **963,068** | +21 mattpocock skills, +156 designdotmd designs (+106,702 edges); patch-path bug fixed (graphify now forces full rebuild when prior graph has 0 semantic edges but current run computed semantic pairs); community detection switched from CNM to Louvain. |
321
- | 2026-04-29 bulk skill import pass | **1,030,831** | +90,846 first-class `skill` nodes, +90,846 skill pages, and +67,519 sparse duplicate/tag metadata edges to the core graph. Full-body semantic edges are intentionally deferred to the hydration pass. |
322
- | 2026-04-29 text-to-cad harness pass | **1,031,011** | +1 first-class `harness` node, +1 harness page, and +224 explainable harness edges, including 44 skill edges. |
323
- | 2026-04-29 harness inventory pass | **1,033,253** | +12 first-class `harness` nodes/pages for LangGraph, CrewAI, AutoGen, Google ADK, Semantic Kernel, Mastra, Pydantic AI, Haystack, OpenAI Agents SDK, LiteLLM, Langfuse, and AgentOps; harness incident edges now total 2,700. |
324
- | 2026-04-30 skill semantic hydration pass | **2,881,027** | +full-body semantic edges for hydrated skill records; semantic top-K became the dominant large-scale signal. |
325
- | 2026-05-01 micro-skill pass | **2,960,189** | Enforced the <=180-line loader threshold across 89,461 hydrated `SKILL.md` files, converted 28,611 long bodies into gated micro-skill orchestrators, used full originals for semantic graphing, excluded `.original` backups from the shipped tarball, bounded generated stage/reference files to 40 lines, and rebuilt the graph. |
326
- | 2026-05-02 GitNexus MCP pass | **2,960,215** | Added GitNexus as an MCP server entity with 26 cross-type edges to related skill pages and architecture/refactoring agents; semantic edge count unchanged. |
327
- | 2026-05-04 v0.7.3 artifact refresh | **2,960,215** | Hydrated one recoverable command-injection-testing body, raising hydrated `SKILL.md` files to 89,463; generated micro-skill markdown now defangs high-risk command-injection payloads before packaging. Graph topology unchanged. |
328
- | 2026-05-04 body-backed skill prune | **2,900,834** | Removed 1,383 skill records that had no packaged `SKILL.md` body and no parseable prose body. Remaining skill records, graph nodes, entity pages, and converted `SKILL.md` bodies are all **89,463**. |
329
- | 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. |
330
- | 2026-05-10 v1.0.0 release prep | **2,900,834** | Refreshed shipped HTML previews from the current export, validated their export IDs in CI, and removed stale PNG previews. Topology unchanged. |
331
- | 2026-05-12 book-to-skill + queue hygiene | **2,900,910** | Added `book-to-skill` as a skill entity (+1 node, +76 edges), restored a missing converted skill body, and repacked `graph/wiki-graph.tar.gz` to omit `.ctx/` queue state. Tar members: **598,154**. |
332
- | 2026-05-13 overlay pass | **2,911,220** | Added AGENTS.md, lat.md, OptiLLM, Matt Pocock refresh deltas, and Julius caveman entities through the safe overlay path (+21 nodes, +10,310 edges) while preserving the saturated skill topology. Tar members at that pass: **598,192**. |
333
- | 2026-05-14 Matt Pocock upstream refresh | **2,911,126** | Pinned `mattpocock/skills` to `e74f0061bb67222181640effa98c675bdb2fdaa7`, removed three stale legacy alias skill pages/nodes (`mattpocock-domain-model`, `mattpocock-github-triage`, `mattpocock-triage-issue`), refreshed `mattpocock-grill-with-docs`, and pruned 94 incident edges plus stale wiki references. Current tar members: **598,189**. |
334
- | 2026-05-14 Mirage + CodeGraph first-class wiki pass | **2,911,162** | Added Mirage as a shipped harness wiki/runtime page, added the CodeGraph MCP markdown page and `codegraph-agentic-codebase-analysis` skill page/body to the full LLM-wiki, added the compact dashboard neighborhood index, regenerated graph preview HTML from the current export, and refreshed exact validation counts. Current tar members: **598,193**. |
335
- | 2026-05-18 repo refresh | **2,911,575** | Refreshed `addyosmani/agent-skills` and `bytedance/deer-flow` from current upstream SKILL.md bodies, added Addy Osmani's `doubt-driven-development` and `interview-me` skills, replaced DeerFlow's stale `vercel-deploy` entry with `vercel-deploy-claimable`, retained `Imbad0202/academic-research-skills` as existing non-commercial upstream content, and added DeerFlow as a first-class harness page/runtime page. Current tar members: **598,596**. |
336
- | 2026-05-26 upstream repo ingest | **2,913,930** | Added `browsing-skills/browsing-skills` as a root browser skill plus 11 site-specific browser skills, refreshed `awesome-skills/code-review-skill` into `code-review-excellence` with its reference pack, refreshed `book-to-skill` through the micro-skill gate, added Presenton as both a harness and MCP server, refreshed DeerFlow's harness page, imported 190 harness catalog pages from `Picrew/awesome-agent-harness`, regenerated dashboard sqlite and preview HTML from the current export, and refreshed exact validation counts. Current tar members: **598,951**. |
337
- | 2026-05-27 Nango catalog/tooling overlay | **2,913,960** | Added `nango-integration-catalog` as a skill page/body, added Nango hosted action-function MCP and Nango docs MCP as first-class MCP pages, connected them to API/auth/tool-calling skills, common SaaS MCPs, and agent harnesses, regenerated dashboard sqlite and preview HTML, and refreshed exact validation counts. Current tar members: **598,955**. |
338
- | 2026-05-27 Nango semantic rescore | **2,913,960** | Replaced Nango's placeholder manual edge weights with measured MiniLM semantic cosines plus graphify-compatible tag/direct/type components. Topology unchanged; semantic edge count increased by 30 to **1,683,193**. |
339
-
340
- The full audit history lives in `CHANGELOG.md`. The current build is
341
- fully reproducible from the wiki content.
342
-
343
- ## Pre-ship gates
344
-
345
- Two advisory gates run before the tarball is repackaged. Both produce
346
- review reports and never auto-modify the inventory.
347
-
348
- - **`ctx-dedup-check`** — flags entity pairs (skill ↔ skill, skill ↔
349
- agent, skill ↔ MCP, agent ↔ agent, agent ↔ MCP, MCP ↔ MCP) at or
350
- above 0.85 cosine similarity. Incremental: keeps a `dedup-state.json`
351
- next to the embedding cache, so follow-up runs only re-check pairs
352
- involving entities whose content changed. Allowlist support via
353
- `.dedup-allowlist.txt`. The current snapshot has 15,976 findings,
354
- most of which are within-MCP near-duplicates (multiple wrappers
355
- around the same upstream service).
356
- - **`ctx-tag-backfill`** — finds skills/agents with empty `tags:`
357
- frontmatter and proposes a backfill drawn from slug tokens, body
358
- keywords, and the existing tag vocabulary. Report-only by default;
359
- pass `--apply` to write. Backfills are additive only.
 
1
+ # Knowledge graph
2
+
3
+ A pre-built weighted graph of skills, agents, MCP servers, and
4
+ harnesses in the ctx ecosystem, shipped as `graph/wiki-graph.tar.gz`.
5
+ The on-disk JSON and `resolve_graph` Python API are harness-aware, including
6
+ plain-slug graph walks from `harness:<slug>` nodes. `ctx-monitor`
7
+ exposes skill/agent/MCP/harness wiki and graph views. Harness installation,
8
+ update, and uninstall are handled by `ctx-harness-install`; dashboard
9
+ load/unload POSTs deliberately reject harnesses and return the dry-run CLI
10
+ command to use instead. Quality scoring is exposed for sidecar-backed skills,
11
+ agents, and MCP servers.
12
+
13
+ ## What's in it
14
+
15
+ Authoritative numbers from the shipped tarball. The curated-core snapshot
16
+ is **13,463 nodes** (1,999 curated skills + 467 agents + 10,790 MCP servers + 207 harnesses). Harness pages under `entities/harnesses/` are ingested into
17
+ local rebuilds and the separate harness recommendation path. The
18
+ tarball also carries **91,464 skill pages**; **89,465**
19
+ skill bodies are hydrated as installable `SKILL.md` files under
20
+ `converted/`; the **28,612** entries over the configured line
21
+ limit were converted to gated micro-skill orchestrators. Full original bodies
22
+ are used during graph rebuilds for semantic similarity, but
23
+ `SKILL.md.original` backups, transient `.lock` files, and `.ctx/` queue state
24
+ are omitted from the shipped tarball.
25
+
26
+ | | Count |
27
+ |---|---:|
28
+ | Total nodes | **102,928** |
29
+ | Curated core nodes | **13,463** (1,999 skills + 467 agents + 10,790 MCP servers + 207 harnesses) |
30
+ | Body-backed skill nodes | **89,465** hydrated installable skill entries |
31
+ | Total edges | **2,913,960** |
32
+ | Hydrated skill incident edges | **2,605,721** |
33
+ | Hydrated skill semantic incident edges | **1,500,648** |
34
+ | Communities | **52** (Louvain) |
35
+ | Edge sources (overlap-deduped) | semantic 1,683,193 - tag 897,784 - token 433,245 |
36
+ | Cross-type edges (skill <-> agent) | ~66,799 |
37
+ | Cross-type edges (skill <-> MCP) | ~41,521 |
38
+ | Cross-type edges (agent <-> MCP) | ~229 |
39
+ | Harness edges | **6,576** |
40
+ | Shipped skill index | **89,465** observed body-backed skill entries |
41
+
42
+ ## Install
43
+
44
+ Use `ctx-init --graph` to install the fast runtime graph. Source checkouts use
45
+ `graph/wiki-graph-runtime.tar.gz`; pip installs download the matching GitHub
46
+ release asset for the installed package version. This installs
47
+ `graphify-out/*`, the skill index used by recommendations, and
48
+ the harness pages used by `ctx-harness-install`:
49
+
50
+ ```bash
51
+ ctx-init --graph
52
+ ```
53
+
54
+ To expand every shipped skill/agent/MCP entity page, harness page,
55
+ skill page, concept page, converted micro-skill pipeline,
56
+ and Obsidian vault metadata, request the full wiki artifact explicitly:
57
+
58
+ ```bash
59
+ ctx-init --graph --graph-install-mode full
60
+ ```
61
+
62
+ Manual extraction is still supported for offline/source installs. Extract the
63
+ full tarball into your `~/.claude/skill-wiki/` when you want local markdown
64
+ wiki browsing:
65
+
66
+ ```bash
67
+ mkdir -p ~/.claude/skill-wiki
68
+ tar xzf graph/wiki-graph.tar.gz -C ~/.claude/skill-wiki/
69
+ ```
70
+
71
+ On Windows PowerShell, create the target and use the built-in `tar.exe`
72
+ without `--force-local`:
73
+
74
+ ```powershell
75
+ New-Item -ItemType Directory -Force "$env:USERPROFILE\.claude\skill-wiki" | Out-Null
76
+ tar -xzf graph\wiki-graph.tar.gz -C "$env:USERPROFILE\.claude\skill-wiki"
77
+ ```
78
+
79
+ The extracted tree also opens directly as an Obsidian vault — the
80
+ `.obsidian/` config ships inside the tarball — so you can use
81
+ Obsidian's native graph view if you prefer it to the web dashboard.
82
+
83
+ ## How edges are built
84
+
85
+ Edges are built and explained by the `ctx-wiki-graphify` console script
86
+ (`ctx.core.wiki.wiki_graphify`). A pair must first have at least one base
87
+ signal:
88
+
89
+ 1. **Semantic cosine** — when the embedding backend is available, entity
90
+ text is embedded and semantic neighbors above the configured build floor
91
+ contribute weighted edges.
92
+ 2. **Explicit frontmatter tags** — each entity page's YAML `tags:`
93
+ list contributes edges between every pair of entities that share
94
+ a tag. Popular tags capped at 500 nodes to avoid noise-floor
95
+ "everything connects to everything" mega-buckets like `typescript`
96
+ or `frontend`.
97
+ 3. **Slug-token pseudo-tags** — each hyphenated slug contributes its
98
+ tokens as implicit tags. `fastapi-pro` contributes `fastapi`;
99
+ `python-patterns` contributes `python` and `patterns`. A stop-word
100
+ filter drops generic tokens like `skill`, `agent`, `pro`, `expert`,
101
+ `core` so they don't over-connect the graph.
102
+ 4. **Source overlap** — pages with the same high-specificity source URL,
103
+ repository URL, homepage, detail URL, or package URL can connect even
104
+ when their tags differ. Dense source buckets are skipped.
105
+ 5. **Direct wikilinks** — explicit entity links such as
106
+ `[[entities/agents/code-reviewer]]` create a direct graph edge.
107
+
108
+ Edge `weight` is the final blended strength. Semantic, tag, and token
109
+ weights form the base blend from `config.json`; source overlap and direct
110
+ links add configured boosts. Existing edges can also receive explainable
111
+ ranking boosts from Adamic-Adar shared-neighbor structure, type affinity,
112
+ usage telemetry, and quality scores. Those boost-only signals do not create
113
+ edges by themselves. The shipped default `graph.min_edge_weight` is `0.03`;
114
+ calibration against the 2026-05 shipped graph showed this is the highest
115
+ floor with zero edge loss, while `0.05` would remove roughly 29.7% of edges.
116
+
117
+ Edge metadata keeps the ingredients explainable: `semantic_sim`,
118
+ `shared_tags`, `shared_tokens`, `shared_sources`, `direct_link`,
119
+ `adamic_adar`, `type_affinity`, `usage_score`, `quality_score`,
120
+ `edge_reasons`, and `score_components`. Hydrated skill records use their
121
+ full source bodies during graph rebuilds, so long converted entries keep
122
+ full-body similarity even though the shipped installable `SKILL.md` files are
123
+ short gated loaders. The raw `SKILL.md.original` backups are build inputs, not
124
+ tarball members.
125
+
126
+ ## Communities
127
+
128
+ After edges are built, `wiki_graphify` runs NetworkX's Louvain
129
+ community detection (`resolution=1.2`, `seed=42` for determinism).
130
+ The result is **52 communities** ranging from single-member isolated
131
+ specialists to several thousand members in broad clusters like
132
+ `Community + Official + AI`. Each community also gets an auto-generated
133
+ `concepts/<community>.md` wiki page summarizing its members and top
134
+ shared tags.
135
+
136
+ The legacy CNM ("greedy modularity") algorithm is still available
137
+ behind `CTX_GRAPH_COMMUNITY=cnm` — it's deterministic but O(n²) on
138
+ dense graphs and hangs on the live 13K-node dataset (~50min run was
139
+ killed on 2026-04-27 inside the priority-queue siftup). Louvain is
140
+ the default because it finishes in seconds and produces equivalent
141
+ quality clusters for the recommendation use case.
142
+
143
+ ## Querying the graph
144
+
145
+ ### Via the dashboard
146
+
147
+ ```bash
148
+ ctx-monitor serve # http://127.0.0.1:8765
149
+ ```
150
+
151
+ Then open `/graph?slug=<entity-slug>&type=<entity-type>` for a
152
+ cytoscape neighborhood view, or
153
+ `/api/graph/<slug>.json?type=<entity-type>&hops=1&limit=40` for the
154
+ dashboard-shaped JSON. The `type` query is optional for unique slugs and
155
+ recommended for duplicate slugs such as `langgraph`. See the
156
+ [dashboard reference](dashboard.md) for the full route catalogue.
157
+
158
+ ### Via Python
159
+
160
+ ```python
161
+ import json
162
+ from pathlib import Path
163
+ from networkx.readwrite import node_link_graph
164
+
165
+ raw = json.loads(
166
+ Path("~/.claude/skill-wiki/graphify-out/graph.json").expanduser().read_text()
167
+ )
168
+ edges_key = "links" if "links" in raw else "edges"
169
+ G = node_link_graph(raw, edges=edges_key)
170
+
171
+ # 102,928 nodes, 2,913,960 edges
172
+ print(G.number_of_nodes(), G.number_of_edges())
173
+
174
+ # Find entities related to 'fastapi-pro' by edge weight
175
+ seed = "skill:fastapi-pro"
176
+ neighbors = sorted(
177
+ G.neighbors(seed),
178
+ key=lambda n: G[seed][n]["weight"],
179
+ reverse=True,
180
+ )[:10]
181
+ for n in neighbors:
182
+ shared = G[seed][n].get("shared_tags", [])
183
+ print(f" w={G[seed][n]['weight']:>2} {G.nodes[n]['label']:<40} {shared[:3]}")
184
+ ```
185
+
186
+ The node-link JSON schema's edges key is auto-detected (legacy
187
+ NetworkX 2.x used `"links"`; current versions default to `"edges"`).
188
+ The helper `resolve_graph.load_graph()` does this for you.
189
+
190
+ ### Via recommendation paths
191
+
192
+ The graph backs two recommendation paths:
193
+
194
+ - Execution recommendation surfaces (`ctx.recommend_bundle`, MCP
195
+ `ctx__recommend_bundle`, generic harness tools, Claude Code hook
196
+ suggestions, and repo-scan advisory output) share
197
+ `ctx.core.resolve.recommendations.recommend_by_tags` for skills,
198
+ agents, and MCP servers. That engine ranks candidates by
199
+ slug-token matches, tag overlap, graph degree, and semantic-cache
200
+ signals when available. Imported skill results are normal `skill` nodes with
201
+ detail URLs, install commands, duplicate
202
+ hints, gated micro-skill loaders when over the line threshold, and
203
+ quality/security metadata. If an older
204
+ extracted wiki has the skill index JSON but no graph nodes for
205
+ those records, the same recommender falls back to the index file.
206
+ - Harness recommendations are a separate path for custom/API/local
207
+ model onboarding (`ctx-init --model-mode custom ...`) and
208
+ `ctx-harness-install`. They use the same graph filtered to
209
+ `harness` nodes and the higher harness match floor from `config.json`.
210
+ - Repository scans still start from stack detections, then turn that profile
211
+ into the same tag/query bundle used by the execution recommender. If a
212
+ shipped graph is unavailable, scan output falls back to the legacy installed
213
+ skill resolver so a plain profile scan remains useful. Harnesses are
214
+ intentionally not emitted from repo scans or Claude Code hook bundles.
215
+
216
+ This split is intentional: execution surfaces need identical ranking and a
217
+ small top-K, while harness choice changes the model runtime itself and belongs
218
+ in an explicit onboarding/install flow.
219
+
220
+ ### LLM-wiki design references
221
+
222
+ ctx follows Karpathy's LLM-wiki pattern. We also reviewed
223
+ [`nashsu/llm_wiki`](https://github.com/nashsu/llm_wiki) as a design reference
224
+ for source traceability, persistent ingest queues, graph insights, and
225
+ budgeted token/vector/graph retrieval. That repository is GPLv3, while ctx is
226
+ MIT, so ctx can use those ideas as product inspiration but must not copy or
227
+ vendor its code or assets.
228
+
229
+ ## Rebuilding
230
+
231
+ After you add a skill, agent, MCP server, or harness entity page:
232
+
233
+ ```bash
234
+ ctx-wiki-worker --wiki ~/.claude/skill-wiki --limit 1
235
+ ```
236
+
237
+ The `entity-upsert` worker path validates the queued page hash, updates the
238
+ wiki index, and, when a persisted semantic vector index exists, runs a
239
+ best-effort ANN attach into `graphify-out/entity-overlays.jsonl`. That overlay
240
+ lets the runtime resolver connect a new or updated entity to existing graph
241
+ neighbors without recomputing global all-pairs similarity. The worker still
242
+ queues the normal incremental `graph-export` job, and the entity markdown page
243
+ remains the source of truth.
244
+
245
+ For manual review or debugging:
246
+
247
+ ```bash
248
+ ctx-incremental-attach calibrate \
249
+ --graph ~/.claude/skill-wiki/graphify-out/graph.json
250
+
251
+ ctx-incremental-attach attach \
252
+ --index-dir ~/.claude/skill-wiki/.embedding-cache/graph/vector-index \
253
+ --overlay ~/.claude/skill-wiki/graphify-out/entity-overlays.jsonl \
254
+ --node-id skill:fastapi-review \
255
+ --type skill \
256
+ --label fastapi-review \
257
+ --text-file ~/.claude/skill-wiki/entities/skills/fastapi-review.md \
258
+ --dry-run
259
+ ```
260
+
261
+ Shadow-gate a persisted index before trusting a new ANN backend, changed
262
+ thresholds, or a large attach workflow:
263
+
264
+ ```bash
265
+ ctx-incremental-shadow \
266
+ --index-dir ~/.claude/skill-wiki/.embedding-cache/graph/vector-index \
267
+ --graph ~/.claude/skill-wiki/graphify-out/graph.json \
268
+ --sample-size 100 \
269
+ --min-overlap 0.85
270
+ ```
271
+
272
+ The shadow command pretends sampled existing nodes are new, compares the
273
+ incremental attach result to batch graph semantic neighbors, and reports
274
+ precision, recall, top-5/top-10/top-20 agreement, score deltas, and bad
275
+ examples. A failing gate means either tune thresholds or use a full graph
276
+ rebuild before shipping.
277
+
278
+ If the vector index is missing, rebuild it without repacking artifacts:
279
+
280
+ ```bash
281
+ ctx-wiki-graphify \
282
+ --wiki-dir ~/.claude/skill-wiki \
283
+ --incremental \
284
+ --graph-only \
285
+ --semantic-vector-index numpy-flat
286
+ ```
287
+
288
+ Then drain pending entity-upsert work with `ctx-wiki-worker --wiki
289
+ ~/.claude/skill-wiki`. This is the current repair path for "build index" and
290
+ "attach pending" without adding another command surface.
291
+
292
+ Before publishing graph artifacts, run the full rebuild/export path:
293
+
294
+ ```bash
295
+ ctx-wiki-graphify # rebuild entity graph + communities
296
+ ```
297
+
298
+ The pre-commit hook (`.githooks/pre-commit`) does **not** rebuild or
299
+ repack graph artifacts from `~/.claude/skill-wiki/`; that local wiki can
300
+ contain private entities. It refreshes cheap README stats when relevant
301
+ checked-in files are staged and warns when entity sources changed. Run
302
+ `ctx-wiki-graphify`, validate, repack, and stage the artifacts explicitly
303
+ for skill, agent, MCP server, or harness releases.
304
+
305
+ Graphify exports stage and validate each generated artifact before atomic
306
+ promotion. `graph.json`, `graph-delta.json`, `communities.json`,
307
+ `graph-report.md`, and `graph-export-manifest.json` each get a sibling
308
+ `*.promotion.json` file with candidate, current, and `last_good` hashes plus
309
+ rollback metadata. The manifest is promoted last, so a crash between artifact
310
+ promotion and manifest promotion is detected as an incomplete export and the
311
+ next run rebuilds instead of trusting mixed graph files.
312
+
313
+ ## Edge-count history
314
+
315
+ | Version | Edges | Note |
316
+ |---|---|---|
317
+ | v0.5.x | 642K (stale) / 861 (live) | Bundle had stale 642K; live rebuild silently produced 861 because `DENSE_TAG_THRESHOLD=20` dropped every popular tag. |
318
+ | v0.6.0 | 454,719 | Threshold raised to 500, multi-line YAML lists parsed, slug-token pseudo-tags added. |
319
+ | v0.7.x | 847,207 | Pulsemcp ingest added 10,786 MCP server nodes; sentence-embedding semantic edges added. |
320
+ | 2026-04-27 graph rebuild pass | **963,068** | +21 mattpocock skills, +156 designdotmd designs (+106,702 edges); patch-path bug fixed (graphify now forces full rebuild when prior graph has 0 semantic edges but current run computed semantic pairs); community detection switched from CNM to Louvain. |
321
+ | 2026-04-29 bulk skill import pass | **1,030,831** | +90,846 first-class `skill` nodes, +90,846 skill pages, and +67,519 sparse duplicate/tag metadata edges to the core graph. Full-body semantic edges are intentionally deferred to the hydration pass. |
322
+ | 2026-04-29 text-to-cad harness pass | **1,031,011** | +1 first-class `harness` node, +1 harness page, and +224 explainable harness edges, including 44 skill edges. |
323
+ | 2026-04-29 harness inventory pass | **1,033,253** | +12 first-class `harness` nodes/pages for LangGraph, CrewAI, AutoGen, Google ADK, Semantic Kernel, Mastra, Pydantic AI, Haystack, OpenAI Agents SDK, LiteLLM, Langfuse, and AgentOps; harness incident edges now total 2,700. |
324
+ | 2026-04-30 skill semantic hydration pass | **2,881,027** | +full-body semantic edges for hydrated skill records; semantic top-K became the dominant large-scale signal. |
325
+ | 2026-05-01 micro-skill pass | **2,960,189** | Enforced the <=180-line loader threshold across 89,461 hydrated `SKILL.md` files, converted 28,611 long bodies into gated micro-skill orchestrators, used full originals for semantic graphing, excluded `.original` backups from the shipped tarball, bounded generated stage/reference files to 40 lines, and rebuilt the graph. |
326
+ | 2026-05-02 GitNexus MCP pass | **2,960,215** | Added GitNexus as an MCP server entity with 26 cross-type edges to related skill pages and architecture/refactoring agents; semantic edge count unchanged. |
327
+ | 2026-05-04 v0.7.3 artifact refresh | **2,960,215** | Hydrated one recoverable command-injection-testing body, raising hydrated `SKILL.md` files to 89,463; generated micro-skill markdown now defangs high-risk command-injection payloads before packaging. Graph topology unchanged. |
328
+ | 2026-05-04 body-backed skill prune | **2,900,834** | Removed 1,383 skill records that had no packaged `SKILL.md` body and no parseable prose body. Remaining skill records, graph nodes, entity pages, and converted `SKILL.md` bodies are all **89,463**. |
329
+ | 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. |
330
+ | 2026-05-10 v1.0.0 release prep | **2,900,834** | Refreshed shipped HTML previews from the current export, validated their export IDs in CI, and removed stale PNG previews. Topology unchanged. |
331
+ | 2026-05-12 book-to-skill + queue hygiene | **2,900,910** | Added `book-to-skill` as a skill entity (+1 node, +76 edges), restored a missing converted skill body, and repacked `graph/wiki-graph.tar.gz` to omit `.ctx/` queue state. Tar members: **598,154**. |
332
+ | 2026-05-13 overlay pass | **2,911,220** | Added AGENTS.md, lat.md, OptiLLM, Matt Pocock refresh deltas, and Julius caveman entities through the safe overlay path (+21 nodes, +10,310 edges) while preserving the saturated skill topology. Tar members at that pass: **598,192**. |
333
+ | 2026-05-14 Matt Pocock upstream refresh | **2,911,126** | Pinned `mattpocock/skills` to `e74f0061bb67222181640effa98c675bdb2fdaa7`, removed three stale legacy alias skill pages/nodes (`mattpocock-domain-model`, `mattpocock-github-triage`, `mattpocock-triage-issue`), refreshed `mattpocock-grill-with-docs`, and pruned 94 incident edges plus stale wiki references. Current tar members: **598,189**. |
334
+ | 2026-05-14 Mirage + CodeGraph first-class wiki pass | **2,911,162** | Added Mirage as a shipped harness wiki/runtime page, added the CodeGraph MCP markdown page and `codegraph-agentic-codebase-analysis` skill page/body to the full LLM-wiki, added the compact dashboard neighborhood index, regenerated graph preview HTML from the current export, and refreshed exact validation counts. Current tar members: **598,193**. |
335
+ | 2026-05-18 repo refresh | **2,911,575** | Refreshed `addyosmani/agent-skills` and `bytedance/deer-flow` from current upstream SKILL.md bodies, added Addy Osmani's `doubt-driven-development` and `interview-me` skills, replaced DeerFlow's stale `vercel-deploy` entry with `vercel-deploy-claimable`, retained `Imbad0202/academic-research-skills` as existing non-commercial upstream content, and added DeerFlow as a first-class harness page/runtime page. Current tar members: **598,596**. |
336
+ | 2026-05-26 upstream repo ingest | **2,913,930** | Added `browsing-skills/browsing-skills` as a root browser skill plus 11 site-specific browser skills, refreshed `awesome-skills/code-review-skill` into `code-review-excellence` with its reference pack, refreshed `book-to-skill` through the micro-skill gate, added Presenton as both a harness and MCP server, refreshed DeerFlow's harness page, imported 190 harness catalog pages from `Picrew/awesome-agent-harness`, regenerated dashboard sqlite and preview HTML from the current export, and refreshed exact validation counts. Current tar members: **598,951**. |
337
+ | 2026-05-27 Nango catalog/tooling overlay | **2,913,960** | Added `nango-integration-catalog` as a skill page/body, added Nango hosted action-function MCP and Nango docs MCP as first-class MCP pages, connected them to API/auth/tool-calling skills, common SaaS MCPs, and agent harnesses, regenerated dashboard sqlite and preview HTML, and refreshed exact validation counts. Current tar members: **598,955**. |
338
+ | 2026-05-27 Nango semantic rescore | **2,913,960** | Replaced Nango's placeholder manual edge weights with measured MiniLM semantic cosines plus graphify-compatible tag/direct/type components. Topology unchanged; semantic edge count increased by 30 to **1,683,193**. |
339
+
340
+ The full audit history lives in `CHANGELOG.md`. The current build is
341
+ fully reproducible from the wiki content.
342
+
343
+ ## Pre-ship gates
344
+
345
+ Two advisory gates run before the tarball is repackaged. Both produce
346
+ review reports and never auto-modify the inventory.
347
+
348
+ - **`ctx-dedup-check`** — flags entity pairs (skill ↔ skill, skill ↔
349
+ agent, skill ↔ MCP, agent ↔ agent, agent ↔ MCP, MCP ↔ MCP) at or
350
+ above 0.85 cosine similarity. Incremental: keeps a `dedup-state.json`
351
+ next to the embedding cache, so follow-up runs only re-check pairs
352
+ involving entities whose content changed. Allowlist support via
353
+ `.dedup-allowlist.txt`. The current snapshot has 15,976 findings,
354
+ most of which are within-MCP near-duplicates (multiple wrappers
355
+ around the same upstream service).
356
+ - **`ctx-tag-backfill`** — finds skills/agents with empty `tags:`
357
+ frontmatter and proposes a backfill drawn from slug tokens, body
358
+ keywords, and the existing tag vocabulary. Report-only by default;
359
+ pass `--apply` to write. Backfills are additive only.
docs/marketplace-registry.md CHANGED
@@ -1,129 +1,129 @@
1
- # Entity Source Registry
2
-
3
- ctx keeps entity sources separate from install state. A source entry can be
4
- searched and recommended without being installed, and duplicate/update paths must
5
- show what would change before replacing an existing entity.
6
-
7
- ## Registered Sources
8
-
9
- ### Shipped Graph And LLM-Wiki
10
-
11
- ```yaml
12
- name: ctx-shipped-graph
13
- type: compressed-runtime
14
- paths:
15
- graph: graph/wiki-graph-runtime.tar.gz
16
- skills: graph/<skill-index>.json.gz
17
- refresh: release-time
18
- priority: 1
19
- ```
20
-
21
- The shipped runtime is the first source for recommendations. It contains the
22
- first-class skills, agents, MCP servers, harnesses, graph edges, quality scores,
23
- usage fields, and wiki pages that ctx can use offline.
24
-
25
- ### User Local Assets
26
-
27
- ```yaml
28
- name: user-local
29
- type: filesystem
30
- paths:
31
- skills: ~/.claude/skills
32
- agents: ~/.claude/agents
33
- mcp: project/user MCP config files
34
- harnesses: ~/.ctx/harnesses
35
- refresh: always current
36
- priority: 2
37
- ```
38
-
39
- Local assets override shipped suggestions when names collide, but updates
40
- still require an explicit review if replacement content is proposed.
41
-
42
- ### Skill Index
43
-
44
- ```yaml
45
- name: shipped-skills
46
- type: shipped-index
47
- shipped_entries: 89465
48
- local_index: graph/<skill-index>.json.gz
49
- hydrated_wiki: external-catalogs/<source>/catalog.json
50
- refresh: on-demand
51
- priority: 3
52
- ```
53
-
54
- Skill index entries are stored as first-class skill entities in the graph/wiki.
55
- Hydrated `SKILL.md` bodies pass through the micro-skill gate before they are
56
- packed into the shipped runtime.
57
-
58
- ### GitHub Entity Repositories
59
-
60
- ```yaml
61
- name: github-entity-repos
62
- type: git
63
- entrypoints:
64
- skills: ctx-skill-add
65
- agents: ctx-agent-add
66
- mcp: ctx-mcp-add
67
- harnesses: ctx-harness-add
68
- refresh: on-demand
69
- priority: 4
70
- ```
71
-
72
- GitHub stars, forks, releases, and update timestamps can be stored as source
73
- metadata for a candidate entity. The ctx repository's own star count is not
74
- hard-coded in docs because it changes continuously; read it from GitHub when
75
- needed.
76
-
77
- ### MCP And Harness Sources
78
-
79
- ```yaml
80
- name: mcp-and-harness-sources
81
- type: curated-source
82
- entrypoints:
83
- mcp: ctx-mcp-fetch, ctx-mcp-add
84
- harnesses: ctx-harness-add, ctx-harness-install
85
- refresh: on-demand
86
- priority: 5
87
- ```
88
-
89
- MCP servers and harnesses are recorded as entities with install guidance,
90
- permission notes, compatibility tags, and quality/security review status.
91
-
92
- ## Query Protocol
93
-
94
- When a user asks for help or the scanner detects a stack/task gap:
95
-
96
- 1. Search the local graph/wiki first.
97
- 2. Search the shipped skill index and, when needed, the `find-skills`
98
- helper for fresher remote results.
99
- 3. Search local user assets and configured entity repositories.
100
- 4. Deduplicate by slug, source URL, canonical name, tags, and semantic overlap.
101
- 5. Score candidates with the shared recommendation engine.
102
- 6. Present at most the configured cap with reasons, quality/usage notes, and
103
- install/update commands.
104
- 7. If an existing entity would be replaced, show the update review: benefits,
105
- drawbacks, changed files, security posture, and rollback path.
106
-
107
- ## Update Rules
108
-
109
- Entity updates are intentionally explicit:
110
-
111
- - `ctx-skill-add`, `ctx-agent-add`, `ctx-mcp-add`, and `ctx-harness-add` create
112
- new entities when no duplicate exists.
113
- - If a duplicate exists, the command emits an update review and refuses to
114
- replace content unless the user passes the update flag.
115
- - New or updated skills go through the micro-skill line-count gate from config.
116
- - Security/cyber checks run before entity content is promoted.
117
- - Graph/wiki artifacts are rebuilt, validated, packed, and atomically promoted.
118
-
119
- ## Security Notes
120
-
121
- - Never auto-install without user confirmation.
122
- - Always show the source URL, entity type, install command, and permissions.
123
- - Reject missing `SKILL.md` bodies for skill imports unless the source is only a
124
- catalog pointer.
125
- - Never execute repository scripts during cataloging without explicit user
126
- approval.
127
- - Warn on network, filesystem, shell, credential, or system-level permissions.
128
- - Preserve last-good graph/wiki artifacts so a failed refresh cannot ship a
129
- corrupt runtime.
 
1
+ # Entity Source Registry
2
+
3
+ ctx keeps entity sources separate from install state. A source entry can be
4
+ searched and recommended without being installed, and duplicate/update paths must
5
+ show what would change before replacing an existing entity.
6
+
7
+ ## Registered Sources
8
+
9
+ ### Shipped Graph And LLM-Wiki
10
+
11
+ ```yaml
12
+ name: ctx-shipped-graph
13
+ type: compressed-runtime
14
+ paths:
15
+ graph: graph/wiki-graph-runtime.tar.gz
16
+ skills: graph/<skill-index>.json.gz
17
+ refresh: release-time
18
+ priority: 1
19
+ ```
20
+
21
+ The shipped runtime is the first source for recommendations. It contains the
22
+ first-class skills, agents, MCP servers, harnesses, graph edges, quality scores,
23
+ usage fields, and wiki pages that ctx can use offline.
24
+
25
+ ### User Local Assets
26
+
27
+ ```yaml
28
+ name: user-local
29
+ type: filesystem
30
+ paths:
31
+ skills: ~/.claude/skills
32
+ agents: ~/.claude/agents
33
+ mcp: project/user MCP config files
34
+ harnesses: ~/.ctx/harnesses
35
+ refresh: always current
36
+ priority: 2
37
+ ```
38
+
39
+ Local assets override shipped suggestions when names collide, but updates
40
+ still require an explicit review if replacement content is proposed.
41
+
42
+ ### Skill Index
43
+
44
+ ```yaml
45
+ name: shipped-skills
46
+ type: shipped-index
47
+ shipped_entries: 89465
48
+ local_index: graph/<skill-index>.json.gz
49
+ hydrated_wiki: external-catalogs/<source>/catalog.json
50
+ refresh: on-demand
51
+ priority: 3
52
+ ```
53
+
54
+ Skill index entries are stored as first-class skill entities in the graph/wiki.
55
+ Hydrated `SKILL.md` bodies pass through the micro-skill gate before they are
56
+ packed into the shipped runtime.
57
+
58
+ ### GitHub Entity Repositories
59
+
60
+ ```yaml
61
+ name: github-entity-repos
62
+ type: git
63
+ entrypoints:
64
+ skills: ctx-skill-add
65
+ agents: ctx-agent-add
66
+ mcp: ctx-mcp-add
67
+ harnesses: ctx-harness-add
68
+ refresh: on-demand
69
+ priority: 4
70
+ ```
71
+
72
+ GitHub stars, forks, releases, and update timestamps can be stored as source
73
+ metadata for a candidate entity. The ctx repository's own star count is not
74
+ hard-coded in docs because it changes continuously; read it from GitHub when
75
+ needed.
76
+
77
+ ### MCP And Harness Sources
78
+
79
+ ```yaml
80
+ name: mcp-and-harness-sources
81
+ type: curated-source
82
+ entrypoints:
83
+ mcp: ctx-mcp-fetch, ctx-mcp-add
84
+ harnesses: ctx-harness-add, ctx-harness-install
85
+ refresh: on-demand
86
+ priority: 5
87
+ ```
88
+
89
+ MCP servers and harnesses are recorded as entities with install guidance,
90
+ permission notes, compatibility tags, and quality/security review status.
91
+
92
+ ## Query Protocol
93
+
94
+ When a user asks for help or the scanner detects a stack/task gap:
95
+
96
+ 1. Search the local graph/wiki first.
97
+ 2. Search the shipped skill index and, when needed, the `find-skills`
98
+ helper for fresher remote results.
99
+ 3. Search local user assets and configured entity repositories.
100
+ 4. Deduplicate by slug, source URL, canonical name, tags, and semantic overlap.
101
+ 5. Score candidates with the shared recommendation engine.
102
+ 6. Present at most the configured cap with reasons, quality/usage notes, and
103
+ install/update commands.
104
+ 7. If an existing entity would be replaced, show the update review: benefits,
105
+ drawbacks, changed files, security posture, and rollback path.
106
+
107
+ ## Update Rules
108
+
109
+ Entity updates are intentionally explicit:
110
+
111
+ - `ctx-skill-add`, `ctx-agent-add`, `ctx-mcp-add`, and `ctx-harness-add` create
112
+ new entities when no duplicate exists.
113
+ - If a duplicate exists, the command emits an update review and refuses to
114
+ replace content unless the user passes the update flag.
115
+ - New or updated skills go through the micro-skill line-count gate from config.
116
+ - Security/cyber checks run before entity content is promoted.
117
+ - Graph/wiki artifacts are rebuilt, validated, packed, and atomically promoted.
118
+
119
+ ## Security Notes
120
+
121
+ - Never auto-install without user confirmation.
122
+ - Always show the source URL, entity type, install command, and permissions.
123
+ - Reject missing `SKILL.md` bodies for skill imports unless the source is only a
124
+ catalog pointer.
125
+ - Never execute repository scripts during cataloging without explicit user
126
+ approval.
127
+ - Warn on network, filesystem, shell, credential, or system-level permissions.
128
+ - Preserve last-good graph/wiki artifacts so a failed refresh cannot ship a
129
+ corrupt runtime.
docs/memory-anchor.md CHANGED
@@ -1,102 +1,102 @@
1
- # Memory anchoring
2
-
3
- [`src/memory_anchor.py`](https://github.com/stevesolun/ctx/blob/main/src/memory_anchor.py)
4
- walks the auto-memory store and flags references that no longer
5
- resolve against the current repository.
6
-
7
- ## Why it exists
8
-
9
- Claude's auto-memory accumulates notes that look like:
10
-
11
- > Fixed the `add_skill()` bug in `src/skill_loader.py:42`. See also
12
- > `docs/intent-interview.md`.
13
-
14
- Those backtick references rot as the codebase moves. A renamed file, a
15
- deleted module, a moved doc — and the memory silently points at
16
- nothing. `memory_anchor` turns that silent rot into a loud dashboard.
17
-
18
- ## Where it looks
19
-
20
- Memory files live under:
21
-
22
- ```text
23
- ~/.claude/projects/<slug>/memory/*.md
24
- ```
25
-
26
- The module recursively scans that tree. You can override the root with
27
- `--memory-root` (useful for tests or multi-project setups).
28
-
29
- ## What counts as a reference
30
-
31
- Only tokens inside **backtick code spans** qualify. The heuristic is
32
- deliberately conservative to keep false positives low:
33
-
34
- - known extension (`.py`, `.md`, `.json`, `.yml`, `.ts`, `.rs`, …), or
35
- - contains a `/` with a dotted final segment.
36
-
37
- Tokens with whitespace, `()` suffixes, `http(s)://` prefixes, or leading
38
- `-` are rejected up front. A trailing `:<digits>` is parsed as a line
39
- suffix — `:` without digits is preserved (keeps Windows drive letters
40
- intact).
41
-
42
- ## How resolution works
43
-
44
- For each extracted reference, the module asks whether it resolves:
45
-
46
- 1. tilde-expand, if `~/…`
47
- 2. if absolute, does the path exist?
48
- 3. does `repo_root / path` exist?
49
- 4. does `repo_root / src / path` exist?
50
-
51
- If any candidate hits, the ref is *live*; otherwise *dead*.
52
-
53
- ## CLI
54
-
55
- ```bash
56
- # JSON report for downstream tooling
57
- python -m memory_anchor scan
58
-
59
- # Human dashboard
60
- python -m memory_anchor dashboard
61
-
62
- # CI gate: exit 2 if any dead references remain
63
- python -m memory_anchor check --strict
64
-
65
- # Override repo / memory roots
66
- python -m memory_anchor check --strict \
67
- --repo-root /path/to/repo \
68
- --memory-root /path/to/project/memory
69
- ```
70
-
71
- When `--repo-root` is omitted, the module walks upward from the current
72
- directory to the nearest `.git/` ancestor.
73
-
74
- ## Data model
75
-
76
- ```python
77
- @dataclass(frozen=True)
78
- class AnchorRef:
79
- raw: str # exactly the backtick contents
80
- path: str # path sans trailing :<line>
81
- line: int | None
82
- exists: bool
83
-
84
- @dataclass(frozen=True)
85
- class MemoryAnchorFile:
86
- memory_path: str
87
- refs: tuple[AnchorRef, ...]
88
- # derived: .live, .dead
89
-
90
- @dataclass(frozen=True)
91
- class AnchorReport:
92
- generated_at: float
93
- repo_root: str
94
- memory_root: str
95
- files: tuple[MemoryAnchorFile, ...]
96
- # derived: .all_refs, .live_count, .dead_count, .has_dead
97
- ```
98
-
99
- ## Related
100
-
101
- - [Skill health dashboard](skills-health.md) — structural and drift
102
- checks for the skill + agent catalog.
 
1
+ # Memory anchoring
2
+
3
+ [`src/memory_anchor.py`](https://github.com/stevesolun/ctx/blob/main/src/memory_anchor.py)
4
+ walks the auto-memory store and flags references that no longer
5
+ resolve against the current repository.
6
+
7
+ ## Why it exists
8
+
9
+ Claude's auto-memory accumulates notes that look like:
10
+
11
+ > Fixed the `add_skill()` bug in `src/skill_loader.py:42`. See also
12
+ > `docs/intent-interview.md`.
13
+
14
+ Those backtick references rot as the codebase moves. A renamed file, a
15
+ deleted module, a moved doc — and the memory silently points at
16
+ nothing. `memory_anchor` turns that silent rot into a loud dashboard.
17
+
18
+ ## Where it looks
19
+
20
+ Memory files live under:
21
+
22
+ ```text
23
+ ~/.claude/projects/<slug>/memory/*.md
24
+ ```
25
+
26
+ The module recursively scans that tree. You can override the root with
27
+ `--memory-root` (useful for tests or multi-project setups).
28
+
29
+ ## What counts as a reference
30
+
31
+ Only tokens inside **backtick code spans** qualify. The heuristic is
32
+ deliberately conservative to keep false positives low:
33
+
34
+ - known extension (`.py`, `.md`, `.json`, `.yml`, `.ts`, `.rs`, …), or
35
+ - contains a `/` with a dotted final segment.
36
+
37
+ Tokens with whitespace, `()` suffixes, `http(s)://` prefixes, or leading
38
+ `-` are rejected up front. A trailing `:<digits>` is parsed as a line
39
+ suffix — `:` without digits is preserved (keeps Windows drive letters
40
+ intact).
41
+
42
+ ## How resolution works
43
+
44
+ For each extracted reference, the module asks whether it resolves:
45
+
46
+ 1. tilde-expand, if `~/…`
47
+ 2. if absolute, does the path exist?
48
+ 3. does `repo_root / path` exist?
49
+ 4. does `repo_root / src / path` exist?
50
+
51
+ If any candidate hits, the ref is *live*; otherwise *dead*.
52
+
53
+ ## CLI
54
+
55
+ ```bash
56
+ # JSON report for downstream tooling
57
+ python -m memory_anchor scan
58
+
59
+ # Human dashboard
60
+ python -m memory_anchor dashboard
61
+
62
+ # CI gate: exit 2 if any dead references remain
63
+ python -m memory_anchor check --strict
64
+
65
+ # Override repo / memory roots
66
+ python -m memory_anchor check --strict \
67
+ --repo-root /path/to/repo \
68
+ --memory-root /path/to/project/memory
69
+ ```
70
+
71
+ When `--repo-root` is omitted, the module walks upward from the current
72
+ directory to the nearest `.git/` ancestor.
73
+
74
+ ## Data model
75
+
76
+ ```python
77
+ @dataclass(frozen=True)
78
+ class AnchorRef:
79
+ raw: str # exactly the backtick contents
80
+ path: str # path sans trailing :<line>
81
+ line: int | None
82
+ exists: bool
83
+
84
+ @dataclass(frozen=True)
85
+ class MemoryAnchorFile:
86
+ memory_path: str
87
+ refs: tuple[AnchorRef, ...]
88
+ # derived: .live, .dead
89
+
90
+ @dataclass(frozen=True)
91
+ class AnchorReport:
92
+ generated_at: float
93
+ repo_root: str
94
+ memory_root: str
95
+ files: tuple[MemoryAnchorFile, ...]
96
+ # derived: .all_refs, .live_count, .dead_count, .has_dead
97
+ ```
98
+
99
+ ## Related
100
+
101
+ - [Skill health dashboard](skills-health.md) — structural and drift
102
+ checks for the skill + agent catalog.
docs/skill-lifecycle-and-dashboard.md CHANGED
@@ -1,171 +1,171 @@
1
- # Skill lifecycle & KPI dashboard — install & operations
2
-
3
- One page on running the lifecycle CLI, the category backfill, and the KPI
4
- dashboard. Prerequisite: the quality scorer is installed and has written at
5
- least one sidecar. See
6
- [skill-quality-install.md](./skill-quality-install.md).
7
-
8
- ## What it does
9
-
10
- After the scorer has labeled everything, these three tools turn the
11
- labels into action:
12
-
13
- | Tool | CLI | Purpose |
14
- | ---- | --- | ------- |
15
- | `ctx_lifecycle.py` | `review`, `demote`, `archive`, `purge`, `review-archived` | Move D/F-grade skills through `active → watch → demote → archive → deleted`. |
16
- | `skill_category.py` | `backfill`, `infer` | Write the closed-set `category:` field into skill/agent frontmatter. |
17
- | `kpi_dashboard.py` | `render`, `summary` | Emit a single Markdown dashboard joined across all quality sinks. |
18
-
19
- Asymmetric gates: downward transitions are automatic from a D-streak;
20
- upward transitions are deliberate. Archive needs aging (`active` for
21
- 14 days in `_demoted`); delete needs a typed-slug confirmation even
22
- under `--auto`.
23
-
24
- ## Category taxonomy
25
-
26
- Closed set: `framework`, `language`, `tool`, `pattern`, `workflow`,
27
- `meta`. The dashboard groups scores by category so you can see, e.g.,
28
- that your `framework`-tagged skills average a B but your
29
- `workflow`-tagged skills are mostly D — which tells you where to focus
30
- curation.
31
-
32
- Inference is precedence-ordered: `python + django` → `language`
33
- (language wins over framework). The backfill **never overwrites** an
34
- existing non-empty value — human edits win.
35
-
36
- Run once after the scorer has seeded the sidecars:
37
-
38
- ```bash
39
- python -m skill_category backfill --dry-run
40
- python -m skill_category backfill # apply
41
- ```
42
-
43
- Unresolved slugs (no tag matched the taxonomy) are listed for manual
44
- curation.
45
-
46
- ## Lifecycle CLI
47
-
48
- Four verbs. All are propose-and-confirm by default; `--auto` unlocks
49
- only the safe tiers (Watch + Demote).
50
-
51
- ```bash
52
- # List every pending transition; no writes.
53
- python -m ctx_lifecycle review --dry-run
54
-
55
- # Apply all Watch/Demote transitions without prompting.
56
- python -m ctx_lifecycle review --auto
57
-
58
- # Archive a specific slug. Requires the demoted aging threshold to have passed.
59
- python -m ctx_lifecycle archive <slug>
60
-
61
- # Delete archived slugs that exceeded the delete threshold.
62
- # Requires typed-slug confirmation per entry even with --auto.
63
- python -m ctx_lifecycle purge
64
-
65
- # List archived slugs with optional diffs, or restore one.
66
- python -m ctx_lifecycle review-archived --show-diff
67
- python -m ctx_lifecycle review-archived --restore <slug>
68
- ```
69
-
70
- Filesystem moves: demote → `<skills_dir>/_demoted/<slug>/`, archive →
71
- `<skills_dir>/_archive/<slug>/`. The scanner skips directories starting
72
- with `_`, so demoted/archived skills no longer show up to the router.
73
-
74
- Lifecycle state is persisted in a sibling sidecar at
75
- `~/.claude/skill-quality/<slug>.lifecycle.json`. Each transition is
76
- folded into the `history` array (capped at `history_max`) so you can
77
- audit how a slug ended up where it did.
78
-
79
- ### The D-streak
80
-
81
- A skill needs `consecutive_d_to_demote` consecutive D-or-F grades to
82
- trigger a demote proposal. Any A/B/C grade resets the streak to 0. The
83
- default is 2 — one bad session is a blip, two in a row is a trend.
84
-
85
- ## KPI dashboard
86
-
87
- Pure read-only. Walks both quality sidecars and lifecycle sidecars,
88
- joins them against `category:` in frontmatter (with inference
89
- fallback), and emits Markdown or JSON.
90
-
91
- ```bash
92
- # Dump Markdown to stdout.
93
- python -m kpi_dashboard render
94
-
95
- # Persist to a file — good target for the cron / pre-push hook.
96
- python -m kpi_dashboard render --out ~/.claude/skill-quality/kpi.md
97
-
98
- # Machine-readable.
99
- python -m kpi_dashboard render --json --out kpi.json
100
-
101
- # Terse one-screen summary.
102
- python -m kpi_dashboard summary
103
- ```
104
-
105
- ### What's in the report
106
-
107
- - **Grade distribution** — A/B/C/D/F counts + percentages. Blank grade
108
- (no score yet) rolls up to F so it surfaces in the "needs
109
- attention" bucket.
110
- - **Lifecycle tiers** — counts across active/watch/demote/archive.
111
- - **Hard floors active** — how many slugs are failing intake or
112
- never-loaded-stale.
113
- - **By category** — per-category count, average score of
114
- scored entries, and a mini A/B/C/D/F mix table.
115
- - **Top demotion candidates** — up to `--limit N` (default 10) active
116
- or watch-tier entries sorted by (D-streak desc, score asc). These
117
- are the first slugs `ctx_lifecycle review --auto` will act on.
118
- - **Archived (restorable)** — every slug currently in the archive
119
- tier; still recoverable via `review-archived --restore <slug>` until
120
- `purge` deletes them.
121
-
122
- ## Configuration
123
-
124
- All knobs live under `quality` in `src/config.json`:
125
-
126
- ```json
127
- {
128
- "quality": {
129
- "lifecycle": {
130
- "archive_threshold_days": 14.0,
131
- "delete_threshold_days": 60.0,
132
- "consecutive_d_to_demote": 2,
133
- "demoted_subdir": "_demoted",
134
- "archive_subdir": "_archive",
135
- "history_max": 20
136
- },
137
- "dashboard": {
138
- "default_top_n": 10,
139
- "report_path": "~/.claude/skill-quality/kpi.md"
140
- }
141
- }
142
- }
143
- ```
144
-
145
- Tighten `consecutive_d_to_demote` to 1 for aggressive pruning, or
146
- loosen `archive_threshold_days` if you want a longer grace window
147
- before a demoted skill gets archived.
148
-
149
- ## Operational cadence
150
-
151
- A reasonable default rhythm, given the defaults above:
152
-
153
- - **Every session** — scorer hook runs automatically on session end.
154
- - **Weekly** — `ctx_lifecycle review --auto` to sweep Watch/Demote.
155
- - **Weekly** — `kpi_dashboard render --out …/kpi.md` for the digest.
156
- - **Monthly** — `ctx_lifecycle review` (no `--auto`) to surface
157
- archive-ready demoted skills for manual approval.
158
- - **Quarterly** — `ctx_lifecycle purge` with typed-slug confirmation
159
- to actually remove archived skills past the delete threshold.
160
-
161
- ## Troubleshooting
162
-
163
- - **"unresolved" in backfill output** — the skill's tags don't match
164
- the taxonomy. Either add a matching tag (e.g. `python`) or set
165
- `category:` manually in frontmatter.
166
- - **Dashboard shows skills as F with no score** — they have a
167
- lifecycle sidecar but no quality sidecar. That's intentional:
168
- archived slugs whose quality sidecar was cleaned up still appear
169
- in the tier and archive sections so you can restore them.
170
- - **`review --auto` refuses to archive or delete** — by design. Those
171
- tiers require human approval.
 
1
+ # Skill lifecycle & KPI dashboard — install & operations
2
+
3
+ One page on running the lifecycle CLI, the category backfill, and the KPI
4
+ dashboard. Prerequisite: the quality scorer is installed and has written at
5
+ least one sidecar. See
6
+ [skill-quality-install.md](./skill-quality-install.md).
7
+
8
+ ## What it does
9
+
10
+ After the scorer has labeled everything, these three tools turn the
11
+ labels into action:
12
+
13
+ | Tool | CLI | Purpose |
14
+ | ---- | --- | ------- |
15
+ | `ctx_lifecycle.py` | `review`, `demote`, `archive`, `purge`, `review-archived` | Move D/F-grade skills through `active → watch → demote → archive → deleted`. |
16
+ | `skill_category.py` | `backfill`, `infer` | Write the closed-set `category:` field into skill/agent frontmatter. |
17
+ | `kpi_dashboard.py` | `render`, `summary` | Emit a single Markdown dashboard joined across all quality sinks. |
18
+
19
+ Asymmetric gates: downward transitions are automatic from a D-streak;
20
+ upward transitions are deliberate. Archive needs aging (`active` for
21
+ 14 days in `_demoted`); delete needs a typed-slug confirmation even
22
+ under `--auto`.
23
+
24
+ ## Category taxonomy
25
+
26
+ Closed set: `framework`, `language`, `tool`, `pattern`, `workflow`,
27
+ `meta`. The dashboard groups scores by category so you can see, e.g.,
28
+ that your `framework`-tagged skills average a B but your
29
+ `workflow`-tagged skills are mostly D — which tells you where to focus
30
+ curation.
31
+
32
+ Inference is precedence-ordered: `python + django` → `language`
33
+ (language wins over framework). The backfill **never overwrites** an
34
+ existing non-empty value — human edits win.
35
+
36
+ Run once after the scorer has seeded the sidecars:
37
+
38
+ ```bash
39
+ python -m skill_category backfill --dry-run
40
+ python -m skill_category backfill # apply
41
+ ```
42
+
43
+ Unresolved slugs (no tag matched the taxonomy) are listed for manual
44
+ curation.
45
+
46
+ ## Lifecycle CLI
47
+
48
+ Four verbs. All are propose-and-confirm by default; `--auto` unlocks
49
+ only the safe tiers (Watch + Demote).
50
+
51
+ ```bash
52
+ # List every pending transition; no writes.
53
+ python -m ctx_lifecycle review --dry-run
54
+
55
+ # Apply all Watch/Demote transitions without prompting.
56
+ python -m ctx_lifecycle review --auto
57
+
58
+ # Archive a specific slug. Requires the demoted aging threshold to have passed.
59
+ python -m ctx_lifecycle archive <slug>
60
+
61
+ # Delete archived slugs that exceeded the delete threshold.
62
+ # Requires typed-slug confirmation per entry even with --auto.
63
+ python -m ctx_lifecycle purge
64
+
65
+ # List archived slugs with optional diffs, or restore one.
66
+ python -m ctx_lifecycle review-archived --show-diff
67
+ python -m ctx_lifecycle review-archived --restore <slug>
68
+ ```
69
+
70
+ Filesystem moves: demote → `<skills_dir>/_demoted/<slug>/`, archive →
71
+ `<skills_dir>/_archive/<slug>/`. The scanner skips directories starting
72
+ with `_`, so demoted/archived skills no longer show up to the router.
73
+
74
+ Lifecycle state is persisted in a sibling sidecar at
75
+ `~/.claude/skill-quality/<slug>.lifecycle.json`. Each transition is
76
+ folded into the `history` array (capped at `history_max`) so you can
77
+ audit how a slug ended up where it did.
78
+
79
+ ### The D-streak
80
+
81
+ A skill needs `consecutive_d_to_demote` consecutive D-or-F grades to
82
+ trigger a demote proposal. Any A/B/C grade resets the streak to 0. The
83
+ default is 2 — one bad session is a blip, two in a row is a trend.
84
+
85
+ ## KPI dashboard
86
+
87
+ Pure read-only. Walks both quality sidecars and lifecycle sidecars,
88
+ joins them against `category:` in frontmatter (with inference
89
+ fallback), and emits Markdown or JSON.
90
+
91
+ ```bash
92
+ # Dump Markdown to stdout.
93
+ python -m kpi_dashboard render
94
+
95
+ # Persist to a file — good target for the cron / pre-push hook.
96
+ python -m kpi_dashboard render --out ~/.claude/skill-quality/kpi.md
97
+
98
+ # Machine-readable.
99
+ python -m kpi_dashboard render --json --out kpi.json
100
+
101
+ # Terse one-screen summary.
102
+ python -m kpi_dashboard summary
103
+ ```
104
+
105
+ ### What's in the report
106
+
107
+ - **Grade distribution** — A/B/C/D/F counts + percentages. Blank grade
108
+ (no score yet) rolls up to F so it surfaces in the "needs
109
+ attention" bucket.
110
+ - **Lifecycle tiers** — counts across active/watch/demote/archive.
111
+ - **Hard floors active** — how many slugs are failing intake or
112
+ never-loaded-stale.
113
+ - **By category** — per-category count, average score of
114
+ scored entries, and a mini A/B/C/D/F mix table.
115
+ - **Top demotion candidates** — up to `--limit N` (default 10) active
116
+ or watch-tier entries sorted by (D-streak desc, score asc). These
117
+ are the first slugs `ctx_lifecycle review --auto` will act on.
118
+ - **Archived (restorable)** — every slug currently in the archive
119
+ tier; still recoverable via `review-archived --restore <slug>` until
120
+ `purge` deletes them.
121
+
122
+ ## Configuration
123
+
124
+ All knobs live under `quality` in `src/config.json`:
125
+
126
+ ```json
127
+ {
128
+ "quality": {
129
+ "lifecycle": {
130
+ "archive_threshold_days": 14.0,
131
+ "delete_threshold_days": 60.0,
132
+ "consecutive_d_to_demote": 2,
133
+ "demoted_subdir": "_demoted",
134
+ "archive_subdir": "_archive",
135
+ "history_max": 20
136
+ },
137
+ "dashboard": {
138
+ "default_top_n": 10,
139
+ "report_path": "~/.claude/skill-quality/kpi.md"
140
+ }
141
+ }
142
+ }
143
+ ```
144
+
145
+ Tighten `consecutive_d_to_demote` to 1 for aggressive pruning, or
146
+ loosen `archive_threshold_days` if you want a longer grace window
147
+ before a demoted skill gets archived.
148
+
149
+ ## Operational cadence
150
+
151
+ A reasonable default rhythm, given the defaults above:
152
+
153
+ - **Every session** — scorer hook runs automatically on session end.
154
+ - **Weekly** — `ctx_lifecycle review --auto` to sweep Watch/Demote.
155
+ - **Weekly** — `kpi_dashboard render --out …/kpi.md` for the digest.
156
+ - **Monthly** — `ctx_lifecycle review` (no `--auto`) to surface
157
+ archive-ready demoted skills for manual approval.
158
+ - **Quarterly** — `ctx_lifecycle purge` with typed-slug confirmation
159
+ to actually remove archived skills past the delete threshold.
160
+
161
+ ## Troubleshooting
162
+
163
+ - **"unresolved" in backfill output** — the skill's tags don't match
164
+ the taxonomy. Either add a matching tag (e.g. `python`) or set
165
+ `category:` manually in frontmatter.
166
+ - **Dashboard shows skills as F with no score** — they have a
167
+ lifecycle sidecar but no quality sidecar. That's intentional:
168
+ archived slugs whose quality sidecar was cleaned up still appear
169
+ in the tier and archive sections so you can restore them.
170
+ - **`review --auto` refuses to archive or delete** — by design. Those
171
+ tiers require human approval.
docs/skill-quality-install.md CHANGED
@@ -1,170 +1,170 @@
1
- # Skill quality — install & operations
2
-
3
- One page on running the quality scorer: install the Stop hook, seed the
4
- sidecars, and verify the data flows into the wiki and the knowledge graph.
5
-
6
- ## What it does
7
-
8
- Every installed skill and agent gets a continuous quality score in
9
- `[0.0, 1.0]` plus an A/B/C/D/F letter grade, derived from four signals:
10
-
11
- | Signal | Weight | What it measures |
12
- | --------- | -----: | ----------------------------------------------------- |
13
- | telemetry | 0.40 | Load count, recency, freshness in `skill-events.jsonl`|
14
- | intake | 0.20 | Live re-run of the six install-time structural checks |
15
- | graph | 0.25 | Degree + average edge weight in the wiki graph |
16
- | routing | 0.15 | Router hit-rate (neutral prior below 3 observations) |
17
-
18
- Two hard floors override the weighted sum:
19
-
20
- - **`intake_fail`** — any structural check is currently failing → grade **F**.
21
- Grade F is **only** produced by this hard floor; it is never returned by
22
- the score-to-grade mapping function alone. A score of 0.0 maps to **D**.
23
- - **`never_loaded_stale`** — no load events ever → grade capped at **D**.
24
-
25
- The score is mirrored to three on-disk sinks so every consumer sees the
26
- same number:
27
-
28
- 1. `~/.claude/skill-quality/<slug>.json` — canonical machine-readable form.
29
- 2. Wiki entity frontmatter — `quality_score`, `quality_grade`, `quality_updated_at`.
30
- 3. Wiki body — a `## Quality` block between `<!-- quality:begin -->` markers.
31
-
32
- The knowledge-graph node attribute is a **separate consumer path**, not a
33
- write path from `persist_quality`: `wiki_graphify` reads the sidecar JSON
34
- produced by sink 1 and attaches `quality_score` / `quality_grade` to each
35
- node on its next build.
36
-
37
- ## Register the Stop hook
38
-
39
- The hook runs once per session-end. It reads `skill-events.jsonl` since
40
- its last run, collects every slug that appeared, and calls
41
- `skill_quality.py recompute --slugs <comma-list>` — so scoring is
42
- incremental (touched skills only), not a full 2,000-page sweep.
43
-
44
- Edit `~/.claude/settings.json` and add, replacing `<REPO>` with the
45
- absolute path to this checkout (use forward slashes on Windows):
46
-
47
- ```json
48
- {
49
- "hooks": {
50
- "Stop": [
51
- {
52
- "hooks": [
53
- {
54
- "type": "command",
55
- "command": "python <REPO>/hooks/quality_on_session_end.py"
56
- }
57
- ]
58
- }
59
- ]
60
- }
61
- }
62
- ```
63
-
64
- The hook always exits 0: a scoring error will not block session
65
- shutdown.
66
-
67
- ## Seed the sidecars (first run only)
68
-
69
- Run once after install so every installed skill has a baseline score:
70
-
71
- ```bash
72
- ctx-skill-quality recompute --all
73
- ```
74
-
75
- This walks `~/.claude/skills/*/SKILL.md` and `~/.claude/agents/*.md`,
76
- scores each, and writes the three on-disk sinks. Expect ~15–30s depending on
77
- corpus size and disk.
78
-
79
- ## CLI reference
80
-
81
- ```bash
82
- # Full recompute (use sparingly; the Stop hook handles incrementals).
83
- ctx-skill-quality recompute --all
84
-
85
- # One slug.
86
- ctx-skill-quality recompute --slug python-testing
87
-
88
- # Show the most recent score.
89
- ctx-skill-quality show python-testing
90
-
91
- # Signal-by-signal breakdown with evidence.
92
- ctx-skill-quality explain python-testing
93
-
94
- # List every slug with its grade, filtered.
95
- ctx-skill-quality list --grade D
96
- ```
97
-
98
- All verbs accept `--json` for piping into other tools.
99
-
100
- ## Graph integration
101
-
102
- `wiki_graphify.py` reads the sidecar directory automatically and
103
- attaches `quality_score` and `quality_grade` to every matching node. The
104
- Obsidian graph view can then color nodes by grade — configure the
105
- `quality_grade` property in Obsidian's graph settings.
106
-
107
- Nodes without a sidecar get `quality_score: null` and `quality_grade:
108
- null` so downstream consumers can always read the attribute safely.
109
-
110
- ## Configuration
111
-
112
- All knobs live in `src/config.json` under the top-level `quality` key:
113
-
114
- ```json
115
- {
116
- "quality": {
117
- "weights": {
118
- "telemetry": 0.40, "intake": 0.20, "graph": 0.25, "routing": 0.15
119
- },
120
- "agent_weights": {
121
- "telemetry": 0.15, "intake": 0.30, "graph": 0.35, "routing": 0.20
122
- },
123
- "grade_thresholds": {"A": 0.80, "B": 0.60, "C": 0.40},
124
- "stale_threshold_days": 30.0,
125
- "recent_window_days": 14.0,
126
- "min_body_chars": 120,
127
- "paths": {
128
- "sidecar_dir": "~/.claude/skill-quality",
129
- "router_trace": "~/.claude/router-trace.jsonl"
130
- }
131
- }
132
- }
133
- ```
134
-
135
- `ctx_config.Config` exposes this through `cfg.get("quality", {})`. User
136
- overrides in `~/.claude/skill-system-config.json` deep-merge over the
137
- repo defaults, so you can pin only the keys you want to change.
138
-
139
- Both weight vectors must sum to 1.0 (±0.01) and grade thresholds must
140
- satisfy `0 ≤ C ≤ B ≤ A ≤ 1` — `QualityConfig.__post_init__` will raise
141
- on bad values, catching typos before they pollute sidecars.
142
-
143
- ### Why two weight vectors
144
-
145
- Skills and agents differ in how they're invoked. Skills are loaded
146
- automatically by the router, so **telemetry** (load counts, recency) is
147
- the strongest post-install quality signal — hence 0.40 weight.
148
-
149
- Agents are invoked via the Agent tool, deliberately and rarely. A
150
- seldom-used agent isn't stale, it's specialized. The agent weights
151
- shift mass onto **graph connectedness** (0.35) and **intake structure**
152
- (0.30) so agents aren't penalized for having an empty telemetry stream.
153
- The `never_loaded_stale` hard floor, which caps skills at D when they
154
- have zero load events, does **not** apply to agents for the same
155
- reason.
156
-
157
- ## Troubleshooting
158
-
159
- - **Every skill grades D.** Telemetry hasn't accumulated enough load
160
- events yet. This is expected on a fresh install; the stop-hook will
161
- pick up real usage over the next few sessions.
162
- - **A recently-edited skill now grades F.** Open the sidecar and look
163
- at `signals.intake.evidence.checks` — one of the six structural
164
- checks is failing. Fix the file and rerun `recompute --slug <name>`.
165
- - **Wiki page has two `## Quality` sections.** Shouldn't happen —
166
- `persist_quality` is idempotent via the HTML-comment markers. If it
167
- does, delete both blocks and rerun `recompute`; the first pass will
168
- re-emit exactly one.
169
- - **Graph view shows no color.** Run `ctx-wiki-graphify
170
- --graph-only` to rebuild; it reads sidecars fresh on every build.
 
1
+ # Skill quality — install & operations
2
+
3
+ One page on running the quality scorer: install the Stop hook, seed the
4
+ sidecars, and verify the data flows into the wiki and the knowledge graph.
5
+
6
+ ## What it does
7
+
8
+ Every installed skill and agent gets a continuous quality score in
9
+ `[0.0, 1.0]` plus an A/B/C/D/F letter grade, derived from four signals:
10
+
11
+ | Signal | Weight | What it measures |
12
+ | --------- | -----: | ----------------------------------------------------- |
13
+ | telemetry | 0.40 | Load count, recency, freshness in `skill-events.jsonl`|
14
+ | intake | 0.20 | Live re-run of the six install-time structural checks |
15
+ | graph | 0.25 | Degree + average edge weight in the wiki graph |
16
+ | routing | 0.15 | Router hit-rate (neutral prior below 3 observations) |
17
+
18
+ Two hard floors override the weighted sum:
19
+
20
+ - **`intake_fail`** — any structural check is currently failing → grade **F**.
21
+ Grade F is **only** produced by this hard floor; it is never returned by
22
+ the score-to-grade mapping function alone. A score of 0.0 maps to **D**.
23
+ - **`never_loaded_stale`** — no load events ever → grade capped at **D**.
24
+
25
+ The score is mirrored to three on-disk sinks so every consumer sees the
26
+ same number:
27
+
28
+ 1. `~/.claude/skill-quality/<slug>.json` — canonical machine-readable form.
29
+ 2. Wiki entity frontmatter — `quality_score`, `quality_grade`, `quality_updated_at`.
30
+ 3. Wiki body — a `## Quality` block between `<!-- quality:begin -->` markers.
31
+
32
+ The knowledge-graph node attribute is a **separate consumer path**, not a
33
+ write path from `persist_quality`: `wiki_graphify` reads the sidecar JSON
34
+ produced by sink 1 and attaches `quality_score` / `quality_grade` to each
35
+ node on its next build.
36
+
37
+ ## Register the Stop hook
38
+
39
+ The hook runs once per session-end. It reads `skill-events.jsonl` since
40
+ its last run, collects every slug that appeared, and calls
41
+ `skill_quality.py recompute --slugs <comma-list>` — so scoring is
42
+ incremental (touched skills only), not a full 2,000-page sweep.
43
+
44
+ Edit `~/.claude/settings.json` and add, replacing `<REPO>` with the
45
+ absolute path to this checkout (use forward slashes on Windows):
46
+
47
+ ```json
48
+ {
49
+ "hooks": {
50
+ "Stop": [
51
+ {
52
+ "hooks": [
53
+ {
54
+ "type": "command",
55
+ "command": "python <REPO>/hooks/quality_on_session_end.py"
56
+ }
57
+ ]
58
+ }
59
+ ]
60
+ }
61
+ }
62
+ ```
63
+
64
+ The hook always exits 0: a scoring error will not block session
65
+ shutdown.
66
+
67
+ ## Seed the sidecars (first run only)
68
+
69
+ Run once after install so every installed skill has a baseline score:
70
+
71
+ ```bash
72
+ ctx-skill-quality recompute --all
73
+ ```
74
+
75
+ This walks `~/.claude/skills/*/SKILL.md` and `~/.claude/agents/*.md`,
76
+ scores each, and writes the three on-disk sinks. Expect ~15–30s depending on
77
+ corpus size and disk.
78
+
79
+ ## CLI reference
80
+
81
+ ```bash
82
+ # Full recompute (use sparingly; the Stop hook handles incrementals).
83
+ ctx-skill-quality recompute --all
84
+
85
+ # One slug.
86
+ ctx-skill-quality recompute --slug python-testing
87
+
88
+ # Show the most recent score.
89
+ ctx-skill-quality show python-testing
90
+
91
+ # Signal-by-signal breakdown with evidence.
92
+ ctx-skill-quality explain python-testing
93
+
94
+ # List every slug with its grade, filtered.
95
+ ctx-skill-quality list --grade D
96
+ ```
97
+
98
+ All verbs accept `--json` for piping into other tools.
99
+
100
+ ## Graph integration
101
+
102
+ `wiki_graphify.py` reads the sidecar directory automatically and
103
+ attaches `quality_score` and `quality_grade` to every matching node. The
104
+ Obsidian graph view can then color nodes by grade — configure the
105
+ `quality_grade` property in Obsidian's graph settings.
106
+
107
+ Nodes without a sidecar get `quality_score: null` and `quality_grade:
108
+ null` so downstream consumers can always read the attribute safely.
109
+
110
+ ## Configuration
111
+
112
+ All knobs live in `src/config.json` under the top-level `quality` key:
113
+
114
+ ```json
115
+ {
116
+ "quality": {
117
+ "weights": {
118
+ "telemetry": 0.40, "intake": 0.20, "graph": 0.25, "routing": 0.15
119
+ },
120
+ "agent_weights": {
121
+ "telemetry": 0.15, "intake": 0.30, "graph": 0.35, "routing": 0.20
122
+ },
123
+ "grade_thresholds": {"A": 0.80, "B": 0.60, "C": 0.40},
124
+ "stale_threshold_days": 30.0,
125
+ "recent_window_days": 14.0,
126
+ "min_body_chars": 120,
127
+ "paths": {
128
+ "sidecar_dir": "~/.claude/skill-quality",
129
+ "router_trace": "~/.claude/router-trace.jsonl"
130
+ }
131
+ }
132
+ }
133
+ ```
134
+
135
+ `ctx_config.Config` exposes this through `cfg.get("quality", {})`. User
136
+ overrides in `~/.claude/skill-system-config.json` deep-merge over the
137
+ repo defaults, so you can pin only the keys you want to change.
138
+
139
+ Both weight vectors must sum to 1.0 (±0.01) and grade thresholds must
140
+ satisfy `0 ≤ C ≤ B ≤ A ≤ 1` — `QualityConfig.__post_init__` will raise
141
+ on bad values, catching typos before they pollute sidecars.
142
+
143
+ ### Why two weight vectors
144
+
145
+ Skills and agents differ in how they're invoked. Skills are loaded
146
+ automatically by the router, so **telemetry** (load counts, recency) is
147
+ the strongest post-install quality signal — hence 0.40 weight.
148
+
149
+ Agents are invoked via the Agent tool, deliberately and rarely. A
150
+ seldom-used agent isn't stale, it's specialized. The agent weights
151
+ shift mass onto **graph connectedness** (0.35) and **intake structure**
152
+ (0.30) so agents aren't penalized for having an empty telemetry stream.
153
+ The `never_loaded_stale` hard floor, which caps skills at D when they
154
+ have zero load events, does **not** apply to agents for the same
155
+ reason.
156
+
157
+ ## Troubleshooting
158
+
159
+ - **Every skill grades D.** Telemetry hasn't accumulated enough load
160
+ events yet. This is expected on a fresh install; the stop-hook will
161
+ pick up real usage over the next few sessions.
162
+ - **A recently-edited skill now grades F.** Open the sidecar and look
163
+ at `signals.intake.evidence.checks` — one of the six structural
164
+ checks is failing. Fix the file and rerun `recompute --slug <name>`.
165
+ - **Wiki page has two `## Quality` sections.** Shouldn't happen —
166
+ `persist_quality` is idempotent via the HTML-comment markers. If it
167
+ does, delete both blocks and rerun `recompute`; the first pass will
168
+ re-emit exactly one.
169
+ - **Graph view shows no color.** Run `ctx-wiki-graphify
170
+ --graph-only` to rebuild; it reads sidecars fresh on every build.
docs/skill-router/index.md CHANGED
@@ -1,51 +1,51 @@
1
- # Skill router
2
-
3
- The skill router decides which skills, agents, and MCP servers are useful for
4
- the active repository and current development task. Harnesses are recommended in
5
- the custom-model onboarding flow; after a harness is attached, the same capped
6
- skills/agents/MCP recommendation layer can be used by that host.
7
-
8
- ## Problem
9
-
10
- Every loaded skill, agent, and MCP server costs tokens, attention, and tool
11
- surface area. Most sessions need a small top-scored bundle from the 91K+ skills,
12
- 460+ agents, and 10K+ MCP servers in the shipped graph, not the whole inventory.
13
- Loading too much:
14
-
15
- - wastes context on irrelevant instructions,
16
- - causes the wrong helper to trigger for a task,
17
- - slows response time, and
18
- - creates conflicting instructions between helpers.
19
-
20
- ## Architecture
21
-
22
- ```text
23
- ctx/
24
- |-- src/scan_repo.py # Repo scanner -> stack profile
25
- |-- src/ctx/core/resolve/resolve_skills.py # Profile -> load/unload manifest
26
- |-- src/ctx/core/resolve/recommendations.py # Shared recommendation engine
27
- |-- src/ctx/adapters/ # Claude Code hooks + generic tools
28
- `-- graph/wiki-graph-runtime.tar.gz # Shipped graph/wiki runtime
29
- ```
30
-
31
- ## Flow
32
-
33
- 1. `ctx-scan-repo --repo . --recommend` scans the repository and produces stack signals.
34
- 2. The shared resolver scores graph/wiki entities by tags, categories, semantic
35
- edges, usage, quality, and configured gates.
36
- 3. The resolver returns a capped manifest: what to load, what to unload, and why.
37
- 4. The user confirms load/unload changes unless they configured automatic mode.
38
- 5. Usage and quality signals are recorded so future recommendations improve.
39
-
40
- The same recommender is used by the CLI, MCP/library tools, Claude Code hooks,
41
- and attached harness hosts. Entry points should differ only in transport and
42
- confirmation UX, not in ranking logic.
43
-
44
- ## Reference Pages
45
-
46
- - [Stack signatures](../stack-signatures.md) - file/config patterns used to
47
- identify stack signals.
48
- - [Skill-stack matrix](../skill-stack-matrix.md) - stack-to-capability mapping
49
- used as scanner evidence.
50
- - [Entity source registry](../marketplace-registry.md) - skill, GitHub,
51
- MCP, harness, and local sources plus update rules.
 
1
+ # Skill router
2
+
3
+ The skill router decides which skills, agents, and MCP servers are useful for
4
+ the active repository and current development task. Harnesses are recommended in
5
+ the custom-model onboarding flow; after a harness is attached, the same capped
6
+ skills/agents/MCP recommendation layer can be used by that host.
7
+
8
+ ## Problem
9
+
10
+ Every loaded skill, agent, and MCP server costs tokens, attention, and tool
11
+ surface area. Most sessions need a small top-scored bundle from the 91K+ skills,
12
+ 460+ agents, and 10K+ MCP servers in the shipped graph, not the whole inventory.
13
+ Loading too much:
14
+
15
+ - wastes context on irrelevant instructions,
16
+ - causes the wrong helper to trigger for a task,
17
+ - slows response time, and
18
+ - creates conflicting instructions between helpers.
19
+
20
+ ## Architecture
21
+
22
+ ```text
23
+ ctx/
24
+ |-- src/scan_repo.py # Repo scanner -> stack profile
25
+ |-- src/ctx/core/resolve/resolve_skills.py # Profile -> load/unload manifest
26
+ |-- src/ctx/core/resolve/recommendations.py # Shared recommendation engine
27
+ |-- src/ctx/adapters/ # Claude Code hooks + generic tools
28
+ `-- graph/wiki-graph-runtime.tar.gz # Shipped graph/wiki runtime
29
+ ```
30
+
31
+ ## Flow
32
+
33
+ 1. `ctx-scan-repo --repo . --recommend` scans the repository and produces stack signals.
34
+ 2. The shared resolver scores graph/wiki entities by tags, categories, semantic
35
+ edges, usage, quality, and configured gates.
36
+ 3. The resolver returns a capped manifest: what to load, what to unload, and why.
37
+ 4. The user confirms load/unload changes unless they configured automatic mode.
38
+ 5. Usage and quality signals are recorded so future recommendations improve.
39
+
40
+ The same recommender is used by the CLI, MCP/library tools, Claude Code hooks,
41
+ and attached harness hosts. Entry points should differ only in transport and
42
+ confirmation UX, not in ranking logic.
43
+
44
+ ## Reference Pages
45
+
46
+ - [Stack signatures](../stack-signatures.md) - file/config patterns used to
47
+ identify stack signals.
48
+ - [Skill-stack matrix](../skill-stack-matrix.md) - stack-to-capability mapping
49
+ used as scanner evidence.
50
+ - [Entity source registry](../marketplace-registry.md) - skill, GitHub,
51
+ MCP, harness, and local sources plus update rules.
docs/skill-stack-matrix.md CHANGED
@@ -1,166 +1,166 @@
1
- # Skill-Stack Matrix
2
-
3
- > Maps stack identifiers to the skills that serve them.
4
- > Used as resolver evidence; final ranking still goes through the shared
5
- > recommendation engine and graph/wiki scores.
6
-
7
- ## Table of Contents
8
- 1. [Matrix Format](#matrix-format)
9
- 2. [The Matrix](#the-matrix)
10
- 3. [Companion Rules](#companion-rules)
11
- 4. [Conflict Rules](#conflict-rules)
12
-
13
- ---
14
-
15
- ## Matrix Format
16
-
17
- Each entry:
18
- - **Stack IDs**: which detected stacks trigger this skill
19
- - **Skill**: skill/entity slug in the graph/wiki catalog
20
- - **Priority Base**: starting priority before signal boosts
21
- - **Required**: must-load if stack detected, vs nice-to-have
22
- - **Companions**: skills that should co-load
23
- - **Conflicts**: skills that should not co-load
24
-
25
- ## The Matrix
26
-
27
- ### Document Creation Skills
28
-
29
- | Skill | Stack IDs | Priority | Required | Path Pattern |
30
- |-------|-----------|----------|----------|--------------|
31
- | docx | (any -- triggered by user request) | 2 | no | graph/wiki or local skill path |
32
- | pdf | (any -- triggered by user request) | 2 | no | graph/wiki or local skill path |
33
- | pptx | (any -- triggered by user request) | 2 | no | graph/wiki or local skill path |
34
- | xlsx | (any -- triggered by user request) | 2 | no | graph/wiki or local skill path |
35
-
36
- > Note: document skills are demand-loaded, not stack-loaded. They activate on user
37
- > request ("make a presentation") not on repo content. The router keeps them in a
38
- > "standby" pool -- not loaded into context, but available for instant load.
39
-
40
- ### Frontend Skills
41
-
42
- | Skill | Stack IDs | Priority | Required |
43
- |-------|-----------|----------|----------|
44
- | frontend-design | react, vue, angular, svelte, nextjs, nuxt, html, css | 8 | yes |
45
- | react | react, nextjs | 7 | yes |
46
- | vue | vue, nuxt | 7 | yes |
47
- | angular | angular | 7 | yes |
48
- | svelte | svelte | 7 | yes |
49
- | tailwind | tailwindcss | 5 | no |
50
- | css-modules | css-modules | 4 | no |
51
-
52
- ### Backend Skills
53
-
54
- | Skill | Stack IDs | Priority | Required |
55
- |-------|-----------|----------|----------|
56
- | fastapi | fastapi | 8 | yes |
57
- | django | django | 8 | yes |
58
- | flask | flask | 7 | yes |
59
- | express | express | 8 | yes |
60
- | nestjs | nestjs | 8 | yes |
61
- | rails | rails | 8 | yes |
62
- | gin | gin | 7 | yes |
63
- | actix | actix | 7 | yes |
64
-
65
- ### Data Skills
66
-
67
- | Skill | Stack IDs | Priority | Required |
68
- |-------|-----------|----------|----------|
69
- | sqlalchemy | sqlalchemy, alembic | 6 | yes |
70
- | prisma | prisma | 6 | yes |
71
- | typeorm | typeorm | 6 | yes |
72
- | drizzle | drizzle | 6 | yes |
73
- | redis | redis | 4 | no |
74
- | kafka | kafka | 5 | no |
75
- | dbt | dbt | 6 | yes |
76
-
77
- ### Infrastructure Skills
78
-
79
- | Skill | Stack IDs | Priority | Required |
80
- |-------|-----------|----------|----------|
81
- | docker | docker, docker-compose | 6 | yes |
82
- | kubernetes | kubernetes, helm, kustomize | 6 | yes |
83
- | terraform | terraform | 7 | yes |
84
- | github-actions | github-actions | 5 | yes |
85
- | gitlab-ci | gitlab-ci | 5 | yes |
86
- | aws | aws-cdk, aws-sam | 7 | yes |
87
- | vercel | vercel | 4 | no |
88
-
89
- ### AI/Agent Skills
90
-
91
- | Skill | Stack IDs | Priority | Required |
92
- |-------|-----------|----------|----------|
93
- | langchain | langchain | 7 | yes |
94
- | llamaindex | llamaindex | 7 | yes |
95
- | mcp-dev | mcp | 7 | yes |
96
- | pytorch | pytorch | 6 | yes |
97
- | huggingface | huggingface | 6 | yes |
98
- | openai-sdk | openai-sdk | 5 | no |
99
- | anthropic-sdk | anthropic-sdk | 5 | no |
100
-
101
- ### Quality Skills
102
-
103
- | Skill | Stack IDs | Priority | Required |
104
- |-------|-----------|----------|----------|
105
- | pytest | pytest | 5 | yes |
106
- | jest | jest, vitest | 5 | yes |
107
- | cypress | cypress | 4 | no |
108
- | playwright | playwright | 4 | no |
109
- | eslint | eslint | 3 | no |
110
- | ruff | ruff | 3 | no |
111
-
112
- ### Documentation Skills
113
-
114
- | Skill | Stack IDs | Priority | Required |
115
- |-------|-----------|----------|----------|
116
- | openapi | openapi | 5 | yes |
117
- | graphql | graphql | 5 | yes |
118
- | mkdocs | mkdocs | 4 | no |
119
- | docusaurus | docusaurus | 4 | no |
120
-
121
- ### Meta Skills (always available, never unloaded)
122
-
123
- | Skill | Stack IDs | Priority | Required | Notes |
124
- |-------|-----------|----------|----------|-------|
125
- | skill-router | * | 99 | yes | This skill -- always loaded |
126
- | file-reading | * | 50 | yes | Core capability |
127
- | skill-creator | * | 10 | no | Standby pool |
128
- | product-self-knowledge | * | 10 | no | Standby pool |
129
-
130
- ---
131
-
132
- ## Companion Rules
133
-
134
- When skill A is loaded, also load skill B if its stack is detected:
135
-
136
- | Primary Skill | Companion | Condition |
137
- |---------------|-----------|-----------|
138
- | fastapi | sqlalchemy | DB migrations detected |
139
- | fastapi | openapi | OpenAPI spec file exists |
140
- | django | django-orm | (always with django) |
141
- | react | tailwind | tailwind.config.* exists |
142
- | docker | docker-compose | docker-compose.yml exists |
143
- | kubernetes | helm | Chart.yaml exists |
144
- | terraform | aws | provider "aws" in *.tf |
145
- | langchain | openai-sdk | openai in deps |
146
- | pytest | coverage | .coveragerc or coverage config exists |
147
-
148
- ## Conflict Rules
149
-
150
- These skills should not be co-loaded (pick the one with higher confidence/priority):
151
-
152
- | Skill A | Skill B | Resolution |
153
- |---------|---------|------------|
154
- | flask | fastapi | Higher confidence wins |
155
- | flask | django | Higher confidence wins |
156
- | jest | vitest | Higher confidence wins |
157
- | webpack | vite | Higher confidence wins |
158
- | npm | yarn | Check lock file |
159
- | npm | pnpm | Check lock file |
160
- | yarn | pnpm | Check lock file |
161
- | react | vue | Both can coexist in monorepo |
162
- | sqlalchemy | prisma | Both can coexist if different services |
163
-
164
- > Conflict resolution: check if the repo is a monorepo. In monorepos, "conflicting"
165
- > skills may serve different packages and should both load. In single-package repos,
166
- > pick the one with higher confidence.
 
1
+ # Skill-Stack Matrix
2
+
3
+ > Maps stack identifiers to the skills that serve them.
4
+ > Used as resolver evidence; final ranking still goes through the shared
5
+ > recommendation engine and graph/wiki scores.
6
+
7
+ ## Table of Contents
8
+ 1. [Matrix Format](#matrix-format)
9
+ 2. [The Matrix](#the-matrix)
10
+ 3. [Companion Rules](#companion-rules)
11
+ 4. [Conflict Rules](#conflict-rules)
12
+
13
+ ---
14
+
15
+ ## Matrix Format
16
+
17
+ Each entry:
18
+ - **Stack IDs**: which detected stacks trigger this skill
19
+ - **Skill**: skill/entity slug in the graph/wiki catalog
20
+ - **Priority Base**: starting priority before signal boosts
21
+ - **Required**: must-load if stack detected, vs nice-to-have
22
+ - **Companions**: skills that should co-load
23
+ - **Conflicts**: skills that should not co-load
24
+
25
+ ## The Matrix
26
+
27
+ ### Document Creation Skills
28
+
29
+ | Skill | Stack IDs | Priority | Required | Path Pattern |
30
+ |-------|-----------|----------|----------|--------------|
31
+ | docx | (any -- triggered by user request) | 2 | no | graph/wiki or local skill path |
32
+ | pdf | (any -- triggered by user request) | 2 | no | graph/wiki or local skill path |
33
+ | pptx | (any -- triggered by user request) | 2 | no | graph/wiki or local skill path |
34
+ | xlsx | (any -- triggered by user request) | 2 | no | graph/wiki or local skill path |
35
+
36
+ > Note: document skills are demand-loaded, not stack-loaded. They activate on user
37
+ > request ("make a presentation") not on repo content. The router keeps them in a
38
+ > "standby" pool -- not loaded into context, but available for instant load.
39
+
40
+ ### Frontend Skills
41
+
42
+ | Skill | Stack IDs | Priority | Required |
43
+ |-------|-----------|----------|----------|
44
+ | frontend-design | react, vue, angular, svelte, nextjs, nuxt, html, css | 8 | yes |
45
+ | react | react, nextjs | 7 | yes |
46
+ | vue | vue, nuxt | 7 | yes |
47
+ | angular | angular | 7 | yes |
48
+ | svelte | svelte | 7 | yes |
49
+ | tailwind | tailwindcss | 5 | no |
50
+ | css-modules | css-modules | 4 | no |
51
+
52
+ ### Backend Skills
53
+
54
+ | Skill | Stack IDs | Priority | Required |
55
+ |-------|-----------|----------|----------|
56
+ | fastapi | fastapi | 8 | yes |
57
+ | django | django | 8 | yes |
58
+ | flask | flask | 7 | yes |
59
+ | express | express | 8 | yes |
60
+ | nestjs | nestjs | 8 | yes |
61
+ | rails | rails | 8 | yes |
62
+ | gin | gin | 7 | yes |
63
+ | actix | actix | 7 | yes |
64
+
65
+ ### Data Skills
66
+
67
+ | Skill | Stack IDs | Priority | Required |
68
+ |-------|-----------|----------|----------|
69
+ | sqlalchemy | sqlalchemy, alembic | 6 | yes |
70
+ | prisma | prisma | 6 | yes |
71
+ | typeorm | typeorm | 6 | yes |
72
+ | drizzle | drizzle | 6 | yes |
73
+ | redis | redis | 4 | no |
74
+ | kafka | kafka | 5 | no |
75
+ | dbt | dbt | 6 | yes |
76
+
77
+ ### Infrastructure Skills
78
+
79
+ | Skill | Stack IDs | Priority | Required |
80
+ |-------|-----------|----------|----------|
81
+ | docker | docker, docker-compose | 6 | yes |
82
+ | kubernetes | kubernetes, helm, kustomize | 6 | yes |
83
+ | terraform | terraform | 7 | yes |
84
+ | github-actions | github-actions | 5 | yes |
85
+ | gitlab-ci | gitlab-ci | 5 | yes |
86
+ | aws | aws-cdk, aws-sam | 7 | yes |
87
+ | vercel | vercel | 4 | no |
88
+
89
+ ### AI/Agent Skills
90
+
91
+ | Skill | Stack IDs | Priority | Required |
92
+ |-------|-----------|----------|----------|
93
+ | langchain | langchain | 7 | yes |
94
+ | llamaindex | llamaindex | 7 | yes |
95
+ | mcp-dev | mcp | 7 | yes |
96
+ | pytorch | pytorch | 6 | yes |
97
+ | huggingface | huggingface | 6 | yes |
98
+ | openai-sdk | openai-sdk | 5 | no |
99
+ | anthropic-sdk | anthropic-sdk | 5 | no |
100
+
101
+ ### Quality Skills
102
+
103
+ | Skill | Stack IDs | Priority | Required |
104
+ |-------|-----------|----------|----------|
105
+ | pytest | pytest | 5 | yes |
106
+ | jest | jest, vitest | 5 | yes |
107
+ | cypress | cypress | 4 | no |
108
+ | playwright | playwright | 4 | no |
109
+ | eslint | eslint | 3 | no |
110
+ | ruff | ruff | 3 | no |
111
+
112
+ ### Documentation Skills
113
+
114
+ | Skill | Stack IDs | Priority | Required |
115
+ |-------|-----------|----------|----------|
116
+ | openapi | openapi | 5 | yes |
117
+ | graphql | graphql | 5 | yes |
118
+ | mkdocs | mkdocs | 4 | no |
119
+ | docusaurus | docusaurus | 4 | no |
120
+
121
+ ### Meta Skills (always available, never unloaded)
122
+
123
+ | Skill | Stack IDs | Priority | Required | Notes |
124
+ |-------|-----------|----------|----------|-------|
125
+ | skill-router | * | 99 | yes | This skill -- always loaded |
126
+ | file-reading | * | 50 | yes | Core capability |
127
+ | skill-creator | * | 10 | no | Standby pool |
128
+ | product-self-knowledge | * | 10 | no | Standby pool |
129
+
130
+ ---
131
+
132
+ ## Companion Rules
133
+
134
+ When skill A is loaded, also load skill B if its stack is detected:
135
+
136
+ | Primary Skill | Companion | Condition |
137
+ |---------------|-----------|-----------|
138
+ | fastapi | sqlalchemy | DB migrations detected |
139
+ | fastapi | openapi | OpenAPI spec file exists |
140
+ | django | django-orm | (always with django) |
141
+ | react | tailwind | tailwind.config.* exists |
142
+ | docker | docker-compose | docker-compose.yml exists |
143
+ | kubernetes | helm | Chart.yaml exists |
144
+ | terraform | aws | provider "aws" in *.tf |
145
+ | langchain | openai-sdk | openai in deps |
146
+ | pytest | coverage | .coveragerc or coverage config exists |
147
+
148
+ ## Conflict Rules
149
+
150
+ These skills should not be co-loaded (pick the one with higher confidence/priority):
151
+
152
+ | Skill A | Skill B | Resolution |
153
+ |---------|---------|------------|
154
+ | flask | fastapi | Higher confidence wins |
155
+ | flask | django | Higher confidence wins |
156
+ | jest | vitest | Higher confidence wins |
157
+ | webpack | vite | Higher confidence wins |
158
+ | npm | yarn | Check lock file |
159
+ | npm | pnpm | Check lock file |
160
+ | yarn | pnpm | Check lock file |
161
+ | react | vue | Both can coexist in monorepo |
162
+ | sqlalchemy | prisma | Both can coexist if different services |
163
+
164
+ > Conflict resolution: check if the repo is a monorepo. In monorepos, "conflicting"
165
+ > skills may serve different packages and should both load. In single-package repos,
166
+ > pick the one with higher confidence.
docs/skills-health.md CHANGED
@@ -1,108 +1,108 @@
1
- # Skill health dashboard
2
-
3
- [`src/skill_health.py`](https://github.com/stevesolun/ctx/blob/main/src/skill_health.py)
4
- scans `~/.claude/skills/` and `~/.claude/agents/` for structural and
5
- catalog issues, then produces a JSON or human-readable dashboard. It
6
- also self-heals catalog drift — without ever modifying a SKILL.md.
7
-
8
- ## What it checks
9
-
10
- For each skill (`~/.claude/skills/<name>/SKILL.md`) and each agent
11
- (`~/.claude/agents/<name>.md`):
12
-
13
- | Code | Severity | Condition |
14
- |---|---|---|
15
- | `missing-file` | error | Skill directory has no SKILL.md |
16
- | `unreadable` | error | File exists but can't be decoded as UTF-8 |
17
- | `no-frontmatter` | error | Missing or malformed `---` YAML fence |
18
- | `frontmatter-missing-name` | error | Frontmatter has no `name:` field |
19
- | `frontmatter-missing-description` | warning | Missing `description:` (router relevance suffers) |
20
- | `empty-body` | error | Fewer than `min_body_lines` non-blank lines |
21
  | `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` |
22
-
23
- ## Drift detection
24
-
25
- `DriftReport` cross-references three sources:
26
-
27
- - on-disk entities (skills + agents),
28
- - `~/.claude/skill-manifest.json` → `load[].skill` entries,
29
- - `~/.claude/pending-skills.json` → `graph_suggestions[].name` and
30
- `unmatched_signals[]`.
31
-
32
- Anything in the manifest or pending file that doesn't exist on disk
33
- becomes an *orphan*. Orphans are the only thing `heal` is allowed to
34
- touch.
35
-
36
- ## Self-healing
37
-
38
- ```bash
39
- ctx-skill-health heal
40
- ```
41
-
42
- - drops orphaned entries from `skill-manifest.json`
43
- - drops orphaned entries from `pending-skills.json`
44
- - writes atomically (`tempfile.mkstemp` + `os.replace`)
45
- - never modifies SKILL.md files or agent .md files
46
-
47
- If nothing needs healing, prints `[heal] nothing to do.` and exits 0.
48
-
49
- ## CLI
50
-
51
- ```bash
52
- # Emit a full JSON report
53
- ctx-skill-health scan
54
-
55
- # Pretty dashboard
56
- ctx-skill-health dashboard
57
-
58
- # CI gate: exit 2 if any error-severity issue or drift is present
59
- ctx-skill-health check --strict
60
-
61
- # Apply safe autofixes to manifest + pending
62
- ctx-skill-health heal
63
- ```
64
-
65
- ## Data model
66
-
67
- ```python
68
- @dataclass(frozen=True)
69
- class Issue:
70
- code: str
71
- severity: str # "warning" | "error"
72
- message: str
73
-
74
- @dataclass(frozen=True)
75
- class EntityHealth:
76
- name: str
77
- kind: str # "skill" | "agent"
78
- path: str
79
- lines: int
80
- has_frontmatter: bool
81
- issues: tuple[Issue, ...] = ()
82
-
83
- @dataclass(frozen=True)
84
- class DriftReport:
85
- orphaned_manifest: tuple[str, ...] = ()
86
- orphaned_pending: tuple[str, ...] = ()
87
-
88
- @dataclass(frozen=True)
89
- class HealthReport:
90
- generated_at: float
91
- entities: tuple[EntityHealth, ...]
92
- drift: DriftReport
93
- totals: dict[str, int]
94
- ```
95
-
96
- `HealthReport.has_errors` is true when any entity has severity `error`
97
- *or* drift is non-empty — that's the single predicate behind
98
- `check --strict`'s exit code.
99
-
100
- ## Related
101
-
102
- - [Memory anchoring](memory-anchor.md) — dead-reference detection for
103
- auto-memory notes.
104
- - `src/skill_quality.py` (v0.5.0+) — the four-signal quality scorer
105
- (telemetry 0.40, intake 0.20, graph 0.25, routing 0.15) that writes
106
- per-entity sidecars and surfaces A/B/C/D/F grades. The `skill_health`
107
- CLI above focuses on *structural* correctness; `skill_quality`
108
- focuses on *behavioral* quality over time.
 
1
+ # Skill health dashboard
2
+
3
+ [`src/skill_health.py`](https://github.com/stevesolun/ctx/blob/main/src/skill_health.py)
4
+ scans `~/.claude/skills/` and `~/.claude/agents/` for structural and
5
+ catalog issues, then produces a JSON or human-readable dashboard. It
6
+ also self-heals catalog drift — without ever modifying a SKILL.md.
7
+
8
+ ## What it checks
9
+
10
+ For each skill (`~/.claude/skills/<name>/SKILL.md`) and each agent
11
+ (`~/.claude/agents/<name>.md`):
12
+
13
+ | Code | Severity | Condition |
14
+ |---|---|---|
15
+ | `missing-file` | error | Skill directory has no SKILL.md |
16
+ | `unreadable` | error | File exists but can't be decoded as UTF-8 |
17
+ | `no-frontmatter` | error | Missing or malformed `---` YAML fence |
18
+ | `frontmatter-missing-name` | error | Frontmatter has no `name:` field |
19
+ | `frontmatter-missing-description` | warning | Missing `description:` (router relevance suffers) |
20
+ | `empty-body` | error | Fewer than `min_body_lines` non-blank lines |
21
  | `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` |
22
+
23
+ ## Drift detection
24
+
25
+ `DriftReport` cross-references three sources:
26
+
27
+ - on-disk entities (skills + agents),
28
+ - `~/.claude/skill-manifest.json` → `load[].skill` entries,
29
+ - `~/.claude/pending-skills.json` → `graph_suggestions[].name` and
30
+ `unmatched_signals[]`.
31
+
32
+ Anything in the manifest or pending file that doesn't exist on disk
33
+ becomes an *orphan*. Orphans are the only thing `heal` is allowed to
34
+ touch.
35
+
36
+ ## Self-healing
37
+
38
+ ```bash
39
+ ctx-skill-health heal
40
+ ```
41
+
42
+ - drops orphaned entries from `skill-manifest.json`
43
+ - drops orphaned entries from `pending-skills.json`
44
+ - writes atomically (`tempfile.mkstemp` + `os.replace`)
45
+ - never modifies SKILL.md files or agent .md files
46
+
47
+ If nothing needs healing, prints `[heal] nothing to do.` and exits 0.
48
+
49
+ ## CLI
50
+
51
+ ```bash
52
+ # Emit a full JSON report
53
+ ctx-skill-health scan
54
+
55
+ # Pretty dashboard
56
+ ctx-skill-health dashboard
57
+
58
+ # CI gate: exit 2 if any error-severity issue or drift is present
59
+ ctx-skill-health check --strict
60
+
61
+ # Apply safe autofixes to manifest + pending
62
+ ctx-skill-health heal
63
+ ```
64
+
65
+ ## Data model
66
+
67
+ ```python
68
+ @dataclass(frozen=True)
69
+ class Issue:
70
+ code: str
71
+ severity: str # "warning" | "error"
72
+ message: str
73
+
74
+ @dataclass(frozen=True)
75
+ class EntityHealth:
76
+ name: str
77
+ kind: str # "skill" | "agent"
78
+ path: str
79
+ lines: int
80
+ has_frontmatter: bool
81
+ issues: tuple[Issue, ...] = ()
82
+
83
+ @dataclass(frozen=True)
84
+ class DriftReport:
85
+ orphaned_manifest: tuple[str, ...] = ()
86
+ orphaned_pending: tuple[str, ...] = ()
87
+
88
+ @dataclass(frozen=True)
89
+ class HealthReport:
90
+ generated_at: float
91
+ entities: tuple[EntityHealth, ...]
92
+ drift: DriftReport
93
+ totals: dict[str, int]
94
+ ```
95
+
96
+ `HealthReport.has_errors` is true when any entity has severity `error`
97
+ *or* drift is non-empty — that's the single predicate behind
98
+ `check --strict`'s exit code.
99
+
100
+ ## Related
101
+
102
+ - [Memory anchoring](memory-anchor.md) — dead-reference detection for
103
+ auto-memory notes.
104
+ - `src/skill_quality.py` (v0.5.0+) — the four-signal quality scorer
105
+ (telemetry 0.40, intake 0.20, graph 0.25, routing 0.15) that writes
106
+ per-entity sidecars and surfaces A/B/C/D/F grades. The `skill_health`
107
+ CLI above focuses on *structural* correctness; `skill_quality`
108
+ focuses on *behavioral* quality over time.
docs/toolbox/behavior-miner.md CHANGED
@@ -1,90 +1,90 @@
1
- # Behavior miner
2
-
3
- [`src/behavior_miner.py`](https://github.com/stevesolun/ctx/blob/main/src/behavior_miner.py)
4
- watches your invocation patterns and proposes toolbox tweaks grounded in
5
- real evidence.
6
-
7
- ## What it collects
8
-
9
- Four signal families, each with `MIN_EVIDENCE = 3` before a suggestion
10
- can surface:
11
-
12
- | Signal | Source | Example suggestion |
13
- |---|---|---|
14
- | **Co-invocation** | Pairs of agents invoked in the same session | "You ran `code-reviewer` + `security-reviewer` together 4 times — consider a bundle." |
15
- | **Skill cadence** | Skill load frequency over time | "`python-patterns` loaded every session — promote to `pre`." |
16
- | **File-type** | File extensions of work-in-progress | "60% of your diffs touch `.tf` files — consider a Terraform toolbox." |
17
- | **Commit-type** | Conventional Commit parsing | "8 of your last 10 commits are `fix:` — consider a pre-commit test toolbox." |
18
-
19
- ## User profile
20
-
21
- Signals aggregate into `~/.claude/user-profile.json`:
22
-
23
- ```jsonc
24
- {
25
- "version": 1,
26
- "updated_at": 1713456789,
27
- "signals": {
28
- "co_invocation": {
29
- "code-reviewer|security-reviewer": 4,
30
- "architect-review|test-automator": 3
31
- },
32
- "skill_cadence": {
33
- "python-patterns": {"loads": 12, "sessions": 12}
34
- },
35
- "file_types": {"py": 87, "md": 31, "tf": 0},
36
- "commit_types": {"fix": 8, "feat": 2}
37
- },
38
- "suggestions": [
39
- {
40
- "id": "bundle:reviewers-pair",
41
- "rationale": "4 co-invocations of code-reviewer + security-reviewer",
42
- "evidence_count": 4
43
- }
44
- ]
45
- }
46
- ```
47
-
48
- ## Digest
49
-
50
- On `session-end`, the hook calls `format_digest(profile)` and prints
51
- anything new. Example output:
52
-
53
- ```
54
- [behavior-miner] 2 suggestions:
55
- - bundle:reviewers-pair (4 co-invocations)
56
- → add to 'review' toolbox:
57
- ctx-toolbox add review --post code-reviewer,security-reviewer
58
- - promote:python-patterns (loaded in 12/12 sessions)
59
- → promote to 'pre' in your default toolbox
60
- ```
61
-
62
- Suggestions are never applied automatically. The user runs the command,
63
- or accepts the suggestion via `toolbox init --accept <id>`.
64
-
65
- ## CLI
66
-
67
- ```bash
68
- # Rebuild the profile from scratch (scans ~/.claude/history/)
69
- python -m behavior_miner build
70
-
71
- # Show current suggestions
72
- python -m behavior_miner show
73
-
74
- # Print digest (same output as session-end hook)
75
- python -m behavior_miner digest
76
-
77
- # Drop a suggestion (noise reduction)
78
- python -m behavior_miner dismiss bundle:reviewers-pair
79
- ```
80
-
81
- ## Privacy
82
-
83
- All signal data stays in `~/.claude/`. Nothing is sent over the network.
84
- The miner never reads file contents — only names, extensions, and commit
85
- message prefixes.
86
-
87
- ## Related
88
-
89
- - [Intent interview](intent-interview.md) — surfaces miner suggestions
90
- during the `toolbox init` flow.
 
1
+ # Behavior miner
2
+
3
+ [`src/behavior_miner.py`](https://github.com/stevesolun/ctx/blob/main/src/behavior_miner.py)
4
+ watches your invocation patterns and proposes toolbox tweaks grounded in
5
+ real evidence.
6
+
7
+ ## What it collects
8
+
9
+ Four signal families, each with `MIN_EVIDENCE = 3` before a suggestion
10
+ can surface:
11
+
12
+ | Signal | Source | Example suggestion |
13
+ |---|---|---|
14
+ | **Co-invocation** | Pairs of agents invoked in the same session | "You ran `code-reviewer` + `security-reviewer` together 4 times — consider a bundle." |
15
+ | **Skill cadence** | Skill load frequency over time | "`python-patterns` loaded every session — promote to `pre`." |
16
+ | **File-type** | File extensions of work-in-progress | "60% of your diffs touch `.tf` files — consider a Terraform toolbox." |
17
+ | **Commit-type** | Conventional Commit parsing | "8 of your last 10 commits are `fix:` — consider a pre-commit test toolbox." |
18
+
19
+ ## User profile
20
+
21
+ Signals aggregate into `~/.claude/user-profile.json`:
22
+
23
+ ```jsonc
24
+ {
25
+ "version": 1,
26
+ "updated_at": 1713456789,
27
+ "signals": {
28
+ "co_invocation": {
29
+ "code-reviewer|security-reviewer": 4,
30
+ "architect-review|test-automator": 3
31
+ },
32
+ "skill_cadence": {
33
+ "python-patterns": {"loads": 12, "sessions": 12}
34
+ },
35
+ "file_types": {"py": 87, "md": 31, "tf": 0},
36
+ "commit_types": {"fix": 8, "feat": 2}
37
+ },
38
+ "suggestions": [
39
+ {
40
+ "id": "bundle:reviewers-pair",
41
+ "rationale": "4 co-invocations of code-reviewer + security-reviewer",
42
+ "evidence_count": 4
43
+ }
44
+ ]
45
+ }
46
+ ```
47
+
48
+ ## Digest
49
+
50
+ On `session-end`, the hook calls `format_digest(profile)` and prints
51
+ anything new. Example output:
52
+
53
+ ```
54
+ [behavior-miner] 2 suggestions:
55
+ - bundle:reviewers-pair (4 co-invocations)
56
+ → add to 'review' toolbox:
57
+ ctx-toolbox add review --post code-reviewer,security-reviewer
58
+ - promote:python-patterns (loaded in 12/12 sessions)
59
+ → promote to 'pre' in your default toolbox
60
+ ```
61
+
62
+ Suggestions are never applied automatically. The user runs the command,
63
+ or accepts the suggestion via `toolbox init --accept <id>`.
64
+
65
+ ## CLI
66
+
67
+ ```bash
68
+ # Rebuild the profile from scratch (scans ~/.claude/history/)
69
+ python -m behavior_miner build
70
+
71
+ # Show current suggestions
72
+ python -m behavior_miner show
73
+
74
+ # Print digest (same output as session-end hook)
75
+ python -m behavior_miner digest
76
+
77
+ # Drop a suggestion (noise reduction)
78
+ python -m behavior_miner dismiss bundle:reviewers-pair
79
+ ```
80
+
81
+ ## Privacy
82
+
83
+ All signal data stays in `~/.claude/`. Nothing is sent over the network.
84
+ The miner never reads file contents — only names, extensions, and commit
85
+ message prefixes.
86
+
87
+ ## Related
88
+
89
+ - [Intent interview](intent-interview.md) — surfaces miner suggestions
90
+ during the `toolbox init` flow.
docs/toolbox/configuration.md CHANGED
@@ -1,143 +1,143 @@
1
- # Configuration
2
-
3
- Toolbox config lives in two files:
4
-
5
- | Layer | Path | Format | Scope |
6
- |---|---|---|---|
7
- | **Global** | `~/.claude/toolboxes.json` | JSON | Every repo on this machine |
8
- | **Per-repo** | `.toolbox.yaml` (project root) | YAML | This repo only, overrides global |
9
-
10
- Per-repo entries shadow global entries with the same name. Fields absent
11
- from the per-repo file fall back to the global value.
12
-
13
- ## Schema
14
-
15
- ```jsonc
16
- {
17
- "version": 1,
18
- "toolboxes": {
19
- "<name>": {
20
- "description": "human-readable purpose",
21
-
22
- // Skills to load before the trigger fires
23
- "pre": ["python-patterns", "docs-lookup"],
24
-
25
- // Agents to run after
26
- "post": [
27
- "code-reviewer",
28
- "security-reviewer",
29
- "architect-review"
30
- ],
31
-
32
- "scope": {
33
- // "diff" | "dynamic" | "full"
34
- "analysis": "dynamic",
35
- // Optional: restrict to these glob projects
36
- "projects": ["*"],
37
- // Optional: restrict to these file globs
38
- "files": ["src/**/*.py"]
39
- },
40
-
41
- "budget": {
42
- "max_tokens": 60000,
43
- "max_seconds": 180
44
- },
45
-
46
- "dedup": {
47
- // "fresh" = always re-run, "user-configurable" = skip
48
- // if same files already reviewed this session
49
- "policy": "user-configurable",
50
- "window_seconds": 3600
51
- },
52
-
53
- "trigger": {
54
- "slash": true,
55
- "session_start": false,
56
- "file_save": false,
57
- "pre_commit": true,
58
- "session_end": false
59
- },
60
-
61
- // If true, HIGH/CRITICAL verdicts block pre-commit
62
- "guardrail": true
63
- }
64
- }
65
- }
66
- ```
67
-
68
- ## Field reference
69
-
70
- ### `pre` and `post`
71
-
72
- - `pre` — skills to load before work starts. Loaded into the session's
73
- skill manifest, unloaded when the session ends.
74
- - `post` — agents to invoke after the trigger. Each runs in its own
75
- sub-agent context window.
76
-
77
- Either list can be empty. A toolbox with only `pre` is a skill preloader;
78
- one with only `post` is a review council.
79
-
80
- ### `scope.analysis`
81
-
82
- Controls what files the council sees:
83
-
84
- | Value | Behavior |
85
- |---|---|
86
- | `diff` | Only files with uncommitted changes. Cheapest, fastest. |
87
- | `dynamic` | Diff + import graph blast radius. Catches downstream regressions. |
88
- | `full` | Every tracked file. Most thorough; expensive — reserve for security sweeps. |
89
-
90
- ### `budget`
91
-
92
- Enforced by `council_runner`. When the plan would exceed `max_tokens`, the
93
- runner truncates the file list; when time exceeds `max_seconds`, the
94
- trigger exits 0 without running remaining agents.
95
-
96
- ### `dedup`
97
-
98
- `fresh` always re-runs. `user-configurable` skips a council run when the
99
- same file set was reviewed within `window_seconds`. Dedup state lives at
100
- `~/.claude/toolbox-runs/<plan_hash>.json`.
101
-
102
- ### `trigger`
103
-
104
- At least one trigger must be true. Multiple triggers are allowed — a
105
- `ship-it` toolbox typically enables `slash`, `pre_commit`, and
106
- `session_end`.
107
-
108
- ### `guardrail`
109
-
110
- When `true` and the trigger is `pre_commit`, the hook reads
111
- `<plan_hash>.verdict.json` after the council runs and exits `2` (blocks
112
- the commit) if level is `HIGH` or `CRITICAL`. See
113
- [Verdicts & guardrails](verdicts.md).
114
-
115
- ## Editing tools
116
-
117
- ```bash
118
- # List all toolboxes, both layers merged
119
- ctx-toolbox list
120
-
121
- # Show resolved config for one toolbox
122
- ctx-toolbox show ship-it
123
-
124
- # Activate a starter preset
125
- ctx-toolbox activate ship-it
126
-
127
- # Export merged config
128
- ctx-toolbox export > my-toolboxes.yaml
129
-
130
- # Import from file
131
- ctx-toolbox import my-toolboxes.yaml
132
- ```
133
-
134
- ## Validation
135
-
136
- `toolbox_config.load()` validates on read:
137
-
138
- - `version` must equal `1`.
139
- - Every toolbox needs at least one trigger.
140
- - `scope.analysis` must be one of `diff`, `dynamic`, `full`.
141
- - `budget.max_tokens` and `budget.max_seconds` must be positive ints.
142
-
143
- Invalid entries raise `ValueError` with the offending key.
 
1
+ # Configuration
2
+
3
+ Toolbox config lives in two files:
4
+
5
+ | Layer | Path | Format | Scope |
6
+ |---|---|---|---|
7
+ | **Global** | `~/.claude/toolboxes.json` | JSON | Every repo on this machine |
8
+ | **Per-repo** | `.toolbox.yaml` (project root) | YAML | This repo only, overrides global |
9
+
10
+ Per-repo entries shadow global entries with the same name. Fields absent
11
+ from the per-repo file fall back to the global value.
12
+
13
+ ## Schema
14
+
15
+ ```jsonc
16
+ {
17
+ "version": 1,
18
+ "toolboxes": {
19
+ "<name>": {
20
+ "description": "human-readable purpose",
21
+
22
+ // Skills to load before the trigger fires
23
+ "pre": ["python-patterns", "docs-lookup"],
24
+
25
+ // Agents to run after
26
+ "post": [
27
+ "code-reviewer",
28
+ "security-reviewer",
29
+ "architect-review"
30
+ ],
31
+
32
+ "scope": {
33
+ // "diff" | "dynamic" | "full"
34
+ "analysis": "dynamic",
35
+ // Optional: restrict to these glob projects
36
+ "projects": ["*"],
37
+ // Optional: restrict to these file globs
38
+ "files": ["src/**/*.py"]
39
+ },
40
+
41
+ "budget": {
42
+ "max_tokens": 60000,
43
+ "max_seconds": 180
44
+ },
45
+
46
+ "dedup": {
47
+ // "fresh" = always re-run, "user-configurable" = skip
48
+ // if same files already reviewed this session
49
+ "policy": "user-configurable",
50
+ "window_seconds": 3600
51
+ },
52
+
53
+ "trigger": {
54
+ "slash": true,
55
+ "session_start": false,
56
+ "file_save": false,
57
+ "pre_commit": true,
58
+ "session_end": false
59
+ },
60
+
61
+ // If true, HIGH/CRITICAL verdicts block pre-commit
62
+ "guardrail": true
63
+ }
64
+ }
65
+ }
66
+ ```
67
+
68
+ ## Field reference
69
+
70
+ ### `pre` and `post`
71
+
72
+ - `pre` — skills to load before work starts. Loaded into the session's
73
+ skill manifest, unloaded when the session ends.
74
+ - `post` — agents to invoke after the trigger. Each runs in its own
75
+ sub-agent context window.
76
+
77
+ Either list can be empty. A toolbox with only `pre` is a skill preloader;
78
+ one with only `post` is a review council.
79
+
80
+ ### `scope.analysis`
81
+
82
+ Controls what files the council sees:
83
+
84
+ | Value | Behavior |
85
+ |---|---|
86
+ | `diff` | Only files with uncommitted changes. Cheapest, fastest. |
87
+ | `dynamic` | Diff + import graph blast radius. Catches downstream regressions. |
88
+ | `full` | Every tracked file. Most thorough; expensive — reserve for security sweeps. |
89
+
90
+ ### `budget`
91
+
92
+ Enforced by `council_runner`. When the plan would exceed `max_tokens`, the
93
+ runner truncates the file list; when time exceeds `max_seconds`, the
94
+ trigger exits 0 without running remaining agents.
95
+
96
+ ### `dedup`
97
+
98
+ `fresh` always re-runs. `user-configurable` skips a council run when the
99
+ same file set was reviewed within `window_seconds`. Dedup state lives at
100
+ `~/.claude/toolbox-runs/<plan_hash>.json`.
101
+
102
+ ### `trigger`
103
+
104
+ At least one trigger must be true. Multiple triggers are allowed — a
105
+ `ship-it` toolbox typically enables `slash`, `pre_commit`, and
106
+ `session_end`.
107
+
108
+ ### `guardrail`
109
+
110
+ When `true` and the trigger is `pre_commit`, the hook reads
111
+ `<plan_hash>.verdict.json` after the council runs and exits `2` (blocks
112
+ the commit) if level is `HIGH` or `CRITICAL`. See
113
+ [Verdicts & guardrails](verdicts.md).
114
+
115
+ ## Editing tools
116
+
117
+ ```bash
118
+ # List all toolboxes, both layers merged
119
+ ctx-toolbox list
120
+
121
+ # Show resolved config for one toolbox
122
+ ctx-toolbox show ship-it
123
+
124
+ # Activate a starter preset
125
+ ctx-toolbox activate ship-it
126
+
127
+ # Export merged config
128
+ ctx-toolbox export > my-toolboxes.yaml
129
+
130
+ # Import from file
131
+ ctx-toolbox import my-toolboxes.yaml
132
+ ```
133
+
134
+ ## Validation
135
+
136
+ `toolbox_config.load()` validates on read:
137
+
138
+ - `version` must equal `1`.
139
+ - Every toolbox needs at least one trigger.
140
+ - `scope.analysis` must be one of `diff`, `dynamic`, `full`.
141
+ - `budget.max_tokens` and `budget.max_seconds` must be positive ints.
142
+
143
+ Invalid entries raise `ValueError` with the offending key.
docs/toolbox/council-runner.md CHANGED
@@ -1,81 +1,81 @@
1
- # Council runner
2
-
3
- [`src/council_runner.py`](https://github.com/stevesolun/ctx/blob/main/src/council_runner.py)
4
- is the planner that turns a toolbox declaration into a concrete `RunPlan`
5
- the hook system can execute.
6
-
7
- ## Responsibilities
8
-
9
- 1. **Resolve the toolbox** — merge global + per-repo config.
10
- 2. **Compute scope** — walk the current diff or full repo, honoring
11
- `scope.analysis` and optional `scope.files` globs.
12
- 3. **Graph-blast expansion** — for `dynamic` scope, add every file that
13
- imports a changed module (via the knowledge graph edge map).
14
- 4. **Enforce budget** — drop files until the plan fits within
15
- `budget.max_tokens` (estimated by line count × heuristic).
16
- 5. **Honor dedup** — skip if the same file set was run within
17
- `dedup.window_seconds` and policy is `user-configurable`.
18
- 6. **Persist** — write the plan to
19
- `~/.claude/toolbox-runs/<plan_hash>.json` for downstream reads.
20
-
21
- ## RunPlan
22
-
23
- ```python
24
- @dataclass(frozen=True)
25
- class RunPlan:
26
- plan_hash: str
27
- toolbox: str
28
- agents: tuple[str, ...]
29
- files: tuple[str, ...]
30
- source: str # "slash" | "pre-commit" | ...
31
- guardrail: bool
32
- budget: Budget
33
- created_at: float
34
- ```
35
-
36
- The `plan_hash` is deterministic (sha256 of `toolbox|sorted(files)|agents`),
37
- which lets dedup work across triggers without any additional state.
38
-
39
- ## CLI
40
-
41
- ```bash
42
- # Build and persist a plan for the named toolbox
43
- python -m council_runner build ship-it
44
-
45
- # Build without persisting (useful for inspection)
46
- python -m council_runner build ship-it --dry-run
47
-
48
- # Show a previously persisted plan
49
- python -m council_runner show <plan_hash>
50
-
51
- # List recent plans
52
- python -m council_runner list --limit 10
53
- ```
54
-
55
- ## Budget estimation
56
-
57
- Token estimates are intentionally rough. The runner assumes ~4 tokens per
58
- line of source, then sorts files by recency (newest first) and greedily
59
- takes until `max_tokens` is reached. If a single file exceeds the budget,
60
- the plan is truncated rather than dropped — the council still runs on a
61
- partial view.
62
-
63
- This cheap estimate is fine because the council itself enforces its own
64
- budgets; `council_runner`'s job is just to stay in the right ballpark.
65
-
66
- ## Dedup window
67
-
68
- Dedup compares the sorted file list, not the plan hash — that way a
69
- toolbox and its re-run with a newer budget still dedup correctly.
70
-
71
- ## Graph-blast expansion
72
-
73
- For `dynamic` scope, `council_runner` reads the graph edge map produced
74
- by `scan_repo.py` and walks imports one hop out from each changed file.
75
- It stops at one hop to keep scope bounded; deep graph walks are reserved
76
- for explicit `full` mode.
77
-
78
- ## Related
79
-
80
- - [Hooks & triggers](hooks.md) — how a plan gets executed.
81
- - [Verdicts & guardrails](verdicts.md) — what the council leaves behind.
 
1
+ # Council runner
2
+
3
+ [`src/council_runner.py`](https://github.com/stevesolun/ctx/blob/main/src/council_runner.py)
4
+ is the planner that turns a toolbox declaration into a concrete `RunPlan`
5
+ the hook system can execute.
6
+
7
+ ## Responsibilities
8
+
9
+ 1. **Resolve the toolbox** — merge global + per-repo config.
10
+ 2. **Compute scope** — walk the current diff or full repo, honoring
11
+ `scope.analysis` and optional `scope.files` globs.
12
+ 3. **Graph-blast expansion** — for `dynamic` scope, add every file that
13
+ imports a changed module (via the knowledge graph edge map).
14
+ 4. **Enforce budget** — drop files until the plan fits within
15
+ `budget.max_tokens` (estimated by line count × heuristic).
16
+ 5. **Honor dedup** — skip if the same file set was run within
17
+ `dedup.window_seconds` and policy is `user-configurable`.
18
+ 6. **Persist** — write the plan to
19
+ `~/.claude/toolbox-runs/<plan_hash>.json` for downstream reads.
20
+
21
+ ## RunPlan
22
+
23
+ ```python
24
+ @dataclass(frozen=True)
25
+ class RunPlan:
26
+ plan_hash: str
27
+ toolbox: str
28
+ agents: tuple[str, ...]
29
+ files: tuple[str, ...]
30
+ source: str # "slash" | "pre-commit" | ...
31
+ guardrail: bool
32
+ budget: Budget
33
+ created_at: float
34
+ ```
35
+
36
+ The `plan_hash` is deterministic (sha256 of `toolbox|sorted(files)|agents`),
37
+ which lets dedup work across triggers without any additional state.
38
+
39
+ ## CLI
40
+
41
+ ```bash
42
+ # Build and persist a plan for the named toolbox
43
+ python -m council_runner build ship-it
44
+
45
+ # Build without persisting (useful for inspection)
46
+ python -m council_runner build ship-it --dry-run
47
+
48
+ # Show a previously persisted plan
49
+ python -m council_runner show <plan_hash>
50
+
51
+ # List recent plans
52
+ python -m council_runner list --limit 10
53
+ ```
54
+
55
+ ## Budget estimation
56
+
57
+ Token estimates are intentionally rough. The runner assumes ~4 tokens per
58
+ line of source, then sorts files by recency (newest first) and greedily
59
+ takes until `max_tokens` is reached. If a single file exceeds the budget,
60
+ the plan is truncated rather than dropped — the council still runs on a
61
+ partial view.
62
+
63
+ This cheap estimate is fine because the council itself enforces its own
64
+ budgets; `council_runner`'s job is just to stay in the right ballpark.
65
+
66
+ ## Dedup window
67
+
68
+ Dedup compares the sorted file list, not the plan hash — that way a
69
+ toolbox and its re-run with a newer budget still dedup correctly.
70
+
71
+ ## Graph-blast expansion
72
+
73
+ For `dynamic` scope, `council_runner` reads the graph edge map produced
74
+ by `scan_repo.py` and walks imports one hop out from each changed file.
75
+ It stops at one hop to keep scope bounded; deep graph walks are reserved
76
+ for explicit `full` mode.
77
+
78
+ ## Related
79
+
80
+ - [Hooks & triggers](hooks.md) — how a plan gets executed.
81
+ - [Verdicts & guardrails](verdicts.md) — what the council leaves behind.
docs/toolbox/index.md CHANGED
@@ -1,75 +1,75 @@
1
- # Toolbox overview
2
-
3
- A **toolbox** is a named bundle of skills and agents that runs at a defined
4
- moment in your workflow: at session start, on file save, before a commit, at
5
- session end, or when you invoke its slash command.
6
-
7
- Toolboxes let you declare the *council* you want reviewing your work
8
- without hand-loading skills each session.
9
-
10
- ## Lifecycle
11
-
12
- ```mermaid
13
- flowchart LR
14
- A[Declare toolbox] --> B[Trigger fires]
15
- B --> C[Council runner<br/>builds plan]
16
- C --> D[Agents run<br/>scoped to plan.files]
17
- D --> E[Findings recorded<br/>as Verdict]
18
- E -->|HIGH / CRITICAL| F[Guardrail blocks<br/>pre-commit]
19
- E -->|LOW / MEDIUM| G[Logged,<br/>session continues]
20
- ```
21
-
22
- Each arrow is a concrete module:
23
-
24
- - **Declare**: [`toolbox_config.py`](https://github.com/stevesolun/ctx/blob/main/src/toolbox_config.py)
25
- loads `~/.claude/toolboxes.json` and merges per-repo `.toolbox.yaml` on top.
26
- - **Trigger**: [`toolbox_hooks.py`](https://github.com/stevesolun/ctx/blob/main/src/toolbox_hooks.py)
27
- listens for `session-start`, `file-save`, `pre-commit`, `session-end`, and
28
- the `/toolbox run` slash command.
29
- - **Plan**: [`council_runner.py`](https://github.com/stevesolun/ctx/blob/main/src/council_runner.py)
30
- assembles a `RunPlan` honoring scope, dedup, and graph-blast expansion.
31
- - **Verdict**: [`toolbox_verdict.py`](https://github.com/stevesolun/ctx/blob/main/src/toolbox_verdict.py)
32
- merges findings by id and escalates level to max(findings).
33
-
34
- ## Minimal declaration
35
-
36
- ```yaml
37
- # .toolbox.yaml (per-repo)
38
- version: 1
39
- toolboxes:
40
- review:
41
- description: "Post-feature code review"
42
- post:
43
- - code-reviewer
44
- - security-reviewer
45
- scope:
46
- analysis: diff
47
- trigger:
48
- slash: true
49
- pre_commit: true
50
- guardrail: true
51
- ```
52
-
53
  Run it manually:
54
 
55
  ```bash
56
  ctx-toolbox run --event pre-commit
57
  ```
58
-
59
- Or let the `pre-commit` hook fire it automatically — see
60
- [Hooks & triggers](hooks.md).
61
-
62
- ## Scope modes
63
-
64
- | Mode | What gets reviewed | Best for |
65
- |---|---|---|
66
- | `diff` | Files in the current uncommitted diff | Pre-commit, real-time review |
67
- | `dynamic` | Diff + graph blast radius (imports of modified files) | Refactor safety |
68
- | `full` | Entire repo | Security sweeps, docs audits |
69
-
70
- ## Related
71
-
72
- - [Configuration schema](configuration.md) — full field reference.
73
- - [Starter toolboxes](starters.md) — 5 shipping presets.
74
- - [Intent interview](intent-interview.md) — `toolbox init` walkthrough.
75
- - [Verdicts & guardrails](verdicts.md) — how blocking works.
 
1
+ # Toolbox overview
2
+
3
+ A **toolbox** is a named bundle of skills and agents that runs at a defined
4
+ moment in your workflow: at session start, on file save, before a commit, at
5
+ session end, or when you invoke its slash command.
6
+
7
+ Toolboxes let you declare the *council* you want reviewing your work
8
+ without hand-loading skills each session.
9
+
10
+ ## Lifecycle
11
+
12
+ ```mermaid
13
+ flowchart LR
14
+ A[Declare toolbox] --> B[Trigger fires]
15
+ B --> C[Council runner<br/>builds plan]
16
+ C --> D[Agents run<br/>scoped to plan.files]
17
+ D --> E[Findings recorded<br/>as Verdict]
18
+ E -->|HIGH / CRITICAL| F[Guardrail blocks<br/>pre-commit]
19
+ E -->|LOW / MEDIUM| G[Logged,<br/>session continues]
20
+ ```
21
+
22
+ Each arrow is a concrete module:
23
+
24
+ - **Declare**: [`toolbox_config.py`](https://github.com/stevesolun/ctx/blob/main/src/toolbox_config.py)
25
+ loads `~/.claude/toolboxes.json` and merges per-repo `.toolbox.yaml` on top.
26
+ - **Trigger**: [`toolbox_hooks.py`](https://github.com/stevesolun/ctx/blob/main/src/toolbox_hooks.py)
27
+ listens for `session-start`, `file-save`, `pre-commit`, `session-end`, and
28
+ the `/toolbox run` slash command.
29
+ - **Plan**: [`council_runner.py`](https://github.com/stevesolun/ctx/blob/main/src/council_runner.py)
30
+ assembles a `RunPlan` honoring scope, dedup, and graph-blast expansion.
31
+ - **Verdict**: [`toolbox_verdict.py`](https://github.com/stevesolun/ctx/blob/main/src/toolbox_verdict.py)
32
+ merges findings by id and escalates level to max(findings).
33
+
34
+ ## Minimal declaration
35
+
36
+ ```yaml
37
+ # .toolbox.yaml (per-repo)
38
+ version: 1
39
+ toolboxes:
40
+ review:
41
+ description: "Post-feature code review"
42
+ post:
43
+ - code-reviewer
44
+ - security-reviewer
45
+ scope:
46
+ analysis: diff
47
+ trigger:
48
+ slash: true
49
+ pre_commit: true
50
+ guardrail: true
51
+ ```
52
+
53
  Run it manually:
54
 
55
  ```bash
56
  ctx-toolbox run --event pre-commit
57
  ```
58
+
59
+ Or let the `pre-commit` hook fire it automatically — see
60
+ [Hooks & triggers](hooks.md).
61
+
62
+ ## Scope modes
63
+
64
+ | Mode | What gets reviewed | Best for |
65
+ |---|---|---|
66
+ | `diff` | Files in the current uncommitted diff | Pre-commit, real-time review |
67
+ | `dynamic` | Diff + graph blast radius (imports of modified files) | Refactor safety |
68
+ | `full` | Entire repo | Security sweeps, docs audits |
69
+
70
+ ## Related
71
+
72
+ - [Configuration schema](configuration.md) — full field reference.
73
+ - [Starter toolboxes](starters.md) — 5 shipping presets.
74
+ - [Intent interview](intent-interview.md) — `toolbox init` walkthrough.
75
+ - [Verdicts & guardrails](verdicts.md) — how blocking works.
docs/toolbox/intent-interview.md CHANGED
@@ -1,94 +1,94 @@
1
- # Intent interview
2
-
3
- [`src/intent_interview.py`](https://github.com/stevesolun/ctx/blob/main/src/intent_interview.py)
4
- bootstraps your toolbox set via a short, skippable interview.
5
-
6
- The slash command `/toolbox init` is a thin wrapper; see
7
- [`.claude/commands/toolbox-init.md`](https://github.com/stevesolun/ctx/blob/main/.claude/commands/toolbox-init.md).
8
-
9
- ## Flow
10
-
11
- 1. **Detect repo state** — is this a git repo? Any commits? What languages?
12
- 2. **Load behavior profile** — read `~/.claude/user-profile.json` for any
13
- mined suggestions.
14
- 3. **Ask up to three questions**:
15
- - Which starter toolboxes to activate.
16
- - Which miner suggestions to accept (if any).
17
- - Default analysis mode for new toolboxes.
18
- 4. **Persist** — write chosen toolboxes to `~/.claude/toolboxes.json`
19
- (only when `--apply` is passed).
20
-
21
- Any prompt can be skipped with the word `skip`.
22
-
23
- ## Repo state detection
24
-
25
- ```python
26
- @dataclass(frozen=True)
27
- class RepoState:
28
- is_git: bool
29
- commit_count: int
30
- languages: dict[str, int] # extension → file count
31
- markers: dict[str, str] # marker file → language
32
- has_toolbox_config: bool
33
-
34
- @property
35
- def is_blank(self) -> bool:
36
- # True when the repo has effectively nothing to analyze yet.
37
- return not self.is_git or self.commit_count == 0 or (
38
- not self.languages and not self.markers
39
- )
40
- ```
41
-
42
- Language scoring uses both extensions (`.py`, `.ts`, …) and marker files
43
- (`pyproject.toml`, `Cargo.toml`, `Dockerfile`, …). Marker files bump the
44
- score by 5 to reflect that they declare intent more strongly than a
45
- stray extension match.
46
-
47
- ## Usage
48
-
49
- ```bash
50
- # Default: interactive, dry-run (no write)
51
- python -m intent_interview init
52
-
53
- # Detect state only
54
- python -m intent_interview detect
55
-
56
- # Preset flows (no prompts)
57
- python -m intent_interview init --preset blank --apply
58
- python -m intent_interview init --preset existing --apply
59
- python -m intent_interview init --preset docs-heavy --apply
60
- python -m intent_interview init --preset security-first --apply
61
-
62
- # Fully structured (CI / scripted setup)
63
- python -m intent_interview init \
64
- --non-interactive \
65
- --starters ship-it,security-sweep \
66
- --suggestions 1,2 \
67
- --analysis dynamic \
68
- --apply
69
- ```
70
-
71
- ## Presets
72
-
73
- | Preset | Starters | Default scope |
74
- |---|---|---|
75
- | `blank` | ship-it, security-sweep, fresh-repo-init | dynamic |
76
- | `existing` | ship-it, refactor-safety | dynamic |
77
- | `docs-heavy` | docs-review | diff |
78
- | `security-first` | security-sweep | full |
79
-
80
- ## Skip semantics
81
-
82
- - Typing `skip` at any prompt short-circuits the whole interview: no
83
- starters activated, no suggestions accepted, analysis mode unchanged.
84
- - `--skip` on the CLI is the non-interactive equivalent.
85
-
86
- ## Exit codes
87
-
88
- - `0` — success; JSON payload printed on stdout.
89
- - non-zero — unrecoverable error (unknown preset, malformed args).
90
-
91
- ## Related
92
-
93
- - [Starter toolboxes](starters.md) — the five bundles the interview can activate.
94
- - [Behavior miner](behavior-miner.md) — source of the suggestions the interview offers.
 
1
+ # Intent interview
2
+
3
+ [`src/intent_interview.py`](https://github.com/stevesolun/ctx/blob/main/src/intent_interview.py)
4
+ bootstraps your toolbox set via a short, skippable interview.
5
+
6
+ The slash command `/toolbox init` is a thin wrapper; see
7
+ [`.claude/commands/toolbox-init.md`](https://github.com/stevesolun/ctx/blob/main/.claude/commands/toolbox-init.md).
8
+
9
+ ## Flow
10
+
11
+ 1. **Detect repo state** — is this a git repo? Any commits? What languages?
12
+ 2. **Load behavior profile** — read `~/.claude/user-profile.json` for any
13
+ mined suggestions.
14
+ 3. **Ask up to three questions**:
15
+ - Which starter toolboxes to activate.
16
+ - Which miner suggestions to accept (if any).
17
+ - Default analysis mode for new toolboxes.
18
+ 4. **Persist** — write chosen toolboxes to `~/.claude/toolboxes.json`
19
+ (only when `--apply` is passed).
20
+
21
+ Any prompt can be skipped with the word `skip`.
22
+
23
+ ## Repo state detection
24
+
25
+ ```python
26
+ @dataclass(frozen=True)
27
+ class RepoState:
28
+ is_git: bool
29
+ commit_count: int
30
+ languages: dict[str, int] # extension → file count
31
+ markers: dict[str, str] # marker file → language
32
+ has_toolbox_config: bool
33
+
34
+ @property
35
+ def is_blank(self) -> bool:
36
+ # True when the repo has effectively nothing to analyze yet.
37
+ return not self.is_git or self.commit_count == 0 or (
38
+ not self.languages and not self.markers
39
+ )
40
+ ```
41
+
42
+ Language scoring uses both extensions (`.py`, `.ts`, …) and marker files
43
+ (`pyproject.toml`, `Cargo.toml`, `Dockerfile`, …). Marker files bump the
44
+ score by 5 to reflect that they declare intent more strongly than a
45
+ stray extension match.
46
+
47
+ ## Usage
48
+
49
+ ```bash
50
+ # Default: interactive, dry-run (no write)
51
+ python -m intent_interview init
52
+
53
+ # Detect state only
54
+ python -m intent_interview detect
55
+
56
+ # Preset flows (no prompts)
57
+ python -m intent_interview init --preset blank --apply
58
+ python -m intent_interview init --preset existing --apply
59
+ python -m intent_interview init --preset docs-heavy --apply
60
+ python -m intent_interview init --preset security-first --apply
61
+
62
+ # Fully structured (CI / scripted setup)
63
+ python -m intent_interview init \
64
+ --non-interactive \
65
+ --starters ship-it,security-sweep \
66
+ --suggestions 1,2 \
67
+ --analysis dynamic \
68
+ --apply
69
+ ```
70
+
71
+ ## Presets
72
+
73
+ | Preset | Starters | Default scope |
74
+ |---|---|---|
75
+ | `blank` | ship-it, security-sweep, fresh-repo-init | dynamic |
76
+ | `existing` | ship-it, refactor-safety | dynamic |
77
+ | `docs-heavy` | docs-review | diff |
78
+ | `security-first` | security-sweep | full |
79
+
80
+ ## Skip semantics
81
+
82
+ - Typing `skip` at any prompt short-circuits the whole interview: no
83
+ starters activated, no suggestions accepted, analysis mode unchanged.
84
+ - `--skip` on the CLI is the non-interactive equivalent.
85
+
86
+ ## Exit codes
87
+
88
+ - `0` — success; JSON payload printed on stdout.
89
+ - non-zero — unrecoverable error (unknown preset, malformed args).
90
+
91
+ ## Related
92
+
93
+ - [Starter toolboxes](starters.md) — the five bundles the interview can activate.
94
+ - [Behavior miner](behavior-miner.md) — source of the suggestions the interview offers.
docs/toolbox/starters.md CHANGED
@@ -1,96 +1,96 @@
1
- # Starter toolboxes
2
-
3
- Five presets ship in `docs/toolbox/templates/`. `toolbox init` activates
4
- them into `~/.claude/toolboxes.json`; you can then override any field per-repo
5
- in `.toolbox.yaml`.
6
-
7
- ## ship-it
8
-
9
- > **Professional council of 7 experts for end-of-feature review.**
10
-
11
- Runs `code-reviewer`, `security-reviewer`, `architect-review`,
12
- `test-automator`, `performance-engineer`, `accessibility-tester`, and
13
- `docs-lookup` against the diff + graph blast radius.
14
-
15
- - **Triggers**: slash, pre-commit, session-end.
16
- - **Scope**: `dynamic` — diff plus imports of changed modules.
17
- - **Budget**: 200 k tokens / 420 seconds.
18
- - **Guardrail**: on (HIGH/CRITICAL blocks pre-commit).
19
-
20
- Best for: shipping a feature branch. The council covers correctness,
21
- security, architecture, testing, performance, accessibility, and docs in
22
- one pass.
23
-
24
- ## security-sweep
25
-
26
- > **Full-repo security audit with blocking guardrail on HIGH findings.**
27
-
28
- Runs `security-reviewer`, `backend-security-coder`, `frontend-security-coder`,
29
- and `compliance-auditor` against the entire repo.
30
-
31
- - **Triggers**: slash, pre-commit.
32
- - **Scope**: `full` — every tracked file.
33
- - **Budget**: 300 k tokens / 600 seconds.
34
- - **Guardrail**: on.
35
-
36
- Best for: periodic audits, pre-release sweeps, compliance checkpoints.
37
- Expensive; not a per-commit hook.
38
-
39
- ## refactor-safety
40
-
41
- > **Graph-informed refactor review with regression and dead-code checks.**
42
-
43
- Runs `architect-review`, `refactor-cleaner`, `test-automator`, and
44
- `code-reviewer` against diff + graph blast.
45
-
46
- - **Triggers**: slash, pre-commit.
47
- - **Scope**: `dynamic`.
48
- - **Budget**: 120 k tokens / 300 seconds.
49
- - **Guardrail**: off — flags issues without blocking.
50
-
51
- Best for: mid-refactor checkpoints. Catches orphaned code, downstream
52
- breakage, missing test updates.
53
-
54
- ## docs-review
55
-
56
- > **Documentation pass: accuracy, completeness, clarity, and API parity.**
57
-
58
- Runs `docs-lookup`, `technical-writer`, and `code-reviewer` against docs
59
- diffs.
60
-
61
- - **Triggers**: slash, pre-commit.
62
- - **Scope**: `diff`.
63
- - **Budget**: 60 k tokens / 180 seconds.
64
- - **Guardrail**: off.
65
-
66
- Best for: docs-heavy branches and README updates.
67
-
68
- ## fresh-repo-init
69
-
70
- > **New-repo bootstrap: run the intent interview, scaffold plan, pick initial toolbox.**
71
-
72
- Invokes `intent_interview` in interactive mode, then activates whichever
73
- starters the user selects.
74
-
75
- - **Triggers**: slash only.
76
- - **Scope**: `full` (fresh scan of a new repo).
77
- - **Budget**: small — this bundle is just an orchestrator.
78
-
79
- Best for: `git init` followed by `toolbox init`.
80
-
81
- ## Activation
82
-
83
- ```bash
84
- # Pick starters interactively
85
- python -m intent_interview init
86
-
87
- # Non-interactive preset
88
- python -m intent_interview init --preset existing --apply
89
- python -m intent_interview init --preset docs-heavy --apply
90
- python -m intent_interview init --preset security-first --apply
91
-
92
- # Activate a specific starter directly
93
- ctx-toolbox activate ship-it
94
- ```
95
-
96
- See [Intent interview](intent-interview.md) for the full flow.
 
1
+ # Starter toolboxes
2
+
3
+ Five presets ship in `docs/toolbox/templates/`. `toolbox init` activates
4
+ them into `~/.claude/toolboxes.json`; you can then override any field per-repo
5
+ in `.toolbox.yaml`.
6
+
7
+ ## ship-it
8
+
9
+ > **Professional council of 7 experts for end-of-feature review.**
10
+
11
+ Runs `code-reviewer`, `security-reviewer`, `architect-review`,
12
+ `test-automator`, `performance-engineer`, `accessibility-tester`, and
13
+ `docs-lookup` against the diff + graph blast radius.
14
+
15
+ - **Triggers**: slash, pre-commit, session-end.
16
+ - **Scope**: `dynamic` — diff plus imports of changed modules.
17
+ - **Budget**: 200 k tokens / 420 seconds.
18
+ - **Guardrail**: on (HIGH/CRITICAL blocks pre-commit).
19
+
20
+ Best for: shipping a feature branch. The council covers correctness,
21
+ security, architecture, testing, performance, accessibility, and docs in
22
+ one pass.
23
+
24
+ ## security-sweep
25
+
26
+ > **Full-repo security audit with blocking guardrail on HIGH findings.**
27
+
28
+ Runs `security-reviewer`, `backend-security-coder`, `frontend-security-coder`,
29
+ and `compliance-auditor` against the entire repo.
30
+
31
+ - **Triggers**: slash, pre-commit.
32
+ - **Scope**: `full` — every tracked file.
33
+ - **Budget**: 300 k tokens / 600 seconds.
34
+ - **Guardrail**: on.
35
+
36
+ Best for: periodic audits, pre-release sweeps, compliance checkpoints.
37
+ Expensive; not a per-commit hook.
38
+
39
+ ## refactor-safety
40
+
41
+ > **Graph-informed refactor review with regression and dead-code checks.**
42
+
43
+ Runs `architect-review`, `refactor-cleaner`, `test-automator`, and
44
+ `code-reviewer` against diff + graph blast.
45
+
46
+ - **Triggers**: slash, pre-commit.
47
+ - **Scope**: `dynamic`.
48
+ - **Budget**: 120 k tokens / 300 seconds.
49
+ - **Guardrail**: off — flags issues without blocking.
50
+
51
+ Best for: mid-refactor checkpoints. Catches orphaned code, downstream
52
+ breakage, missing test updates.
53
+
54
+ ## docs-review
55
+
56
+ > **Documentation pass: accuracy, completeness, clarity, and API parity.**
57
+
58
+ Runs `docs-lookup`, `technical-writer`, and `code-reviewer` against docs
59
+ diffs.
60
+
61
+ - **Triggers**: slash, pre-commit.
62
+ - **Scope**: `diff`.
63
+ - **Budget**: 60 k tokens / 180 seconds.
64
+ - **Guardrail**: off.
65
+
66
+ Best for: docs-heavy branches and README updates.
67
+
68
+ ## fresh-repo-init
69
+
70
+ > **New-repo bootstrap: run the intent interview, scaffold plan, pick initial toolbox.**
71
+
72
+ Invokes `intent_interview` in interactive mode, then activates whichever
73
+ starters the user selects.
74
+
75
+ - **Triggers**: slash only.
76
+ - **Scope**: `full` (fresh scan of a new repo).
77
+ - **Budget**: small — this bundle is just an orchestrator.
78
+
79
+ Best for: `git init` followed by `toolbox init`.
80
+
81
+ ## Activation
82
+
83
+ ```bash
84
+ # Pick starters interactively
85
+ python -m intent_interview init
86
+
87
+ # Non-interactive preset
88
+ python -m intent_interview init --preset existing --apply
89
+ python -m intent_interview init --preset docs-heavy --apply
90
+ python -m intent_interview init --preset security-first --apply
91
+
92
+ # Activate a specific starter directly
93
+ ctx-toolbox activate ship-it
94
+ ```
95
+
96
+ See [Intent interview](intent-interview.md) for the full flow.
docs/toolbox/verdicts.md CHANGED
@@ -1,142 +1,142 @@
1
- # Verdicts & guardrails
2
-
3
- [`src/toolbox_verdict.py`](https://github.com/stevesolun/ctx/blob/main/src/toolbox_verdict.py)
4
- owns the council's finding ledger. A `RunPlan` says *what should run*; a
5
- `Verdict` says *what was found* and, if the level escalates high enough,
6
- blocks `git commit`.
7
-
8
- ## Data model
9
-
10
- ```python
11
- @dataclass(frozen=True)
12
- class Evidence:
13
- file: str
14
- line: int | None = None
15
- note: str = ""
16
-
17
- @dataclass(frozen=True)
18
- class Finding:
19
- id: str # stable, hash(level|agent|title)
20
- level: str # "LOW" | "MEDIUM" | "HIGH" | "CRITICAL"
21
- title: str
22
- agent: str = ""
23
- evidence: tuple[Evidence, ...] = ()
24
- rationale: str = ""
25
- created_at: float = 0.0
26
-
27
- @dataclass(frozen=True)
28
- class Verdict:
29
- plan_hash: str
30
- level: str # max(findings)
31
- summary: str
32
- findings: tuple[Finding, ...]
33
- created_at: float
34
- updated_at: float
35
- ```
36
-
37
- Level escalation is always `max(findings)`. Clearing a finding
38
- re-escalates from whatever remains.
39
-
40
- ## Storage
41
-
42
- ```
43
- ~/.claude/toolbox-runs/
44
- abc123.json # the RunPlan
45
- abc123.verdict.json # the Verdict (sibling)
46
- ```
47
-
48
- Same directory, same hash. A single `history` sweep covers both.
49
-
50
- ## Merge-by-id
51
-
52
- Agents can refine a previous finding by recording with the same id.
53
- The new record replaces the old one (rationale, evidence, level all
54
- update). This is how a `security-reviewer` can start with a MEDIUM
55
- finding, then bump it to CRITICAL after deeper analysis — without
56
- leaving duplicate entries.
57
-
58
- The default id is `sha256(level|agent|title)[:12]`, so the same
59
- agent recording the same titled issue naturally dedups. Pass
60
- `--id custom-value` if you need a different stable key.
61
-
62
- ## Blocking
63
-
64
- `toolbox_hooks` reads `<plan>.verdict.json` after a `pre-commit`
65
- council runs. If `level in {"HIGH", "CRITICAL"}` and the toolbox has
66
- `guardrail: true`, it returns exit `2`, which stops the commit.
67
-
68
- `LOW` and `MEDIUM` findings are logged but never block.
69
-
70
- ## CLI
71
-
72
- ```bash
73
- # Record a finding
74
- python -m toolbox_verdict record \
75
- --plan-hash abc123 \
76
- --level HIGH \
77
- --title "SQL injection in users.py" \
78
- --agent security-reviewer \
79
- --evidence src/users.py:42:unescaped input \
80
- --rationale "req.form values flow into raw SQL"
81
-
82
- # Show the verdict
83
- python -m toolbox_verdict show --plan-hash abc123
84
-
85
- # JSON payload for piping
86
- python -m toolbox_verdict show --plan-hash abc123 --json
87
-
88
- # Recent verdicts (retrospective)
89
- python -m toolbox_verdict retro --limit 10
90
-
91
- # Only HIGH/CRITICAL
92
- python -m toolbox_verdict retro --min-level HIGH
93
-
94
- # Pretty-print the evidence chain
95
- python -m toolbox_verdict explain --plan-hash abc123
96
-
97
- # Remove a single finding
98
- python -m toolbox_verdict clear --plan-hash abc123 --id <id>
99
- ```
100
-
101
- ## Evidence parsing
102
-
103
- `parse_evidence()` accepts three forms, parsed right-to-left so Windows
104
- drive-letter paths don't trip the delimiter:
105
-
106
- - `src/foo.py` → `Evidence(file="src/foo.py")`
107
- - `src/foo.py:42` → `Evidence(file="src/foo.py", line=42)`
108
- - `src/foo.py:42:race on counter` → `Evidence(file=..., line=42, note=...)`
109
- - `C:/Users/me/foo.py:17` → `Evidence(file="C:/Users/me/foo.py", line=17)`
110
-
111
- Empty specs yield an `Evidence` with an empty file and are filtered out
112
- at `build_finding()` time.
113
-
114
- ## Explain output
115
-
116
- ```
117
- [verdict] plan=abc123 level=HIGH 2 finding(s): 1 high, 1 low
118
- - [HIGH] SQL injection in users.py (agent: security-reviewer)
119
- why: req.form values flow into raw SQL
120
- evidence: src/users.py:42 — unescaped input
121
- - [LOW] style: trailing whitespace (agent: code-reviewer)
122
- evidence: src/users.py:57
123
- ```
124
-
125
- Findings render in severity-desc order so the blocking issue always
126
- appears first.
127
-
128
- ## Retrospective
129
-
130
- `recent_verdicts()` returns verdicts sorted by `updated_at` desc:
131
-
132
- ```
133
- [retro] 3 recent verdict(s):
134
- - plan-crit CRITICAL BLOCK 1 finding(s): 1 critical
135
- - plan-hi HIGH BLOCK 2 finding(s): 1 high, 1 low
136
- - plan-ok LOW ok 1 finding(s): 1 low
137
- ```
138
-
139
- ## Related
140
-
141
- - [Hooks & triggers](hooks.md) — where the `2` exit blocks the commit.
142
- - [Council runner](council-runner.md) — where the plan hash comes from.
 
1
+ # Verdicts & guardrails
2
+
3
+ [`src/toolbox_verdict.py`](https://github.com/stevesolun/ctx/blob/main/src/toolbox_verdict.py)
4
+ owns the council's finding ledger. A `RunPlan` says *what should run*; a
5
+ `Verdict` says *what was found* and, if the level escalates high enough,
6
+ blocks `git commit`.
7
+
8
+ ## Data model
9
+
10
+ ```python
11
+ @dataclass(frozen=True)
12
+ class Evidence:
13
+ file: str
14
+ line: int | None = None
15
+ note: str = ""
16
+
17
+ @dataclass(frozen=True)
18
+ class Finding:
19
+ id: str # stable, hash(level|agent|title)
20
+ level: str # "LOW" | "MEDIUM" | "HIGH" | "CRITICAL"
21
+ title: str
22
+ agent: str = ""
23
+ evidence: tuple[Evidence, ...] = ()
24
+ rationale: str = ""
25
+ created_at: float = 0.0
26
+
27
+ @dataclass(frozen=True)
28
+ class Verdict:
29
+ plan_hash: str
30
+ level: str # max(findings)
31
+ summary: str
32
+ findings: tuple[Finding, ...]
33
+ created_at: float
34
+ updated_at: float
35
+ ```
36
+
37
+ Level escalation is always `max(findings)`. Clearing a finding
38
+ re-escalates from whatever remains.
39
+
40
+ ## Storage
41
+
42
+ ```
43
+ ~/.claude/toolbox-runs/
44
+ abc123.json # the RunPlan
45
+ abc123.verdict.json # the Verdict (sibling)
46
+ ```
47
+
48
+ Same directory, same hash. A single `history` sweep covers both.
49
+
50
+ ## Merge-by-id
51
+
52
+ Agents can refine a previous finding by recording with the same id.
53
+ The new record replaces the old one (rationale, evidence, level all
54
+ update). This is how a `security-reviewer` can start with a MEDIUM
55
+ finding, then bump it to CRITICAL after deeper analysis — without
56
+ leaving duplicate entries.
57
+
58
+ The default id is `sha256(level|agent|title)[:12]`, so the same
59
+ agent recording the same titled issue naturally dedups. Pass
60
+ `--id custom-value` if you need a different stable key.
61
+
62
+ ## Blocking
63
+
64
+ `toolbox_hooks` reads `<plan>.verdict.json` after a `pre-commit`
65
+ council runs. If `level in {"HIGH", "CRITICAL"}` and the toolbox has
66
+ `guardrail: true`, it returns exit `2`, which stops the commit.
67
+
68
+ `LOW` and `MEDIUM` findings are logged but never block.
69
+
70
+ ## CLI
71
+
72
+ ```bash
73
+ # Record a finding
74
+ python -m toolbox_verdict record \
75
+ --plan-hash abc123 \
76
+ --level HIGH \
77
+ --title "SQL injection in users.py" \
78
+ --agent security-reviewer \
79
+ --evidence src/users.py:42:unescaped input \
80
+ --rationale "req.form values flow into raw SQL"
81
+
82
+ # Show the verdict
83
+ python -m toolbox_verdict show --plan-hash abc123
84
+
85
+ # JSON payload for piping
86
+ python -m toolbox_verdict show --plan-hash abc123 --json
87
+
88
+ # Recent verdicts (retrospective)
89
+ python -m toolbox_verdict retro --limit 10
90
+
91
+ # Only HIGH/CRITICAL
92
+ python -m toolbox_verdict retro --min-level HIGH
93
+
94
+ # Pretty-print the evidence chain
95
+ python -m toolbox_verdict explain --plan-hash abc123
96
+
97
+ # Remove a single finding
98
+ python -m toolbox_verdict clear --plan-hash abc123 --id <id>
99
+ ```
100
+
101
+ ## Evidence parsing
102
+
103
+ `parse_evidence()` accepts three forms, parsed right-to-left so Windows
104
+ drive-letter paths don't trip the delimiter:
105
+
106
+ - `src/foo.py` → `Evidence(file="src/foo.py")`
107
+ - `src/foo.py:42` → `Evidence(file="src/foo.py", line=42)`
108
+ - `src/foo.py:42:race on counter` → `Evidence(file=..., line=42, note=...)`
109
+ - `C:/Users/me/foo.py:17` → `Evidence(file="C:/Users/me/foo.py", line=17)`
110
+
111
+ Empty specs yield an `Evidence` with an empty file and are filtered out
112
+ at `build_finding()` time.
113
+
114
+ ## Explain output
115
+
116
+ ```
117
+ [verdict] plan=abc123 level=HIGH 2 finding(s): 1 high, 1 low
118
+ - [HIGH] SQL injection in users.py (agent: security-reviewer)
119
+ why: req.form values flow into raw SQL
120
+ evidence: src/users.py:42 — unescaped input
121
+ - [LOW] style: trailing whitespace (agent: code-reviewer)
122
+ evidence: src/users.py:57
123
+ ```
124
+
125
+ Findings render in severity-desc order so the blocking issue always
126
+ appears first.
127
+
128
+ ## Retrospective
129
+
130
+ `recent_verdicts()` returns verdicts sorted by `updated_at` desc:
131
+
132
+ ```
133
+ [retro] 3 recent verdict(s):
134
+ - plan-crit CRITICAL BLOCK 1 finding(s): 1 critical
135
+ - plan-hi HIGH BLOCK 2 finding(s): 1 high, 1 low
136
+ - plan-ok LOW ok 1 finding(s): 1 low
137
+ ```
138
+
139
+ ## Related
140
+
141
+ - [Hooks & triggers](hooks.md) — where the `2` exit blocks the commit.
142
+ - [Council runner](council-runner.md) — where the plan hash comes from.
graph/README.md CHANGED
@@ -1,274 +1,274 @@
1
- # Knowledge Graph Artifacts
2
-
3
- This directory ships the pre-built ctx LLM-wiki and knowledge graph.
4
-
5
- Current snapshot:
6
-
7
- - **102,928 graph nodes**
8
- - **2,913,960 graph edges**
9
- - **52 Louvain communities**
10
- - **91,464 skill entity pages**; **89,465** have hydrated catalog bodies
11
- - **467 agent pages**
12
- - **10,790 MCP server pages**
13
- - **207 harness pages**
14
- - **89,465 hydrated `SKILL.md` bodies**
15
- - **28,612 long skill bodies converted through the micro-skill gate**
16
-
17
- The runtime recommendation paths use this graph in two ways:
18
-
19
- - Development recommendations return skills, agents, and MCP servers only.
20
- - Custom/API/local model onboarding recommends harnesses using the higher harness fit floor in `src/config.json`.
21
-
22
- ## Files
23
-
24
- | File | Contents |
25
- |---|---|
26
- | `wiki-graph-runtime.tar.gz` | Fast install artifact used by default `ctx-init --graph`: `graphify-out/*`, the skill index, 207 harness pages, wiki index files, and Obsidian metadata needed for recommendations and harness dry-runs without expanding every entity page |
27
- | `wiki-graph.tar.gz` | Full LLM-wiki: entity pages, converted skill bodies, mirrored agent bodies, concept pages, `graphify-out/graph.json`, `graph-delta.json`, export manifest, communities, skill indexes, and Obsidian metadata |
28
- | Skill catalog gzip | Compressed skill index for the 89,465 body-backed skill entries shipped in the wiki |
29
- | `communities.json` | Current Louvain community export |
30
- | `entity-overlays.jsonl` | Release overlay for first-class entities added after the base graph export; installed beside `graphify-out/graph.json` by `ctx-init --graph` |
31
- | `graphify-out/dashboard-neighborhoods.sqlite3` inside both tarballs | Compact top-neighbor index used by `ctx-monitor` so `/api/graph/<slug>.json` does not cold-parse the 818 MiB graph JSON |
32
- | `viz-overview.html` | Plotly overview of the graph |
33
- | `viz-python.html` | Python-focused graph view |
34
- | `viz-security.html` | Security-focused graph view |
35
- | `viz-ai-agents.html` | AI-agent-focused graph view |
36
- | `sample-top60.html` | Interactive top-degree sample |
37
-
38
- Preview HTML files are generated from the shipped `graphify-out/graph.json`
39
- and embed the graph export ID in `<meta name="ctx-graph-export-id">`. Static
40
- PNG snapshots are intentionally not shipped because they can drift from the
41
- current tarball without an executable freshness check.
42
-
43
- ## Runtime vs Full Wiki
44
-
45
- `ctx-init --graph` installs `wiki-graph-runtime.tar.gz` by default. That is the
46
- right path for recommendations and first-time installs because it avoids
47
- expanding hundreds of thousands of markdown files while still shipping the
48
- harness pages needed by `ctx-harness-install --dry-run`. Use
49
- `ctx-init --graph --graph-install-mode full` or manual full extraction when you
50
- want local wiki browsing, Obsidian, or the converted skill body tree.
51
-
52
- ## What Is Inside `wiki-graph.tar.gz`
53
-
54
- - `entities/skills/` - all skill entity pages
55
- - `entities/agents/` - agent entity pages
56
- - `entities/mcp-servers/<shard>/` - sharded MCP server entity pages
57
- - `entities/harnesses/` - harness entity pages
58
- - `converted/` - installable skill bodies
59
- - `converted-agents/` - mirrored agent bodies
60
- - `concepts/` - community concept pages
61
- - `external-catalogs/` - machine-readable skill index, summary, and coverage metadata
62
- - `graphify-out/graph.json` - NetworkX node-link graph
63
- - `graphify-out/graph-delta.json` - delta export for the latest graph generation
64
- - `graphify-out/graph-export-manifest.json` - export manifest tying graph, delta, communities, and report to one generation
65
- - `graphify-out/communities.json` - community export
66
- - `SCHEMA.md`, `index.md`, `log.md`, `catalog.md` - wiki contract and indexes
67
- - `.obsidian/` - vault metadata for local graph browsing
68
-
69
- `SKILL.md.original` backups, transient `.lock` files, and `.ctx/` queue state
70
- are not shipped. Local micro-skill conversion may keep `.original` files for
71
- traceability, but the packaged tarball excludes them so users do not ingest raw
72
- long bodies after conversion.
73
-
74
- ## Extract
75
-
76
- Default runtime install:
77
-
78
- ```bash
79
- ctx-init --graph
80
- ```
81
-
82
- Full wiki extraction:
83
-
84
- ```bash
85
- mkdir -p ~/.claude/skill-wiki
86
- tar xzf graph/wiki-graph.tar.gz -C ~/.claude/skill-wiki/
87
- ```
88
-
89
- On Windows PowerShell, use the built-in `tar.exe` without `--force-local`:
90
-
91
- ```powershell
92
- New-Item -ItemType Directory -Force "$env:USERPROFILE\.claude\skill-wiki"
93
- tar -xzf graph\wiki-graph.tar.gz -C "$env:USERPROFILE\.claude\skill-wiki"
94
- ```
95
-
96
- With Git Bash or MSYS tar, use `--force-local` only when the `-C` target is a
97
- drive-letter path:
98
-
99
- ```bash
100
- tar --force-local xzf graph/wiki-graph.tar.gz -C C:/Users/<you>/.claude/skill-wiki/
101
- ```
102
-
103
- ## Validate
104
-
105
- ```bash
106
- python src/validate_graph_artifacts.py --deep
107
- python src/update_repo_stats.py --check
108
- ```
109
-
110
- For release-count validation, pin the exact snapshot numbers:
111
-
112
- ```bash
113
- python src/validate_graph_artifacts.py --deep \
114
- --expected-nodes 102928 \
115
- --expected-edges 2913960 \
116
- --expected-semantic-edges 1683193 \
117
- --expected-harness-nodes 207 \
118
- --expected-skill-pages 91464 \
119
- --expected-agent-pages 467 \
120
- --expected-mcp-pages 10790 \
121
- --expected-harness-pages 207
122
- ```
123
-
124
- Manual sanity checks:
125
-
126
- ```bash
127
- tar -tzf graph/wiki-graph.tar.gz | grep 'graphify-out/graph.json'
128
- tar -tzf graph/wiki-graph.tar.gz | grep 'external-catalogs/.*/catalog.json'
129
- tar -tzf graph/wiki-graph.tar.gz | grep 'SKILL.md.original' && exit 1 || true
130
- tar -tzf graph/wiki-graph.tar.gz | grep '\.lock$' && exit 1 || true
131
- tar -tzf graph/wiki-graph.tar.gz | grep '^\./\.ctx/' && exit 1 || true
132
- ```
133
-
134
- Windows PowerShell equivalent for the exclusion checks:
135
-
136
- ```powershell
137
- tar -tzf graph/wiki-graph.tar.gz | Select-String 'SKILL.md.original'
138
- tar -tzf graph/wiki-graph.tar.gz | Select-String '\.lock$'
139
- tar -tzf graph/wiki-graph.tar.gz | Select-String '^\./\.ctx/'
140
- ```
141
-
142
- The PowerShell commands should print nothing.
143
-
144
- ## Rebuild
145
-
146
- After adding or updating skills, agents, MCP servers, or harnesses:
147
-
148
- ```bash
149
- ctx-wiki-worker --wiki ~/.claude/skill-wiki --limit 1
150
- ctx-scan-repo --repo . --recommend
151
- ```
152
-
153
- The worker path is the fast local update path. It validates the queued entity
154
- page, updates the wiki index, and attempts incremental ANN attach into
155
- `graphify-out/entity-overlays.jsonl` when the semantic vector index exists. It
156
- also queues the normal incremental graph export job, so a full rebuild remains
157
- the reconciliation path for release artifacts.
158
-
159
- If the worker reports that incremental attach was skipped because no vector
160
- index exists, build the exact portable index:
161
-
162
- ```bash
163
- ctx-wiki-graphify \
164
- --wiki-dir ~/.claude/skill-wiki \
165
- --incremental \
166
- --graph-only \
167
- --semantic-vector-index numpy-flat
168
- ```
169
-
170
- Then drain pending queue work again:
171
-
172
- ```bash
173
- ctx-wiki-worker --wiki ~/.claude/skill-wiki
174
- ```
175
-
176
- Before promoting an ANN backend or changed thresholds, run the shadow gate:
177
-
178
- ```bash
179
- ctx-incremental-shadow \
180
- --index-dir ~/.claude/skill-wiki/.embedding-cache/graph/vector-index \
181
- --graph ~/.claude/skill-wiki/graphify-out/graph.json \
182
- --sample-size 100 \
183
- --min-overlap 0.85
184
- ```
185
-
186
- It reports precision/recall, top-k agreement, score deltas, and bad examples;
187
- the release gate fails when recall at the largest requested top-k is below the
188
- overlap floor.
189
-
190
- For release artifact rebuilds:
191
-
192
- ```bash
193
- python scripts/graph_artifact_guard.py park
194
- ctx-wiki-graphify
195
- python src/validate_graph_artifacts.py --deep
196
- python src/update_repo_stats.py --check
197
- ```
198
-
199
- `park` sets Git's local `skip-worktree` bit for the heavyweight generated
200
- archives: `graph/wiki-graph.tar.gz`, `graph/wiki-graph-runtime.tar.gz`, and
201
- the compressed skill index. Keep them parked while graph/wiki generation,
202
- validation, dashboard smoke, and stats checks are still in progress. This
203
- prevents background Git integrations from repeatedly staging hundreds of
204
- megabytes through the Git LFS clean filter. When the release candidate is final,
205
- unpark and stage the artifacts exactly once:
206
-
207
- ```bash
208
- python scripts/graph_artifact_guard.py unpark
209
- git add graph/wiki-graph.tar.gz graph/wiki-graph-runtime.tar.gz \
210
- graph/skills-sh-catalog.json.gz graph/communities.json graph/entity-overlays.jsonl
211
- python scripts/graph_artifact_guard.py prune
212
- ```
213
-
214
- If a local Git integration gets interrupted while artifacts are dirty,
215
- `python scripts/graph_artifact_guard.py prune` removes prunable local LFS cache
216
- entries. It does not delete tracked graph files, rewrite history, or change the
217
- remote LFS store. Repo-wide `git prune --expire=now` is intentionally opt-in via
218
- `--include-git-prune` because it can discard unrelated dangling recovery objects.
219
-
220
- For a bulk skill refresh, update the existing shipped tarball through the
221
- release refresh path:
222
-
223
- ```bash
224
- python src/import_skills_sh_catalog.py \
225
- --from-catalog <skill-catalog.json.gz> \
226
- --catalog-out <skill-catalog.json.gz> \
227
- --wiki-tar graph/wiki-graph.tar.gz \
228
- --update-wiki-tar
229
- ```
230
-
231
- For a full local wiki repack, write the tarball to the sibling staged path,
232
- then promote that staged candidate after validation:
233
-
234
- ```bash
235
- cd ~/.claude/skill-wiki
236
- tar --force-local -czf /path/to/ctx/graph/wiki-graph.tar.gz.staged \
237
- --exclude='.trash' \
238
- --exclude='__pycache__' \
239
- --exclude='./raw' \
240
- --exclude='./.embedding-cache' \
241
- --exclude='./.ingest-checkpoint' \
242
- --exclude='./.enrich-checkpoint' \
243
- --exclude='./.ctx' \
244
- --exclude='./graphify-out/graph.pickle' \
245
- --exclude='*.original' \
246
- --exclude='*.lock' \
247
- .
248
- cd /path/to/ctx
249
- python -c "from pathlib import Path; from ctx.core.wiki.artifact_promotion import promote_staged_artifact; from import_skills_sh_catalog import _validate_wiki_tarball_candidate; promote_staged_artifact(Path('graph/wiki-graph.tar.gz.staged'), Path('graph/wiki-graph.tar.gz'), validate=_validate_wiki_tarball_candidate)"
250
- ```
251
-
252
- The repack command above is for Git Bash/MSYS. In Linux/macOS shells omit
253
- `--force-local`; in PowerShell use `tar -czf` without `--force-local`.
254
-
255
- Both flows validate candidates before atomic promotion. Each promoted artifact
256
- gets a sibling `*.promotion.json` file with current, candidate, and `last_good`
257
- hashes for review or rollback. The graph, delta, communities, report, and
258
- export manifest are shipped together and carry the same export ID so validation
259
- can reject mixed or partially refreshed graph generations. Raw `.original`
260
- backups, transient `.lock` files, and `.ctx/` queue state must not appear in
261
- the shipped tarball.
262
-
263
- ## Implementation Notes
264
-
265
- The graph is built by `ctx.core.wiki.wiki_graphify` and the `ctx-wiki-graphify`
266
- console script. Edges blend semantic similarity, explicit tag overlap,
267
- slug-token overlap, source overlap, direct links, quality, usage, type affinity,
268
- and graph-structure signals where available. The shipped default
269
- `graph.min_edge_weight` is `0.03`, chosen from artifact calibration because it
270
- keeps the current topology intact while recording the real shipped floor.
271
-
272
- `nashsu/llm_wiki` was reviewed for design ideas around persistent wiki
273
- contracts, queues, retrieval, and graph maintenance. ctx does not vendor that
274
- code in this MIT repository.
 
1
+ # Knowledge Graph Artifacts
2
+
3
+ This directory ships the pre-built ctx LLM-wiki and knowledge graph.
4
+
5
+ Current snapshot:
6
+
7
+ - **102,928 graph nodes**
8
+ - **2,913,960 graph edges**
9
+ - **52 Louvain communities**
10
+ - **91,464 skill entity pages**; **89,465** have hydrated catalog bodies
11
+ - **467 agent pages**
12
+ - **10,790 MCP server pages**
13
+ - **207 harness pages**
14
+ - **89,465 hydrated `SKILL.md` bodies**
15
+ - **28,612 long skill bodies converted through the micro-skill gate**
16
+
17
+ The runtime recommendation paths use this graph in two ways:
18
+
19
+ - Development recommendations return skills, agents, and MCP servers only.
20
+ - Custom/API/local model onboarding recommends harnesses using the higher harness fit floor in `src/config.json`.
21
+
22
+ ## Files
23
+
24
+ | File | Contents |
25
+ |---|---|
26
+ | `wiki-graph-runtime.tar.gz` | Fast install artifact used by default `ctx-init --graph`: `graphify-out/*`, the skill index, 207 harness pages, wiki index files, and Obsidian metadata needed for recommendations and harness dry-runs without expanding every entity page |
27
+ | `wiki-graph.tar.gz` | Full LLM-wiki: entity pages, converted skill bodies, mirrored agent bodies, concept pages, `graphify-out/graph.json`, `graph-delta.json`, export manifest, communities, skill indexes, and Obsidian metadata |
28
+ | Skill catalog gzip | Compressed skill index for the 89,465 body-backed skill entries shipped in the wiki |
29
+ | `communities.json` | Current Louvain community export |
30
+ | `entity-overlays.jsonl` | Release overlay for first-class entities added after the base graph export; installed beside `graphify-out/graph.json` by `ctx-init --graph` |
31
+ | `graphify-out/dashboard-neighborhoods.sqlite3` inside both tarballs | Compact top-neighbor index used by `ctx-monitor` so `/api/graph/<slug>.json` does not cold-parse the 818 MiB graph JSON |
32
+ | `viz-overview.html` | Plotly overview of the graph |
33
+ | `viz-python.html` | Python-focused graph view |
34
+ | `viz-security.html` | Security-focused graph view |
35
+ | `viz-ai-agents.html` | AI-agent-focused graph view |
36
+ | `sample-top60.html` | Interactive top-degree sample |
37
+
38
+ Preview HTML files are generated from the shipped `graphify-out/graph.json`
39
+ and embed the graph export ID in `<meta name="ctx-graph-export-id">`. Static
40
+ PNG snapshots are intentionally not shipped because they can drift from the
41
+ current tarball without an executable freshness check.
42
+
43
+ ## Runtime vs Full Wiki
44
+
45
+ `ctx-init --graph` installs `wiki-graph-runtime.tar.gz` by default. That is the
46
+ right path for recommendations and first-time installs because it avoids
47
+ expanding hundreds of thousands of markdown files while still shipping the
48
+ harness pages needed by `ctx-harness-install --dry-run`. Use
49
+ `ctx-init --graph --graph-install-mode full` or manual full extraction when you
50
+ want local wiki browsing, Obsidian, or the converted skill body tree.
51
+
52
+ ## What Is Inside `wiki-graph.tar.gz`
53
+
54
+ - `entities/skills/` - all skill entity pages
55
+ - `entities/agents/` - agent entity pages
56
+ - `entities/mcp-servers/<shard>/` - sharded MCP server entity pages
57
+ - `entities/harnesses/` - harness entity pages
58
+ - `converted/` - installable skill bodies
59
+ - `converted-agents/` - mirrored agent bodies
60
+ - `concepts/` - community concept pages
61
+ - `external-catalogs/` - machine-readable skill index, summary, and coverage metadata
62
+ - `graphify-out/graph.json` - NetworkX node-link graph
63
+ - `graphify-out/graph-delta.json` - delta export for the latest graph generation
64
+ - `graphify-out/graph-export-manifest.json` - export manifest tying graph, delta, communities, and report to one generation
65
+ - `graphify-out/communities.json` - community export
66
+ - `SCHEMA.md`, `index.md`, `log.md`, `catalog.md` - wiki contract and indexes
67
+ - `.obsidian/` - vault metadata for local graph browsing
68
+
69
+ `SKILL.md.original` backups, transient `.lock` files, and `.ctx/` queue state
70
+ are not shipped. Local micro-skill conversion may keep `.original` files for
71
+ traceability, but the packaged tarball excludes them so users do not ingest raw
72
+ long bodies after conversion.
73
+
74
+ ## Extract
75
+
76
+ Default runtime install:
77
+
78
+ ```bash
79
+ ctx-init --graph
80
+ ```
81
+
82
+ Full wiki extraction:
83
+
84
+ ```bash
85
+ mkdir -p ~/.claude/skill-wiki
86
+ tar xzf graph/wiki-graph.tar.gz -C ~/.claude/skill-wiki/
87
+ ```
88
+
89
+ On Windows PowerShell, use the built-in `tar.exe` without `--force-local`:
90
+
91
+ ```powershell
92
+ New-Item -ItemType Directory -Force "$env:USERPROFILE\.claude\skill-wiki"
93
+ tar -xzf graph\wiki-graph.tar.gz -C "$env:USERPROFILE\.claude\skill-wiki"
94
+ ```
95
+
96
+ With Git Bash or MSYS tar, use `--force-local` only when the `-C` target is a
97
+ drive-letter path:
98
+
99
+ ```bash
100
+ tar --force-local xzf graph/wiki-graph.tar.gz -C C:/Users/<you>/.claude/skill-wiki/
101
+ ```
102
+
103
+ ## Validate
104
+
105
+ ```bash
106
+ python src/validate_graph_artifacts.py --deep
107
+ python src/update_repo_stats.py --check
108
+ ```
109
+
110
+ For release-count validation, pin the exact snapshot numbers:
111
+
112
+ ```bash
113
+ python src/validate_graph_artifacts.py --deep \
114
+ --expected-nodes 102928 \
115
+ --expected-edges 2913960 \
116
+ --expected-semantic-edges 1683193 \
117
+ --expected-harness-nodes 207 \
118
+ --expected-skill-pages 91464 \
119
+ --expected-agent-pages 467 \
120
+ --expected-mcp-pages 10790 \
121
+ --expected-harness-pages 207
122
+ ```
123
+
124
+ Manual sanity checks:
125
+
126
+ ```bash
127
+ tar -tzf graph/wiki-graph.tar.gz | grep 'graphify-out/graph.json'
128
+ tar -tzf graph/wiki-graph.tar.gz | grep 'external-catalogs/.*/catalog.json'
129
+ tar -tzf graph/wiki-graph.tar.gz | grep 'SKILL.md.original' && exit 1 || true
130
+ tar -tzf graph/wiki-graph.tar.gz | grep '\.lock$' && exit 1 || true
131
+ tar -tzf graph/wiki-graph.tar.gz | grep '^\./\.ctx/' && exit 1 || true
132
+ ```
133
+
134
+ Windows PowerShell equivalent for the exclusion checks:
135
+
136
+ ```powershell
137
+ tar -tzf graph/wiki-graph.tar.gz | Select-String 'SKILL.md.original'
138
+ tar -tzf graph/wiki-graph.tar.gz | Select-String '\.lock$'
139
+ tar -tzf graph/wiki-graph.tar.gz | Select-String '^\./\.ctx/'
140
+ ```
141
+
142
+ The PowerShell commands should print nothing.
143
+
144
+ ## Rebuild
145
+
146
+ After adding or updating skills, agents, MCP servers, or harnesses:
147
+
148
+ ```bash
149
+ ctx-wiki-worker --wiki ~/.claude/skill-wiki --limit 1
150
+ ctx-scan-repo --repo . --recommend
151
+ ```
152
+
153
+ The worker path is the fast local update path. It validates the queued entity
154
+ page, updates the wiki index, and attempts incremental ANN attach into
155
+ `graphify-out/entity-overlays.jsonl` when the semantic vector index exists. It
156
+ also queues the normal incremental graph export job, so a full rebuild remains
157
+ the reconciliation path for release artifacts.
158
+
159
+ If the worker reports that incremental attach was skipped because no vector
160
+ index exists, build the exact portable index:
161
+
162
+ ```bash
163
+ ctx-wiki-graphify \
164
+ --wiki-dir ~/.claude/skill-wiki \
165
+ --incremental \
166
+ --graph-only \
167
+ --semantic-vector-index numpy-flat
168
+ ```
169
+
170
+ Then drain pending queue work again:
171
+
172
+ ```bash
173
+ ctx-wiki-worker --wiki ~/.claude/skill-wiki
174
+ ```
175
+
176
+ Before promoting an ANN backend or changed thresholds, run the shadow gate:
177
+
178
+ ```bash
179
+ ctx-incremental-shadow \
180
+ --index-dir ~/.claude/skill-wiki/.embedding-cache/graph/vector-index \
181
+ --graph ~/.claude/skill-wiki/graphify-out/graph.json \
182
+ --sample-size 100 \
183
+ --min-overlap 0.85
184
+ ```
185
+
186
+ It reports precision/recall, top-k agreement, score deltas, and bad examples;
187
+ the release gate fails when recall at the largest requested top-k is below the
188
+ overlap floor.
189
+
190
+ For release artifact rebuilds:
191
+
192
+ ```bash
193
+ python scripts/graph_artifact_guard.py park
194
+ ctx-wiki-graphify
195
+ python src/validate_graph_artifacts.py --deep
196
+ python src/update_repo_stats.py --check
197
+ ```
198
+
199
+ `park` sets Git's local `skip-worktree` bit for the heavyweight generated
200
+ archives: `graph/wiki-graph.tar.gz`, `graph/wiki-graph-runtime.tar.gz`, and
201
+ the compressed skill index. Keep them parked while graph/wiki generation,
202
+ validation, dashboard smoke, and stats checks are still in progress. This
203
+ prevents background Git integrations from repeatedly staging hundreds of
204
+ megabytes through the Git LFS clean filter. When the release candidate is final,
205
+ unpark and stage the artifacts exactly once:
206
+
207
+ ```bash
208
+ python scripts/graph_artifact_guard.py unpark
209
+ git add graph/wiki-graph.tar.gz graph/wiki-graph-runtime.tar.gz \
210
+ graph/skills-sh-catalog.json.gz graph/communities.json graph/entity-overlays.jsonl
211
+ python scripts/graph_artifact_guard.py prune
212
+ ```
213
+
214
+ If a local Git integration gets interrupted while artifacts are dirty,
215
+ `python scripts/graph_artifact_guard.py prune` removes prunable local LFS cache
216
+ entries. It does not delete tracked graph files, rewrite history, or change the
217
+ remote LFS store. Repo-wide `git prune --expire=now` is intentionally opt-in via
218
+ `--include-git-prune` because it can discard unrelated dangling recovery objects.
219
+
220
+ For a bulk skill refresh, update the existing shipped tarball through the
221
+ release refresh path:
222
+
223
+ ```bash
224
+ python src/import_skills_sh_catalog.py \
225
+ --from-catalog <skill-catalog.json.gz> \
226
+ --catalog-out <skill-catalog.json.gz> \
227
+ --wiki-tar graph/wiki-graph.tar.gz \
228
+ --update-wiki-tar
229
+ ```
230
+
231
+ For a full local wiki repack, write the tarball to the sibling staged path,
232
+ then promote that staged candidate after validation:
233
+
234
+ ```bash
235
+ cd ~/.claude/skill-wiki
236
+ tar --force-local -czf /path/to/ctx/graph/wiki-graph.tar.gz.staged \
237
+ --exclude='.trash' \
238
+ --exclude='__pycache__' \
239
+ --exclude='./raw' \
240
+ --exclude='./.embedding-cache' \
241
+ --exclude='./.ingest-checkpoint' \
242
+ --exclude='./.enrich-checkpoint' \
243
+ --exclude='./.ctx' \
244
+ --exclude='./graphify-out/graph.pickle' \
245
+ --exclude='*.original' \
246
+ --exclude='*.lock' \
247
+ .
248
+ cd /path/to/ctx
249
+ python -c "from pathlib import Path; from ctx.core.wiki.artifact_promotion import promote_staged_artifact; from import_skills_sh_catalog import _validate_wiki_tarball_candidate; promote_staged_artifact(Path('graph/wiki-graph.tar.gz.staged'), Path('graph/wiki-graph.tar.gz'), validate=_validate_wiki_tarball_candidate)"
250
+ ```
251
+
252
+ The repack command above is for Git Bash/MSYS. In Linux/macOS shells omit
253
+ `--force-local`; in PowerShell use `tar -czf` without `--force-local`.
254
+
255
+ Both flows validate candidates before atomic promotion. Each promoted artifact
256
+ gets a sibling `*.promotion.json` file with current, candidate, and `last_good`
257
+ hashes for review or rollback. The graph, delta, communities, report, and
258
+ export manifest are shipped together and carry the same export ID so validation
259
+ can reject mixed or partially refreshed graph generations. Raw `.original`
260
+ backups, transient `.lock` files, and `.ctx/` queue state must not appear in
261
+ the shipped tarball.
262
+
263
+ ## Implementation Notes
264
+
265
+ The graph is built by `ctx.core.wiki.wiki_graphify` and the `ctx-wiki-graphify`
266
+ console script. Edges blend semantic similarity, explicit tag overlap,
267
+ slug-token overlap, source overlap, direct links, quality, usage, type affinity,
268
+ and graph-structure signals where available. The shipped default
269
+ `graph.min_edge_weight` is `0.03`, chosen from artifact calibration because it
270
+ keeps the current topology intact while recording the real shipped floor.
271
+
272
+ `nashsu/llm_wiki` was reviewed for design ideas around persistent wiki
273
+ contracts, queues, retrieval, and graph maintenance. ctx does not vendor that
274
+ code in this MIT repository.
graph/communities.json CHANGED
The diff for this file is too large to render. See raw diff
 
graph/entity-overlays.jsonl CHANGED
The diff for this file is too large to render. See raw diff
 
graph/sample-top60.html CHANGED
The diff for this file is too large to render. See raw diff
 
graph/viz-ai-agents.html CHANGED
The diff for this file is too large to render. See raw diff
 
graph/viz-overview.html CHANGED
The diff for this file is too large to render. See raw diff
 
graph/viz-python.html CHANGED
The diff for this file is too large to render. See raw diff
 
graph/viz-security.html CHANGED
The diff for this file is too large to render. See raw diff
 
imported-skills/julius-caveman/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Julius Brussee
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Julius Brussee
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
imported-skills/julius-caveman/MANIFEST.json CHANGED
@@ -1,123 +1,123 @@
1
- {
2
- "upstream": "https://github.com/JuliusBrussee/caveman",
3
- "upstream_revision": "63a91ecadbf4",
4
- "license": "MIT",
5
- "namespace": "julius-caveman",
6
- "total": 10,
7
- "skills": 7,
8
- "agents": 3,
9
- "entries": [
10
- {
11
- "name": "cavecrew",
12
- "description": "Decision guide for delegating to caveman-style subagents. Tells the main thread WHEN to spawn `cavecrew-investigator` (locate code), `cavecrew-builder` (1-2 file edit), or `cavecrew-reviewer` (diff review) instead of doing the work inline or using vanilla `Explore`. Subagent output is caveman-compressed so the tool-result injected back into main context is ~60% smaller \u2014 main context lasts longer across long sessions. Trigger: \"delegate to subagent\", \"use cavecrew\", \"spawn investigator/builder/reviewer\", \"save context\", \"compressed agent output\".",
13
- "slug": "cavecrew",
14
- "type": "skill",
15
- "source_path": "skills/cavecrew/SKILL.md",
16
- "support_files": [
17
- "README.md"
18
- ],
19
- "lines": 82
20
- },
21
- {
22
- "name": "caveman",
23
- "description": "Ultra-compressed communication mode. Cuts token usage ~75% by speaking like caveman while keeping full technical accuracy. Supports intensity levels: lite, full (default), ultra, wenyan-lite, wenyan-full, wenyan-ultra. Use when user says \"caveman mode\", \"talk like caveman\", \"use caveman\", \"less tokens\", \"be brief\", or invokes /caveman. Also auto-triggers when token efficiency is requested.",
24
- "slug": "caveman",
25
- "type": "skill",
26
- "source_path": "skills/caveman/SKILL.md",
27
- "support_files": [
28
- "README.md"
29
- ],
30
- "lines": 74
31
- },
32
- {
33
- "name": "caveman-commit",
34
- "description": "Ultra-compressed commit message generator. Cuts noise from commit messages while preserving intent and reasoning. Conventional Commits format. Subject \u226450 chars, body only when \"why\" isn't obvious. Use when user says \"write a commit\", \"commit message\", \"generate commit\", \"/commit\", or invokes /caveman-commit. Auto-triggers when staging changes.",
35
- "slug": "caveman-commit",
36
- "type": "skill",
37
- "source_path": "skills/caveman-commit/SKILL.md",
38
- "support_files": [
39
- "README.md"
40
- ],
41
- "lines": 65
42
- },
43
- {
44
- "name": "caveman-compress",
45
- "description": "Compress natural language memory files (CLAUDE.md, todos, preferences) into caveman format to save input tokens. Preserves all technical substance, code, URLs, and structure. Compressed version overwrites the original file. Human-readable backup saved as FILE.original.md. Trigger: /caveman-compress FILEPATH or \"compress memory file\"",
46
- "slug": "caveman-compress",
47
- "type": "skill",
48
- "source_path": "skills/caveman-compress/SKILL.md",
49
- "support_files": [
50
- "README.md",
51
- "scripts/__init__.py",
52
- "scripts/__main__.py",
53
- "scripts/benchmark.py",
54
- "scripts/cli.py",
55
- "scripts/compress.py",
56
- "scripts/detect.py",
57
- "scripts/validate.py",
58
- "SECURITY.md"
59
- ],
60
- "lines": 111
61
- },
62
- {
63
- "name": "caveman-help",
64
- "description": "Quick-reference card for all caveman modes, skills, and commands. One-shot display, not a persistent mode. Trigger: /caveman-help, \"caveman help\", \"what caveman commands\", \"how do I use caveman\".",
65
- "slug": "caveman-help",
66
- "type": "skill",
67
- "source_path": "skills/caveman-help/SKILL.md",
68
- "support_files": [
69
- "README.md"
70
- ],
71
- "lines": 59
72
- },
73
- {
74
- "name": "caveman-review",
75
- "description": "Ultra-compressed code review comments. Cuts noise from PR feedback while preserving the actionable signal. Each comment is one line: location, problem, fix. Use when user says \"review this PR\", \"code review\", \"review the diff\", \"/review\", or invokes /caveman-review. Auto-triggers when reviewing pull requests.",
76
- "slug": "caveman-review",
77
- "type": "skill",
78
- "source_path": "skills/caveman-review/SKILL.md",
79
- "support_files": [
80
- "README.md"
81
- ],
82
- "lines": 55
83
- },
84
- {
85
- "name": "caveman-stats",
86
- "description": "Show real token usage and estimated savings for the current session. Reads directly from the Claude Code session log \u2014 no AI estimation. Triggers on /caveman-stats. Output is injected by the mode-tracker hook; the model itself does not compute the numbers.",
87
- "slug": "caveman-stats",
88
- "type": "skill",
89
- "source_path": "skills/caveman-stats/SKILL.md",
90
- "support_files": [
91
- "README.md"
92
- ],
93
- "lines": 10
94
- },
95
- {
96
- "name": "cavecrew-builder",
97
- "description": "Surgical 1-2 file edit. Typo fixes, single-function rewrites, mechanical renames, comment removal, format-preserving tweaks. Hard refuses 3+ file scope. Returns caveman diff receipt. Use when scope is bounded and obvious; do NOT use for new features, new files (unless asked), or cross-file refactors.",
98
- "slug": "cavecrew-builder",
99
- "type": "agent",
100
- "source_path": "agents/cavecrew-builder.md",
101
- "support_files": [],
102
- "lines": 47
103
- },
104
- {
105
- "name": "cavecrew-investigator",
106
- "description": "Read-only code locator. Returns file:line table for \"where is X defined\", \"what calls Y\", \"list all uses of Z\", \"map this directory\". Output is caveman-compressed so the main thread eats ~60% fewer tokens than vanilla Explore. Refuses to suggest fixes.",
107
- "slug": "cavecrew-investigator",
108
- "type": "agent",
109
- "source_path": "agents/cavecrew-investigator.md",
110
- "support_files": [],
111
- "lines": 57
112
- },
113
- {
114
- "name": "cavecrew-reviewer",
115
- "description": "Diff/branch/file reviewer. One line per finding, severity-tagged, no praise, no scope creep. Output format `path:line: <emoji> <severity>: <problem>. <fix>.` Use for \"review this PR\", \"review my diff\", \"audit this file\". Skips formatting nits unless they change meaning.",
116
- "slug": "cavecrew-reviewer",
117
- "type": "agent",
118
- "source_path": "agents/cavecrew-reviewer.md",
119
- "support_files": [],
120
- "lines": 48
121
- }
122
- ]
123
- }
 
1
+ {
2
+ "upstream": "https://github.com/JuliusBrussee/caveman",
3
+ "upstream_revision": "63a91ecadbf4",
4
+ "license": "MIT",
5
+ "namespace": "julius-caveman",
6
+ "total": 10,
7
+ "skills": 7,
8
+ "agents": 3,
9
+ "entries": [
10
+ {
11
+ "name": "cavecrew",
12
+ "description": "Decision guide for delegating to caveman-style subagents. Tells the main thread WHEN to spawn `cavecrew-investigator` (locate code), `cavecrew-builder` (1-2 file edit), or `cavecrew-reviewer` (diff review) instead of doing the work inline or using vanilla `Explore`. Subagent output is caveman-compressed so the tool-result injected back into main context is ~60% smaller \u2014 main context lasts longer across long sessions. Trigger: \"delegate to subagent\", \"use cavecrew\", \"spawn investigator/builder/reviewer\", \"save context\", \"compressed agent output\".",
13
+ "slug": "cavecrew",
14
+ "type": "skill",
15
+ "source_path": "skills/cavecrew/SKILL.md",
16
+ "support_files": [
17
+ "README.md"
18
+ ],
19
+ "lines": 82
20
+ },
21
+ {
22
+ "name": "caveman",
23
+ "description": "Ultra-compressed communication mode. Cuts token usage ~75% by speaking like caveman while keeping full technical accuracy. Supports intensity levels: lite, full (default), ultra, wenyan-lite, wenyan-full, wenyan-ultra. Use when user says \"caveman mode\", \"talk like caveman\", \"use caveman\", \"less tokens\", \"be brief\", or invokes /caveman. Also auto-triggers when token efficiency is requested.",
24
+ "slug": "caveman",
25
+ "type": "skill",
26
+ "source_path": "skills/caveman/SKILL.md",
27
+ "support_files": [
28
+ "README.md"
29
+ ],
30
+ "lines": 74
31
+ },
32
+ {
33
+ "name": "caveman-commit",
34
+ "description": "Ultra-compressed commit message generator. Cuts noise from commit messages while preserving intent and reasoning. Conventional Commits format. Subject \u226450 chars, body only when \"why\" isn't obvious. Use when user says \"write a commit\", \"commit message\", \"generate commit\", \"/commit\", or invokes /caveman-commit. Auto-triggers when staging changes.",
35
+ "slug": "caveman-commit",
36
+ "type": "skill",
37
+ "source_path": "skills/caveman-commit/SKILL.md",
38
+ "support_files": [
39
+ "README.md"
40
+ ],
41
+ "lines": 65
42
+ },
43
+ {
44
+ "name": "caveman-compress",
45
+ "description": "Compress natural language memory files (CLAUDE.md, todos, preferences) into caveman format to save input tokens. Preserves all technical substance, code, URLs, and structure. Compressed version overwrites the original file. Human-readable backup saved as FILE.original.md. Trigger: /caveman-compress FILEPATH or \"compress memory file\"",
46
+ "slug": "caveman-compress",
47
+ "type": "skill",
48
+ "source_path": "skills/caveman-compress/SKILL.md",
49
+ "support_files": [
50
+ "README.md",
51
+ "scripts/__init__.py",
52
+ "scripts/__main__.py",
53
+ "scripts/benchmark.py",
54
+ "scripts/cli.py",
55
+ "scripts/compress.py",
56
+ "scripts/detect.py",
57
+ "scripts/validate.py",
58
+ "SECURITY.md"
59
+ ],
60
+ "lines": 111
61
+ },
62
+ {
63
+ "name": "caveman-help",
64
+ "description": "Quick-reference card for all caveman modes, skills, and commands. One-shot display, not a persistent mode. Trigger: /caveman-help, \"caveman help\", \"what caveman commands\", \"how do I use caveman\".",
65
+ "slug": "caveman-help",
66
+ "type": "skill",
67
+ "source_path": "skills/caveman-help/SKILL.md",
68
+ "support_files": [
69
+ "README.md"
70
+ ],
71
+ "lines": 59
72
+ },
73
+ {
74
+ "name": "caveman-review",
75
+ "description": "Ultra-compressed code review comments. Cuts noise from PR feedback while preserving the actionable signal. Each comment is one line: location, problem, fix. Use when user says \"review this PR\", \"code review\", \"review the diff\", \"/review\", or invokes /caveman-review. Auto-triggers when reviewing pull requests.",
76
+ "slug": "caveman-review",
77
+ "type": "skill",
78
+ "source_path": "skills/caveman-review/SKILL.md",
79
+ "support_files": [
80
+ "README.md"
81
+ ],
82
+ "lines": 55
83
+ },
84
+ {
85
+ "name": "caveman-stats",
86
+ "description": "Show real token usage and estimated savings for the current session. Reads directly from the Claude Code session log \u2014 no AI estimation. Triggers on /caveman-stats. Output is injected by the mode-tracker hook; the model itself does not compute the numbers.",
87
+ "slug": "caveman-stats",
88
+ "type": "skill",
89
+ "source_path": "skills/caveman-stats/SKILL.md",
90
+ "support_files": [
91
+ "README.md"
92
+ ],
93
+ "lines": 10
94
+ },
95
+ {
96
+ "name": "cavecrew-builder",
97
+ "description": "Surgical 1-2 file edit. Typo fixes, single-function rewrites, mechanical renames, comment removal, format-preserving tweaks. Hard refuses 3+ file scope. Returns caveman diff receipt. Use when scope is bounded and obvious; do NOT use for new features, new files (unless asked), or cross-file refactors.",
98
+ "slug": "cavecrew-builder",
99
+ "type": "agent",
100
+ "source_path": "agents/cavecrew-builder.md",
101
+ "support_files": [],
102
+ "lines": 47
103
+ },
104
+ {
105
+ "name": "cavecrew-investigator",
106
+ "description": "Read-only code locator. Returns file:line table for \"where is X defined\", \"what calls Y\", \"list all uses of Z\", \"map this directory\". Output is caveman-compressed so the main thread eats ~60% fewer tokens than vanilla Explore. Refuses to suggest fixes.",
107
+ "slug": "cavecrew-investigator",
108
+ "type": "agent",
109
+ "source_path": "agents/cavecrew-investigator.md",
110
+ "support_files": [],
111
+ "lines": 57
112
+ },
113
+ {
114
+ "name": "cavecrew-reviewer",
115
+ "description": "Diff/branch/file reviewer. One line per finding, severity-tagged, no praise, no scope creep. Output format `path:line: <emoji> <severity>: <problem>. <fix>.` Use for \"review this PR\", \"review my diff\", \"audit this file\". Skips formatting nits unless they change meaning.",
116
+ "slug": "cavecrew-reviewer",
117
+ "type": "agent",
118
+ "source_path": "agents/cavecrew-reviewer.md",
119
+ "support_files": [],
120
+ "lines": 48
121
+ }
122
+ ]
123
+ }
imported-skills/julius-caveman/agents/cavecrew-builder.md CHANGED
@@ -1,47 +1,47 @@
1
- ---
2
- name: cavecrew-builder
3
- description: >
4
- Surgical 1-2 file edit. Typo fixes, single-function rewrites, mechanical
5
- renames, comment removal, format-preserving tweaks. Hard refuses 3+ file
6
- scope. Returns caveman diff receipt. Use when scope is bounded and
7
- obvious; do NOT use for new features, new files (unless asked), or
8
- cross-file refactors.
9
- tools: [Read, Edit, Write, Grep, Glob]
10
- ---
11
-
12
- Caveman-ultra. Drop articles/filler. Code/paths exact, backticked. No narration.
13
-
14
- ## Scope
15
-
16
- 1 file ideal. 2 OK. 3+ → refuse.
17
- Edit existing only (new file iff user asked).
18
- No new abstractions. No drive-by refactors. No comment additions.
19
- No `Bash` available — cannot shell out, cannot push, cannot delete.
20
-
21
- ## Workflow
22
-
23
- 1. `Read` target(s). Never edit blind.
24
- 2. `Edit` smallest diff that work.
25
- 3. Re-`Read` to verify.
26
- 4. Return receipt.
27
-
28
- ## Output (receipt)
29
-
30
- ```
31
- <path:line-range> — <change ≤10 words>.
32
- <path:line-range> — <change ≤10 words>.
33
- verified: <re-read OK | mismatch @ path:line>.
34
- ```
35
-
36
- Diff is the artifact. Receipt is the proof. No exploration story.
37
-
38
- ## Refusals (terminal lines)
39
-
40
- 3+ files → `too-big. split: <n one-line tasks>.`
41
- Destructive needed → `needs-confirm. op: <command>.`
42
- Spec ambiguous → `ambiguous. ask: <one question>.`
43
- Tests fail post-edit, can't fix in scope → `regressed. revert path:line. cause: <fragment>.`
44
-
45
- ## Auto-clarity
46
-
47
- Security or destructive paths → write normal English warning, then resume caveman.
 
1
+ ---
2
+ name: cavecrew-builder
3
+ description: >
4
+ Surgical 1-2 file edit. Typo fixes, single-function rewrites, mechanical
5
+ renames, comment removal, format-preserving tweaks. Hard refuses 3+ file
6
+ scope. Returns caveman diff receipt. Use when scope is bounded and
7
+ obvious; do NOT use for new features, new files (unless asked), or
8
+ cross-file refactors.
9
+ tools: [Read, Edit, Write, Grep, Glob]
10
+ ---
11
+
12
+ Caveman-ultra. Drop articles/filler. Code/paths exact, backticked. No narration.
13
+
14
+ ## Scope
15
+
16
+ 1 file ideal. 2 OK. 3+ → refuse.
17
+ Edit existing only (new file iff user asked).
18
+ No new abstractions. No drive-by refactors. No comment additions.
19
+ No `Bash` available — cannot shell out, cannot push, cannot delete.
20
+
21
+ ## Workflow
22
+
23
+ 1. `Read` target(s). Never edit blind.
24
+ 2. `Edit` smallest diff that work.
25
+ 3. Re-`Read` to verify.
26
+ 4. Return receipt.
27
+
28
+ ## Output (receipt)
29
+
30
+ ```
31
+ <path:line-range> — <change ≤10 words>.
32
+ <path:line-range> — <change ≤10 words>.
33
+ verified: <re-read OK | mismatch @ path:line>.
34
+ ```
35
+
36
+ Diff is the artifact. Receipt is the proof. No exploration story.
37
+
38
+ ## Refusals (terminal lines)
39
+
40
+ 3+ files → `too-big. split: <n one-line tasks>.`
41
+ Destructive needed → `needs-confirm. op: <command>.`
42
+ Spec ambiguous → `ambiguous. ask: <one question>.`
43
+ Tests fail post-edit, can't fix in scope → `regressed. revert path:line. cause: <fragment>.`
44
+
45
+ ## Auto-clarity
46
+
47
+ Security or destructive paths → write normal English warning, then resume caveman.
imported-skills/julius-caveman/agents/cavecrew-investigator.md CHANGED
@@ -1,57 +1,57 @@
1
- ---
2
- name: cavecrew-investigator
3
- description: >
4
- Read-only code locator. Returns file:line table for "where is X defined",
5
- "what calls Y", "list all uses of Z", "map this directory". Output is
6
- caveman-compressed so the main thread eats ~60% fewer tokens than
7
- vanilla Explore. Refuses to suggest fixes.
8
- tools: [Read, Grep, Glob, Bash]
9
- model: haiku
10
- ---
11
-
12
- Caveman-ultra. Drop articles/filler/hedging. Code/symbols/paths exact, backticked. Lead with answer.
13
-
14
- ## Job
15
-
16
- Locate. Report. Stop. Never edit, never propose fix.
17
-
18
- ## Output
19
-
20
- ```
21
- <path:line> — `<symbol>` — <≤6 word note>
22
- <path:line> — `<symbol>` — <≤6 word note>
23
- ```
24
-
25
- Group with one-word header when 3+ rows: `Defs:` / `Refs:` / `Callers:` / `Tests:` / `Imports:` / `Sites:`.
26
- Single hit → one line, no header.
27
- Zero hits → `No match.`
28
- Last line → totals: `2 defs, 5 refs.` (omit if 0 or 1).
29
-
30
- ## Tools
31
-
32
- `Grep` for symbols/strings. `Glob` for paths. `Read` only specific ranges. `Bash` for `git log -S`/`git grep`/`find` when faster.
33
-
34
- ## Refusals
35
-
36
- Asked to fix → `Read-only. Spawn cavecrew-builder.`
37
- Asked to design → `Read-only. Spawn cavecrew-builder or use main thread.`
38
-
39
- ## Auto-clarity
40
-
41
- Security warnings, destructive ops → write normal English. Resume after.
42
-
43
- ## Example
44
-
45
- Q: "where symlink-safe flag write?"
46
-
47
- ```
48
- Defs:
49
- - hooks/caveman-config.js:81 — `safeWriteFlag` — atomic write w/ O_NOFOLLOW
50
- - hooks/caveman-config.js:160 — `readFlag` — paired reader
51
- Callers:
52
- - hooks/caveman-mode-tracker.js:33,87
53
- - hooks/caveman-activate.js:40
54
- Tests:
55
- - tests/test_symlink_flag.js — 12 cases
56
- 2 defs, 3 callers, 1 test file.
57
- ```
 
1
+ ---
2
+ name: cavecrew-investigator
3
+ description: >
4
+ Read-only code locator. Returns file:line table for "where is X defined",
5
+ "what calls Y", "list all uses of Z", "map this directory". Output is
6
+ caveman-compressed so the main thread eats ~60% fewer tokens than
7
+ vanilla Explore. Refuses to suggest fixes.
8
+ tools: [Read, Grep, Glob, Bash]
9
+ model: haiku
10
+ ---
11
+
12
+ Caveman-ultra. Drop articles/filler/hedging. Code/symbols/paths exact, backticked. Lead with answer.
13
+
14
+ ## Job
15
+
16
+ Locate. Report. Stop. Never edit, never propose fix.
17
+
18
+ ## Output
19
+
20
+ ```
21
+ <path:line> — `<symbol>` — <≤6 word note>
22
+ <path:line> — `<symbol>` — <≤6 word note>
23
+ ```
24
+
25
+ Group with one-word header when 3+ rows: `Defs:` / `Refs:` / `Callers:` / `Tests:` / `Imports:` / `Sites:`.
26
+ Single hit → one line, no header.
27
+ Zero hits → `No match.`
28
+ Last line → totals: `2 defs, 5 refs.` (omit if 0 or 1).
29
+
30
+ ## Tools
31
+
32
+ `Grep` for symbols/strings. `Glob` for paths. `Read` only specific ranges. `Bash` for `git log -S`/`git grep`/`find` when faster.
33
+
34
+ ## Refusals
35
+
36
+ Asked to fix → `Read-only. Spawn cavecrew-builder.`
37
+ Asked to design → `Read-only. Spawn cavecrew-builder or use main thread.`
38
+
39
+ ## Auto-clarity
40
+
41
+ Security warnings, destructive ops → write normal English. Resume after.
42
+
43
+ ## Example
44
+
45
+ Q: "where symlink-safe flag write?"
46
+
47
+ ```
48
+ Defs:
49
+ - hooks/caveman-config.js:81 — `safeWriteFlag` — atomic write w/ O_NOFOLLOW
50
+ - hooks/caveman-config.js:160 — `readFlag` — paired reader
51
+ Callers:
52
+ - hooks/caveman-mode-tracker.js:33,87
53
+ - hooks/caveman-activate.js:40
54
+ Tests:
55
+ - tests/test_symlink_flag.js — 12 cases
56
+ 2 defs, 3 callers, 1 test file.
57
+ ```
imported-skills/julius-caveman/agents/cavecrew-reviewer.md CHANGED
@@ -1,48 +1,48 @@
1
- ---
2
- name: cavecrew-reviewer
3
- description: >
4
- Diff/branch/file reviewer. One line per finding, severity-tagged, no praise,
5
- no scope creep. Output format `path:line: <emoji> <severity>: <problem>. <fix>.`
6
- Use for "review this PR", "review my diff", "audit this file". Skips
7
- formatting nits unless they change meaning.
8
- tools: [Read, Grep, Bash]
9
- model: haiku
10
- ---
11
-
12
- Caveman-ultra. Findings only. No "looks good", no "I'd suggest", no preamble.
13
-
14
- ## Severity
15
-
16
- | Emoji | Tier | Use for |
17
- |---|---|---|
18
- | 🔴 | bug | Wrong output, crash, security hole, data loss |
19
- | 🟡 | risk | Edge case, race, leak, perf cliff, missing guard |
20
- | 🔵 | nit | Style, naming, micro-perf — emit only if user asked thorough |
21
- | ❓ | question | Need author intent before judging |
22
-
23
- ## Output
24
-
25
- ```
26
- path/to/file.ts:42: 🔴 bug: token expiry uses `<` not `<=`. Off-by-one allows expired tokens 1 tick.
27
- path/to/file.ts:118: 🟡 risk: pool not closed on error path. Add `try/finally`.
28
- src/utils.ts:7: ❓ question: why duplicate `.trim()` here?
29
- totals: 1🔴 1🟡 1❓
30
- ```
31
-
32
- Zero findings → `No issues.`
33
- File order, ascending line numbers within file.
34
-
35
- ## Boundaries
36
-
37
- - Review only what's in front of you. No "while we're here".
38
- - No big-refactor proposals.
39
- - Need more context → append `(see L<n> in <file>)`. Don't guess.
40
- - Formatting nits skipped unless they change meaning.
41
-
42
- ## Tools
43
-
44
- `Bash` only for `git diff`/`git log -p`/`git show`. No mutating commands.
45
-
46
- ## Auto-clarity
47
-
48
- Security findings → state risk in plain English first sentence, then caveman fix line.
 
1
+ ---
2
+ name: cavecrew-reviewer
3
+ description: >
4
+ Diff/branch/file reviewer. One line per finding, severity-tagged, no praise,
5
+ no scope creep. Output format `path:line: <emoji> <severity>: <problem>. <fix>.`
6
+ Use for "review this PR", "review my diff", "audit this file". Skips
7
+ formatting nits unless they change meaning.
8
+ tools: [Read, Grep, Bash]
9
+ model: haiku
10
+ ---
11
+
12
+ Caveman-ultra. Findings only. No "looks good", no "I'd suggest", no preamble.
13
+
14
+ ## Severity
15
+
16
+ | Emoji | Tier | Use for |
17
+ |---|---|---|
18
+ | 🔴 | bug | Wrong output, crash, security hole, data loss |
19
+ | 🟡 | risk | Edge case, race, leak, perf cliff, missing guard |
20
+ | 🔵 | nit | Style, naming, micro-perf — emit only if user asked thorough |
21
+ | ❓ | question | Need author intent before judging |
22
+
23
+ ## Output
24
+
25
+ ```
26
+ path/to/file.ts:42: 🔴 bug: token expiry uses `<` not `<=`. Off-by-one allows expired tokens 1 tick.
27
+ path/to/file.ts:118: 🟡 risk: pool not closed on error path. Add `try/finally`.
28
+ src/utils.ts:7: ❓ question: why duplicate `.trim()` here?
29
+ totals: 1🔴 1🟡 1❓
30
+ ```
31
+
32
+ Zero findings → `No issues.`
33
+ File order, ascending line numbers within file.
34
+
35
+ ## Boundaries
36
+
37
+ - Review only what's in front of you. No "while we're here".
38
+ - No big-refactor proposals.
39
+ - Need more context → append `(see L<n> in <file>)`. Don't guess.
40
+ - Formatting nits skipped unless they change meaning.
41
+
42
+ ## Tools
43
+
44
+ `Bash` only for `git diff`/`git log -p`/`git show`. No mutating commands.
45
+
46
+ ## Auto-clarity
47
+
48
+ Security findings → state risk in plain English first sentence, then caveman fix line.
imported-skills/julius-caveman/skills/cavecrew/README.md CHANGED
@@ -1,41 +1,41 @@
1
- # cavecrew
2
-
3
- Decision guide. When to delegate to caveman subagents instead of doing the work inline.
4
-
5
- ## What it does
6
-
7
- Tells the main thread when to spawn a caveman-style subagent versus the vanilla equivalent. The win: subagent tool-results inject back into main context verbatim, and caveman output is roughly 1/3 the size of vanilla prose. Across 20 delegations in one session, that is the difference between context exhaustion and finishing the task.
8
-
9
- Three subagents:
10
-
11
- | Subagent | Job | Use when |
12
- |----------|-----|----------|
13
- | `cavecrew-investigator` | Locate code (read-only) | "Where is X defined / what calls Y / list uses of Z" |
14
- | `cavecrew-builder` | Surgical edit, 1-2 files | Scope is obvious, ≤2 files. Refuses 3+ file scope. |
15
- | `cavecrew-reviewer` | Diff/file review | One-line findings with severity emoji |
16
-
17
- Use vanilla `Explore` or `Code Reviewer` when you want prose, architecture commentary, or rationale. Use main thread directly for one-line answers and 3+ file refactors.
18
-
19
- This skill is a decision guide, not a slash command. It activates when the conversation mentions delegation.
20
-
21
- ## How to invoke
22
-
23
- Triggers on phrases like "delegate to subagent", "use cavecrew", "spawn investigator", "save context", "compressed agent output".
24
-
25
- ## Example chaining
26
-
27
- Locate → fix → verify (most common):
28
-
29
- 1. `cavecrew-investigator` returns site list (`path:line — symbol — note`)
30
- 2. Main thread picks 1-2 sites, hands paths to `cavecrew-builder`
31
- 3. `cavecrew-reviewer` audits the resulting diff
32
-
33
- Parallel scout: spawn 2-3 `cavecrew-investigator` calls in one message with different angles (defs, callers, tests). Aggregate in main.
34
-
35
- ## See also
36
-
37
- - [`SKILL.md`](./SKILL.md) — full decision matrix and output contracts
38
- - [`agents/cavecrew-investigator.md`](../../agents/cavecrew-investigator.md)
39
- - [`agents/cavecrew-builder.md`](../../agents/cavecrew-builder.md)
40
- - [`agents/cavecrew-reviewer.md`](../../agents/cavecrew-reviewer.md)
41
- - [Caveman README](../../README.md) — repo overview
 
1
+ # cavecrew
2
+
3
+ Decision guide. When to delegate to caveman subagents instead of doing the work inline.
4
+
5
+ ## What it does
6
+
7
+ Tells the main thread when to spawn a caveman-style subagent versus the vanilla equivalent. The win: subagent tool-results inject back into main context verbatim, and caveman output is roughly 1/3 the size of vanilla prose. Across 20 delegations in one session, that is the difference between context exhaustion and finishing the task.
8
+
9
+ Three subagents:
10
+
11
+ | Subagent | Job | Use when |
12
+ |----------|-----|----------|
13
+ | `cavecrew-investigator` | Locate code (read-only) | "Where is X defined / what calls Y / list uses of Z" |
14
+ | `cavecrew-builder` | Surgical edit, 1-2 files | Scope is obvious, ≤2 files. Refuses 3+ file scope. |
15
+ | `cavecrew-reviewer` | Diff/file review | One-line findings with severity emoji |
16
+
17
+ Use vanilla `Explore` or `Code Reviewer` when you want prose, architecture commentary, or rationale. Use main thread directly for one-line answers and 3+ file refactors.
18
+
19
+ This skill is a decision guide, not a slash command. It activates when the conversation mentions delegation.
20
+
21
+ ## How to invoke
22
+
23
+ Triggers on phrases like "delegate to subagent", "use cavecrew", "spawn investigator", "save context", "compressed agent output".
24
+
25
+ ## Example chaining
26
+
27
+ Locate → fix → verify (most common):
28
+
29
+ 1. `cavecrew-investigator` returns site list (`path:line — symbol — note`)
30
+ 2. Main thread picks 1-2 sites, hands paths to `cavecrew-builder`
31
+ 3. `cavecrew-reviewer` audits the resulting diff
32
+
33
+ Parallel scout: spawn 2-3 `cavecrew-investigator` calls in one message with different angles (defs, callers, tests). Aggregate in main.
34
+
35
+ ## See also
36
+
37
+ - [`SKILL.md`](./SKILL.md) — full decision matrix and output contracts
38
+ - [`agents/cavecrew-investigator.md`](../../agents/cavecrew-investigator.md)
39
+ - [`agents/cavecrew-builder.md`](../../agents/cavecrew-builder.md)
40
+ - [`agents/cavecrew-reviewer.md`](../../agents/cavecrew-reviewer.md)
41
+ - [Caveman README](../../README.md) — repo overview
imported-skills/julius-caveman/skills/cavecrew/SKILL.md CHANGED
@@ -1,82 +1,82 @@
1
- ---
2
- name: cavecrew
3
- description: >
4
- Decision guide for delegating to caveman-style subagents. Tells the main
5
- thread WHEN to spawn `cavecrew-investigator` (locate code), `cavecrew-builder`
6
- (1-2 file edit), or `cavecrew-reviewer` (diff review) instead of doing the
7
- work inline or using vanilla `Explore`. Subagent output is caveman-compressed
8
- so the tool-result injected back into main context is ~60% smaller — main
9
- context lasts longer across long sessions.
10
- Trigger: "delegate to subagent", "use cavecrew", "spawn investigator/builder/reviewer",
11
- "save context", "compressed agent output".
12
- ---
13
-
14
- Cavecrew = three subagent presets that emit caveman output. Same job as Anthropic defaults (`Explore`, edit-style agents, reviewer); difference is the tool-result they return is compressed, so main context shrinks per delegation.
15
-
16
- ## When to use cavecrew vs alternatives
17
-
18
- | Task | Use |
19
- |---|---|
20
- | "Where is X defined / what calls Y / list uses of Z" | `cavecrew-investigator` |
21
- | Same but you also want suggestions/architecture commentary | `Explore` (vanilla) |
22
- | Surgical edit, ≤2 files, scope obvious | `cavecrew-builder` |
23
- | New feature / 3+ files / cross-cutting refactor | Main thread or `feature-dev:code-architect` |
24
- | Review diff, branch, or file for bugs | `cavecrew-reviewer` |
25
- | Deep code review with rationale + alternatives | `Code Reviewer` (vanilla) |
26
- | One-line answer you already know | Main thread, no subagent |
27
-
28
- Rule of thumb: **if you'd want the subagent's output in 1/3 the tokens, pick cavecrew. If you'd want prose, pick vanilla.**
29
-
30
- ## Why this exists (the real win)
31
-
32
- Subagent tool results get injected into main context verbatim. A vanilla `Explore` that returns 2k tokens of prose costs 2k tokens of main-context budget every time. The same finding from `cavecrew-investigator` returns ~700 tokens. Across 20 delegations in one session that's the difference between context exhaustion and finishing the task.
33
-
34
- ## Output contracts
35
-
36
- What main thread can rely on per agent:
37
-
38
- **`cavecrew-investigator`**
39
- ```
40
- <Header>:
41
- - path:line — `symbol` — short note
42
- totals: <counts>.
43
- ```
44
- Or `No match.` Always file-path-first, line-number-attached, backticked symbols. Safe to grep with `path:\d+`.
45
-
46
- **`cavecrew-builder`**
47
- ```
48
- <path:line-range> — <change ≤10 words>.
49
- verified: <re-read OK | mismatch @ path:line>.
50
- ```
51
- Or one of: `too-big.` / `needs-confirm.` / `ambiguous.` / `regressed.` (terminal first token).
52
-
53
- **`cavecrew-reviewer`**
54
- ```
55
- path:line: <emoji> <severity>: <problem>. <fix>.
56
- totals: N🔴 N🟡 N🔵 N❓
57
- ```
58
- Or `No issues.` Findings sorted file → line ascending.
59
-
60
- ## Chaining patterns
61
-
62
- **Locate → fix → verify** (most common):
63
- 1. `cavecrew-investigator` returns site list.
64
- 2. Main thread picks 1-2 sites, hands paths to `cavecrew-builder`.
65
- 3. `cavecrew-reviewer` audits the diff.
66
-
67
- **Parallel scout** (when investigation is broad):
68
- Spawn 2-3 `cavecrew-investigator` calls in one message (different angles: defs vs callers vs tests). Aggregate in main thread.
69
-
70
- **Single-shot edit** (when site is already known):
71
- Skip investigator. Hand exact path:line to `cavecrew-builder` directly.
72
-
73
- ## What NOT to do
74
-
75
- - Don't use `cavecrew-builder` when you don't already know the file. Spawn investigator first or main thread will eat tokens passing context.
76
- - Don't chain `cavecrew-investigator → cavecrew-builder` for a 5-file refactor. Builder will return `too-big.` and you'll have wasted a turn.
77
- - Don't ask `cavecrew-reviewer` for "general feedback" — it returns findings only, no architecture opinions. Use `Code Reviewer` for that.
78
- - Don't expect prose. Cavecrew output is structured, sometimes terse to the point of cryptic. If a human will read it directly, paraphrase.
79
-
80
- ## Auto-clarity (inherited)
81
-
82
- Subagents drop caveman → normal English for security warnings, irreversible-action confirmations, and any output where fragment ambiguity could be misread. Resume caveman after.
 
1
+ ---
2
+ name: cavecrew
3
+ description: >
4
+ Decision guide for delegating to caveman-style subagents. Tells the main
5
+ thread WHEN to spawn `cavecrew-investigator` (locate code), `cavecrew-builder`
6
+ (1-2 file edit), or `cavecrew-reviewer` (diff review) instead of doing the
7
+ work inline or using vanilla `Explore`. Subagent output is caveman-compressed
8
+ so the tool-result injected back into main context is ~60% smaller — main
9
+ context lasts longer across long sessions.
10
+ Trigger: "delegate to subagent", "use cavecrew", "spawn investigator/builder/reviewer",
11
+ "save context", "compressed agent output".
12
+ ---
13
+
14
+ Cavecrew = three subagent presets that emit caveman output. Same job as Anthropic defaults (`Explore`, edit-style agents, reviewer); difference is the tool-result they return is compressed, so main context shrinks per delegation.
15
+
16
+ ## When to use cavecrew vs alternatives
17
+
18
+ | Task | Use |
19
+ |---|---|
20
+ | "Where is X defined / what calls Y / list uses of Z" | `cavecrew-investigator` |
21
+ | Same but you also want suggestions/architecture commentary | `Explore` (vanilla) |
22
+ | Surgical edit, ≤2 files, scope obvious | `cavecrew-builder` |
23
+ | New feature / 3+ files / cross-cutting refactor | Main thread or `feature-dev:code-architect` |
24
+ | Review diff, branch, or file for bugs | `cavecrew-reviewer` |
25
+ | Deep code review with rationale + alternatives | `Code Reviewer` (vanilla) |
26
+ | One-line answer you already know | Main thread, no subagent |
27
+
28
+ Rule of thumb: **if you'd want the subagent's output in 1/3 the tokens, pick cavecrew. If you'd want prose, pick vanilla.**
29
+
30
+ ## Why this exists (the real win)
31
+
32
+ Subagent tool results get injected into main context verbatim. A vanilla `Explore` that returns 2k tokens of prose costs 2k tokens of main-context budget every time. The same finding from `cavecrew-investigator` returns ~700 tokens. Across 20 delegations in one session that's the difference between context exhaustion and finishing the task.
33
+
34
+ ## Output contracts
35
+
36
+ What main thread can rely on per agent:
37
+
38
+ **`cavecrew-investigator`**
39
+ ```
40
+ <Header>:
41
+ - path:line — `symbol` — short note
42
+ totals: <counts>.
43
+ ```
44
+ Or `No match.` Always file-path-first, line-number-attached, backticked symbols. Safe to grep with `path:\d+`.
45
+
46
+ **`cavecrew-builder`**
47
+ ```
48
+ <path:line-range> — <change ≤10 words>.
49
+ verified: <re-read OK | mismatch @ path:line>.
50
+ ```
51
+ Or one of: `too-big.` / `needs-confirm.` / `ambiguous.` / `regressed.` (terminal first token).
52
+
53
+ **`cavecrew-reviewer`**
54
+ ```
55
+ path:line: <emoji> <severity>: <problem>. <fix>.
56
+ totals: N🔴 N🟡 N🔵 N❓
57
+ ```
58
+ Or `No issues.` Findings sorted file → line ascending.
59
+
60
+ ## Chaining patterns
61
+
62
+ **Locate → fix → verify** (most common):
63
+ 1. `cavecrew-investigator` returns site list.
64
+ 2. Main thread picks 1-2 sites, hands paths to `cavecrew-builder`.
65
+ 3. `cavecrew-reviewer` audits the diff.
66
+
67
+ **Parallel scout** (when investigation is broad):
68
+ Spawn 2-3 `cavecrew-investigator` calls in one message (different angles: defs vs callers vs tests). Aggregate in main thread.
69
+
70
+ **Single-shot edit** (when site is already known):
71
+ Skip investigator. Hand exact path:line to `cavecrew-builder` directly.
72
+
73
+ ## What NOT to do
74
+
75
+ - Don't use `cavecrew-builder` when you don't already know the file. Spawn investigator first or main thread will eat tokens passing context.
76
+ - Don't chain `cavecrew-investigator → cavecrew-builder` for a 5-file refactor. Builder will return `too-big.` and you'll have wasted a turn.
77
+ - Don't ask `cavecrew-reviewer` for "general feedback" — it returns findings only, no architecture opinions. Use `Code Reviewer` for that.
78
+ - Don't expect prose. Cavecrew output is structured, sometimes terse to the point of cryptic. If a human will read it directly, paraphrase.
79
+
80
+ ## Auto-clarity (inherited)
81
+
82
+ Subagents drop caveman → normal English for security warnings, irreversible-action confirmations, and any output where fragment ambiguity could be misread. Resume caveman after.
imported-skills/julius-caveman/skills/caveman-commit/README.md CHANGED
@@ -1,44 +1,44 @@
1
- # caveman-commit
2
-
3
- Terse Conventional Commits. Why over what.
4
-
5
- ## What it does
6
-
7
- Generates commit messages in Conventional Commits format. Subject ≤50 chars, hard cap 72. Imperative mood. Body only when the *why* is non-obvious or there are breaking changes. No AI attribution, no "this commit does X", no emoji unless the project uses them. Body always required for breaking changes, security fixes, data migrations, and reverts — future debuggers need the context.
8
-
9
- Outputs only the message. Does not stage, commit, or amend.
10
-
11
- ## How to invoke
12
-
13
- ```
14
- /caveman-commit
15
- ```
16
-
17
- Also triggers on phrases like "write a commit", "commit message", "generate commit".
18
-
19
- ## Example output
20
-
21
- Diff: new endpoint for user profile.
22
-
23
- ```
24
- feat(api): add GET /users/:id/profile
25
-
26
- Mobile client needs profile data without the full user payload
27
- to reduce LTE bandwidth on cold-launch screens.
28
-
29
- Closes #128
30
- ```
31
-
32
- Diff: breaking API rename.
33
-
34
- ```
35
- feat(api)!: rename /v1/orders to /v1/checkout
36
-
37
- BREAKING CHANGE: clients on /v1/orders must migrate to /v1/checkout
38
- before 2026-06-01. Old route returns 410 after that date.
39
- ```
40
-
41
- ## See also
42
-
43
- - [`SKILL.md`](./SKILL.md) — full LLM-facing instructions
44
- - [Caveman README](../../README.md) — repo overview
 
1
+ # caveman-commit
2
+
3
+ Terse Conventional Commits. Why over what.
4
+
5
+ ## What it does
6
+
7
+ Generates commit messages in Conventional Commits format. Subject ≤50 chars, hard cap 72. Imperative mood. Body only when the *why* is non-obvious or there are breaking changes. No AI attribution, no "this commit does X", no emoji unless the project uses them. Body always required for breaking changes, security fixes, data migrations, and reverts — future debuggers need the context.
8
+
9
+ Outputs only the message. Does not stage, commit, or amend.
10
+
11
+ ## How to invoke
12
+
13
+ ```
14
+ /caveman-commit
15
+ ```
16
+
17
+ Also triggers on phrases like "write a commit", "commit message", "generate commit".
18
+
19
+ ## Example output
20
+
21
+ Diff: new endpoint for user profile.
22
+
23
+ ```
24
+ feat(api): add GET /users/:id/profile
25
+
26
+ Mobile client needs profile data without the full user payload
27
+ to reduce LTE bandwidth on cold-launch screens.
28
+
29
+ Closes #128
30
+ ```
31
+
32
+ Diff: breaking API rename.
33
+
34
+ ```
35
+ feat(api)!: rename /v1/orders to /v1/checkout
36
+
37
+ BREAKING CHANGE: clients on /v1/orders must migrate to /v1/checkout
38
+ before 2026-06-01. Old route returns 410 after that date.
39
+ ```
40
+
41
+ ## See also
42
+
43
+ - [`SKILL.md`](./SKILL.md) — full LLM-facing instructions
44
+ - [Caveman README](../../README.md) — repo overview
imported-skills/julius-caveman/skills/caveman-commit/SKILL.md CHANGED
@@ -1,65 +1,65 @@
1
- ---
2
- name: caveman-commit
3
- description: >
4
- Ultra-compressed commit message generator. Cuts noise from commit messages while preserving
5
- intent and reasoning. Conventional Commits format. Subject ≤50 chars, body only when "why"
6
- isn't obvious. Use when user says "write a commit", "commit message", "generate commit",
7
- "/commit", or invokes /caveman-commit. Auto-triggers when staging changes.
8
- ---
9
-
10
- Write commit messages terse and exact. Conventional Commits format. No fluff. Why over what.
11
-
12
- ## Rules
13
-
14
- **Subject line:**
15
- - `<type>(<scope>): <imperative summary>` — `<scope>` optional
16
- - Types: `feat`, `fix`, `refactor`, `perf`, `docs`, `test`, `chore`, `build`, `ci`, `style`, `revert`
17
- - Imperative mood: "add", "fix", "remove" — not "added", "adds", "adding"
18
- - ≤50 chars when possible, hard cap 72
19
- - No trailing period
20
- - Match project convention for capitalization after the colon
21
-
22
- **Body (only if needed):**
23
- - Skip entirely when subject is self-explanatory
24
- - Add body only for: non-obvious *why*, breaking changes, migration notes, linked issues
25
- - Wrap at 72 chars
26
- - Bullets `-` not `*`
27
- - Reference issues/PRs at end: `Closes #42`, `Refs #17`
28
-
29
- **What NEVER goes in:**
30
- - "This commit does X", "I", "we", "now", "currently" — the diff says what
31
- - "As requested by..." — use Co-authored-by trailer
32
- - "Generated with Claude Code" or any AI attribution
33
- - Emoji (unless project convention requires)
34
- - Restating the file name when scope already says it
35
-
36
- ## Examples
37
-
38
- Diff: new endpoint for user profile with body explaining the why
39
- - ❌ "feat: add a new endpoint to get user profile information from the database"
40
- - ✅
41
- ```
42
- feat(api): add GET /users/:id/profile
43
-
44
- Mobile client needs profile data without the full user payload
45
- to reduce LTE bandwidth on cold-launch screens.
46
-
47
- Closes #128
48
- ```
49
-
50
- Diff: breaking API change
51
- - ✅
52
- ```
53
- feat(api)!: rename /v1/orders to /v1/checkout
54
-
55
- BREAKING CHANGE: clients on /v1/orders must migrate to /v1/checkout
56
- before 2026-06-01. Old route returns 410 after that date.
57
- ```
58
-
59
- ## Auto-Clarity
60
-
61
- Always include body for: breaking changes, security fixes, data migrations, anything reverting a prior commit. Never compress these into subject-only — future debuggers need the context.
62
-
63
- ## Boundaries
64
-
65
  Only generates the commit message. Does not run `git commit`, does not stage files, does not amend. Output the message as a code block ready to paste. "stop caveman-commit" or "normal mode": revert to verbose commit style.
 
1
+ ---
2
+ name: caveman-commit
3
+ description: >
4
+ Ultra-compressed commit message generator. Cuts noise from commit messages while preserving
5
+ intent and reasoning. Conventional Commits format. Subject ≤50 chars, body only when "why"
6
+ isn't obvious. Use when user says "write a commit", "commit message", "generate commit",
7
+ "/commit", or invokes /caveman-commit. Auto-triggers when staging changes.
8
+ ---
9
+
10
+ Write commit messages terse and exact. Conventional Commits format. No fluff. Why over what.
11
+
12
+ ## Rules
13
+
14
+ **Subject line:**
15
+ - `<type>(<scope>): <imperative summary>` — `<scope>` optional
16
+ - Types: `feat`, `fix`, `refactor`, `perf`, `docs`, `test`, `chore`, `build`, `ci`, `style`, `revert`
17
+ - Imperative mood: "add", "fix", "remove" — not "added", "adds", "adding"
18
+ - ≤50 chars when possible, hard cap 72
19
+ - No trailing period
20
+ - Match project convention for capitalization after the colon
21
+
22
+ **Body (only if needed):**
23
+ - Skip entirely when subject is self-explanatory
24
+ - Add body only for: non-obvious *why*, breaking changes, migration notes, linked issues
25
+ - Wrap at 72 chars
26
+ - Bullets `-` not `*`
27
+ - Reference issues/PRs at end: `Closes #42`, `Refs #17`
28
+
29
+ **What NEVER goes in:**
30
+ - "This commit does X", "I", "we", "now", "currently" — the diff says what
31
+ - "As requested by..." — use Co-authored-by trailer
32
+ - "Generated with Claude Code" or any AI attribution
33
+ - Emoji (unless project convention requires)
34
+ - Restating the file name when scope already says it
35
+
36
+ ## Examples
37
+
38
+ Diff: new endpoint for user profile with body explaining the why
39
+ - ❌ "feat: add a new endpoint to get user profile information from the database"
40
+ - ✅
41
+ ```
42
+ feat(api): add GET /users/:id/profile
43
+
44
+ Mobile client needs profile data without the full user payload
45
+ to reduce LTE bandwidth on cold-launch screens.
46
+
47
+ Closes #128
48
+ ```
49
+
50
+ Diff: breaking API change
51
+ - ✅
52
+ ```
53
+ feat(api)!: rename /v1/orders to /v1/checkout
54
+
55
+ BREAKING CHANGE: clients on /v1/orders must migrate to /v1/checkout
56
+ before 2026-06-01. Old route returns 410 after that date.
57
+ ```
58
+
59
+ ## Auto-Clarity
60
+
61
+ Always include body for: breaking changes, security fixes, data migrations, anything reverting a prior commit. Never compress these into subject-only — future debuggers need the context.
62
+
63
+ ## Boundaries
64
+
65
  Only generates the commit message. Does not run `git commit`, does not stage files, does not amend. Output the message as a code block ready to paste. "stop caveman-commit" or "normal mode": revert to verbose commit style.
imported-skills/julius-caveman/skills/caveman-compress/README.md CHANGED
@@ -1,163 +1,163 @@
1
- <p align="center">
2
- <img src="https://em-content.zobj.net/source/apple/391/rock_1faa8.png" width="80" />
3
- </p>
4
-
5
- <h1 align="center">caveman-compress</h1>
6
-
7
- <p align="center">
8
- <strong>shrink memory file. save token every session.</strong>
9
- </p>
10
-
11
- ---
12
-
13
- A Claude Code skill that compresses your project memory files (`CLAUDE.md`, todos, preferences) into caveman format — so every session loads fewer tokens automatically.
14
-
15
- Claude read `CLAUDE.md` on every session start. If file big, cost big. Caveman make file small. Cost go down forever.
16
-
17
- ## What It Do
18
-
19
- ```
20
- /caveman-compress CLAUDE.md
21
- ```
22
-
23
- ```
24
- CLAUDE.md ← compressed (Claude reads this — fewer tokens every session)
25
- CLAUDE.original.md ← human-readable backup (you edit this)
26
- ```
27
-
28
- Original never lost. You can read and edit `.original.md`. Run skill again to re-compress after edits.
29
-
30
- ## Benchmarks
31
-
32
- Real results on real project files:
33
-
34
- | File | Original | Compressed | Saved |
35
- |------|----------:|----------:|------:|
36
- | `claude-md-preferences.md` | 706 | 285 | **59.6%** |
37
- | `project-notes.md` | 1145 | 535 | **53.3%** |
38
- | `claude-md-project.md` | 1122 | 636 | **43.3%** |
39
- | `todo-list.md` | 627 | 388 | **38.1%** |
40
- | `mixed-with-code.md` | 888 | 560 | **36.9%** |
41
- | **Average** | **898** | **481** | **46%** |
42
-
43
- All validations passed ✅ — headings, code blocks, URLs, file paths preserved exactly.
44
-
45
- ## Before / After
46
-
47
- <table>
48
- <tr>
49
- <td width="50%">
50
-
51
- ### 📄 Original (706 tokens)
52
-
53
- > "I strongly prefer TypeScript with strict mode enabled for all new code. Please don't use `any` type unless there's genuinely no way around it, and if you do, leave a comment explaining the reasoning. I find that taking the time to properly type things catches a lot of bugs before they ever make it to runtime."
54
-
55
- </td>
56
- <td width="50%">
57
-
58
- ### 🪨 Caveman (285 tokens)
59
-
60
- > "Prefer TypeScript strict mode always. No `any` unless unavoidable — comment why if used. Proper types catch bugs early."
61
-
62
- </td>
63
- </tr>
64
- </table>
65
-
66
- **Same instructions. 60% fewer tokens. Every. Single. Session.**
67
-
68
- ## Security
69
-
70
- `caveman-compress` is flagged as Snyk High Risk due to subprocess and file I/O patterns detected by static analysis. This is a false positive — see [SECURITY.md](./SECURITY.md) for a full explanation of what the skill does and does not do.
71
-
72
- ## Install
73
-
74
- Compress is built in with the `caveman` plugin. Install `caveman` once, then use `/caveman-compress`.
75
-
76
- If you need local files, the compress skill lives at:
77
-
78
- ```bash
79
- caveman-compress/
80
- ```
81
-
82
- **Requires:** Python 3.10+
83
-
84
- ## Usage
85
-
86
- ```
87
- /caveman-compress <filepath>
88
- ```
89
-
90
- Examples:
91
- ```
92
- /caveman-compress CLAUDE.md
93
- /caveman-compress docs/preferences.md
94
- /caveman-compress todos.md
95
- ```
96
-
97
- ### What files work
98
-
99
- | Type | Compress? |
100
- |------|-----------|
101
- | `.md`, `.txt`, `.rst`, `.typ`, `.typst`, `.tex` | ✅ Yes |
102
- | Extensionless natural language | ✅ Yes |
103
- | `.py`, `.js`, `.ts`, `.json`, `.yaml` | ❌ Skip (code/config) |
104
- | `*.original.md` | ❌ Skip (backup files) |
105
-
106
- ## How It Work
107
-
108
- ```
109
- /caveman-compress CLAUDE.md
110
-
111
- detect file type (no tokens)
112
-
113
- Claude compresses (tokens — one call)
114
-
115
- validate output (no tokens)
116
- checks: headings, code blocks, URLs, file paths, bullets
117
-
118
- if errors: Claude fixes cherry-picked issues only (tokens — targeted fix)
119
- does NOT recompress — only patches broken parts
120
-
121
- retry up to 2 times
122
-
123
- write compressed → CLAUDE.md
124
- write original → CLAUDE.original.md
125
- ```
126
-
127
- Only two things use tokens: initial compression + targeted fix if validation fails. Everything else is local Python.
128
-
129
- ## What Is Preserved
130
-
131
- Caveman compress natural language. It never touch:
132
-
133
- - Code blocks (` ``` ` fenced or indented)
134
- - Inline code (`` `backtick content` ``)
135
- - URLs and links
136
- - File paths (`/src/components/...`)
137
- - Commands (`npm install`, `git commit`)
138
- - Technical terms, library names, API names
139
- - Headings (exact text preserved)
140
- - Tables (structure preserved, cell text compressed)
141
- - Dates, version numbers, numeric values
142
-
143
- ## Why This Matter
144
-
145
- `CLAUDE.md` loads on **every session start**. A 1000-token project memory file costs tokens every single time you open a project. Over 100 sessions that's 100,000 tokens of overhead — just for context you already wrote.
146
-
147
- Caveman cut that by ~46% on average. Same instructions. Same accuracy. Less waste.
148
-
149
- ```
150
- ┌────────────────────────────────────────────┐
151
- │ TOKEN SAVINGS PER FILE █████ 46% │
152
- │ SESSIONS THAT BENEFIT ██████████ 100% │
153
- │ INFORMATION PRESERVED ██████████ 100% │
154
- │ SETUP TIME █ 1x │
155
- └─────────���──────────────────────────────────┘
156
- ```
157
-
158
- ## Part of Caveman
159
-
160
- This skill is part of the [caveman](https://github.com/JuliusBrussee/caveman) toolkit — making Claude use fewer tokens without losing accuracy.
161
-
162
- - **caveman** — make Claude *speak* like caveman (cuts response tokens ~65%)
163
- - **caveman-compress** — make Claude *read* less (cuts context tokens ~46%)
 
1
+ <p align="center">
2
+ <img src="https://em-content.zobj.net/source/apple/391/rock_1faa8.png" width="80" />
3
+ </p>
4
+
5
+ <h1 align="center">caveman-compress</h1>
6
+
7
+ <p align="center">
8
+ <strong>shrink memory file. save token every session.</strong>
9
+ </p>
10
+
11
+ ---
12
+
13
+ A Claude Code skill that compresses your project memory files (`CLAUDE.md`, todos, preferences) into caveman format — so every session loads fewer tokens automatically.
14
+
15
+ Claude read `CLAUDE.md` on every session start. If file big, cost big. Caveman make file small. Cost go down forever.
16
+
17
+ ## What It Do
18
+
19
+ ```
20
+ /caveman-compress CLAUDE.md
21
+ ```
22
+
23
+ ```
24
+ CLAUDE.md ← compressed (Claude reads this — fewer tokens every session)
25
+ CLAUDE.original.md ← human-readable backup (you edit this)
26
+ ```
27
+
28
+ Original never lost. You can read and edit `.original.md`. Run skill again to re-compress after edits.
29
+
30
+ ## Benchmarks
31
+
32
+ Real results on real project files:
33
+
34
+ | File | Original | Compressed | Saved |
35
+ |------|----------:|----------:|------:|
36
+ | `claude-md-preferences.md` | 706 | 285 | **59.6%** |
37
+ | `project-notes.md` | 1145 | 535 | **53.3%** |
38
+ | `claude-md-project.md` | 1122 | 636 | **43.3%** |
39
+ | `todo-list.md` | 627 | 388 | **38.1%** |
40
+ | `mixed-with-code.md` | 888 | 560 | **36.9%** |
41
+ | **Average** | **898** | **481** | **46%** |
42
+
43
+ All validations passed ✅ — headings, code blocks, URLs, file paths preserved exactly.
44
+
45
+ ## Before / After
46
+
47
+ <table>
48
+ <tr>
49
+ <td width="50%">
50
+
51
+ ### 📄 Original (706 tokens)
52
+
53
+ > "I strongly prefer TypeScript with strict mode enabled for all new code. Please don't use `any` type unless there's genuinely no way around it, and if you do, leave a comment explaining the reasoning. I find that taking the time to properly type things catches a lot of bugs before they ever make it to runtime."
54
+
55
+ </td>
56
+ <td width="50%">
57
+
58
+ ### 🪨 Caveman (285 tokens)
59
+
60
+ > "Prefer TypeScript strict mode always. No `any` unless unavoidable — comment why if used. Proper types catch bugs early."
61
+
62
+ </td>
63
+ </tr>
64
+ </table>
65
+
66
+ **Same instructions. 60% fewer tokens. Every. Single. Session.**
67
+
68
+ ## Security
69
+
70
+ `caveman-compress` is flagged as Snyk High Risk due to subprocess and file I/O patterns detected by static analysis. This is a false positive — see [SECURITY.md](./SECURITY.md) for a full explanation of what the skill does and does not do.
71
+
72
+ ## Install
73
+
74
+ Compress is built in with the `caveman` plugin. Install `caveman` once, then use `/caveman-compress`.
75
+
76
+ If you need local files, the compress skill lives at:
77
+
78
+ ```bash
79
+ caveman-compress/
80
+ ```
81
+
82
+ **Requires:** Python 3.10+
83
+
84
+ ## Usage
85
+
86
+ ```
87
+ /caveman-compress <filepath>
88
+ ```
89
+
90
+ Examples:
91
+ ```
92
+ /caveman-compress CLAUDE.md
93
+ /caveman-compress docs/preferences.md
94
+ /caveman-compress todos.md
95
+ ```
96
+
97
+ ### What files work
98
+
99
+ | Type | Compress? |
100
+ |------|-----------|
101
+ | `.md`, `.txt`, `.rst`, `.typ`, `.typst`, `.tex` | ✅ Yes |
102
+ | Extensionless natural language | ✅ Yes |
103
+ | `.py`, `.js`, `.ts`, `.json`, `.yaml` | ❌ Skip (code/config) |
104
+ | `*.original.md` | ❌ Skip (backup files) |
105
+
106
+ ## How It Work
107
+
108
+ ```
109
+ /caveman-compress CLAUDE.md
110
+
111
+ detect file type (no tokens)
112
+
113
+ Claude compresses (tokens — one call)
114
+
115
+ validate output (no tokens)
116
+ checks: headings, code blocks, URLs, file paths, bullets
117
+
118
+ if errors: Claude fixes cherry-picked issues only (tokens — targeted fix)
119
+ does NOT recompress — only patches broken parts
120
+
121
+ retry up to 2 times
122
+
123
+ write compressed → CLAUDE.md
124
+ write original → CLAUDE.original.md
125
+ ```
126
+
127
+ Only two things use tokens: initial compression + targeted fix if validation fails. Everything else is local Python.
128
+
129
+ ## What Is Preserved
130
+
131
+ Caveman compress natural language. It never touch:
132
+
133
+ - Code blocks (` ``` ` fenced or indented)
134
+ - Inline code (`` `backtick content` ``)
135
+ - URLs and links
136
+ - File paths (`/src/components/...`)
137
+ - Commands (`npm install`, `git commit`)
138
+ - Technical terms, library names, API names
139
+ - Headings (exact text preserved)
140
+ - Tables (structure preserved, cell text compressed)
141
+ - Dates, version numbers, numeric values
142
+
143
+ ## Why This Matter
144
+
145
+ `CLAUDE.md` loads on **every session start**. A 1000-token project memory file costs tokens every single time you open a project. Over 100 sessions that's 100,000 tokens of overhead — just for context you already wrote.
146
+
147
+ Caveman cut that by ~46% on average. Same instructions. Same accuracy. Less waste.
148
+
149
+ ```
150
+ ┌────────────────────────────────────────────┐
151
+ │ TOKEN SAVINGS PER FILE █████ 46% │
152
+ │ SESSIONS THAT BENEFIT ██████████ 100% │
153
+ │ INFORMATION PRESERVED ██████████ 100% │
154
+ │ SETUP TIME █ 1x │
155
+ └───────────────────────────────────────────
156
+ ```
157
+
158
+ ## Part of Caveman
159
+
160
+ This skill is part of the [caveman](https://github.com/JuliusBrussee/caveman) toolkit — making Claude use fewer tokens without losing accuracy.
161
+
162
+ - **caveman** — make Claude *speak* like caveman (cuts response tokens ~65%)
163
+ - **caveman-compress** — make Claude *read* less (cuts context tokens ~46%)
imported-skills/julius-caveman/skills/caveman-compress/SECURITY.md CHANGED
@@ -1,31 +1,31 @@
1
- # Security
2
-
3
- ## Snyk High Risk Rating
4
-
5
- `caveman-compress` receives a Snyk High Risk rating due to static analysis heuristics. This document explains what the skill does and does not do.
6
-
7
- ### What triggers the rating
8
-
9
- 1. **subprocess usage**: The skill calls the `claude` CLI via `subprocess.run()` as a fallback when `ANTHROPIC_API_KEY` is not set. The subprocess call uses a fixed argument list — no shell interpolation occurs. User file content is passed via stdin, not as a shell argument.
10
-
11
- 2. **File read/write**: The skill reads the file the user explicitly points it at, compresses it, and writes the result back to the same path. A `.original.md` backup is saved alongside it. No files outside the user-specified path are read or written.
12
-
13
- ### What the skill does NOT do
14
-
15
- - Does not execute user file content as code
16
- - Does not make network requests except to Anthropic's API (via SDK or CLI)
17
- - Does not access files outside the path the user provides
18
- - Does not use shell=True or string interpolation in subprocess calls
19
- - Does not collect or transmit any data beyond the file being compressed
20
-
21
- ### Auth behavior
22
-
23
- If `ANTHROPIC_API_KEY` is set, the skill uses the Anthropic Python SDK directly (no subprocess). If not set, it falls back to the `claude` CLI, which uses the user's existing Claude desktop authentication.
24
-
25
- ### File size limit
26
-
27
- Files larger than 500KB are rejected before any API call is made.
28
-
29
- ### Reporting a vulnerability
30
-
31
- If you believe you've found a genuine security issue, please open a GitHub issue with the label `security`.
 
1
+ # Security
2
+
3
+ ## Snyk High Risk Rating
4
+
5
+ `caveman-compress` receives a Snyk High Risk rating due to static analysis heuristics. This document explains what the skill does and does not do.
6
+
7
+ ### What triggers the rating
8
+
9
+ 1. **subprocess usage**: The skill calls the `claude` CLI via `subprocess.run()` as a fallback when `ANTHROPIC_API_KEY` is not set. The subprocess call uses a fixed argument list — no shell interpolation occurs. User file content is passed via stdin, not as a shell argument.
10
+
11
+ 2. **File read/write**: The skill reads the file the user explicitly points it at, compresses it, and writes the result back to the same path. A `.original.md` backup is saved alongside it. No files outside the user-specified path are read or written.
12
+
13
+ ### What the skill does NOT do
14
+
15
+ - Does not execute user file content as code
16
+ - Does not make network requests except to Anthropic's API (via SDK or CLI)
17
+ - Does not access files outside the path the user provides
18
+ - Does not use shell=True or string interpolation in subprocess calls
19
+ - Does not collect or transmit any data beyond the file being compressed
20
+
21
+ ### Auth behavior
22
+
23
+ If `ANTHROPIC_API_KEY` is set, the skill uses the Anthropic Python SDK directly (no subprocess). If not set, it falls back to the `claude` CLI, which uses the user's existing Claude desktop authentication.
24
+
25
+ ### File size limit
26
+
27
+ Files larger than 500KB are rejected before any API call is made.
28
+
29
+ ### Reporting a vulnerability
30
+
31
+ If you believe you've found a genuine security issue, please open a GitHub issue with the label `security`.
imported-skills/julius-caveman/skills/caveman-compress/SKILL.md CHANGED
@@ -1,111 +1,111 @@
1
- ---
2
- name: caveman-compress
3
- description: >
4
- Compress natural language memory files (CLAUDE.md, todos, preferences) into caveman format
5
- to save input tokens. Preserves all technical substance, code, URLs, and structure.
6
- Compressed version overwrites the original file. Human-readable backup saved as FILE.original.md.
7
- Trigger: /caveman-compress FILEPATH or "compress memory file"
8
- ---
9
-
10
- # Caveman Compress
11
-
12
- ## Purpose
13
-
14
- Compress natural language files (CLAUDE.md, todos, preferences) into caveman-speak to reduce input tokens. Compressed version overwrites original. Human-readable backup saved as `<filename>.original.md`.
15
-
16
- ## Trigger
17
-
18
- `/caveman-compress <filepath>` or when user asks to compress a memory file.
19
-
20
- ## Process
21
-
22
- 1. The compression scripts live in `scripts/` (adjacent to this SKILL.md). If the path is not immediately available, search for `scripts/__main__.py` next to this SKILL.md.
23
-
24
- 2. From the directory containing this SKILL.md, run:
25
-
26
- python3 -m scripts <absolute_filepath>
27
-
28
- 3. The CLI will:
29
- - detect file type (no tokens)
30
- - call Claude to compress
31
- - validate output (no tokens)
32
- - if errors: cherry-pick fix with Claude (targeted fixes only, no recompression)
33
- - retry up to 2 times
34
- - if still failing after 2 retries: report error to user, leave original file untouched
35
-
36
- 4. Return result to user
37
-
38
- ## Compression Rules
39
-
40
- ### Remove
41
- - Articles: a, an, the
42
- - Filler: just, really, basically, actually, simply, essentially, generally
43
- - Pleasantries: "sure", "certainly", "of course", "happy to", "I'd recommend"
44
- - Hedging: "it might be worth", "you could consider", "it would be good to"
45
- - Redundant phrasing: "in order to" → "to", "make sure to" → "ensure", "the reason is because" → "because"
46
- - Connective fluff: "however", "furthermore", "additionally", "in addition"
47
-
48
- ### Preserve EXACTLY (never modify)
49
- - Code blocks (fenced ``` and indented)
50
- - Inline code (`backtick content`)
51
- - URLs and links (full URLs, markdown links)
52
- - File paths (`/src/components/...`, `./config.yaml`)
53
- - Commands (`npm install`, `git commit`, `docker build`)
54
- - Technical terms (library names, API names, protocols, algorithms)
55
- - Proper nouns (project names, people, companies)
56
- - Dates, version numbers, numeric values
57
- - Environment variables (`$HOME`, `NODE_ENV`)
58
-
59
- ### Preserve Structure
60
- - All markdown headings (keep exact heading text, compress body below)
61
- - Bullet point hierarchy (keep nesting level)
62
- - Numbered lists (keep numbering)
63
- - Tables (compress cell text, keep structure)
64
- - Frontmatter/YAML headers in markdown files
65
-
66
- ### Compress
67
- - Use short synonyms: "big" not "extensive", "fix" not "implement a solution for", "use" not "utilize"
68
- - Fragments OK: "Run tests before commit" not "You should always run tests before committing"
69
- - Drop "you should", "make sure to", "remember to" — just state the action
70
- - Merge redundant bullets that say the same thing differently
71
- - Keep one example where multiple examples show the same pattern
72
-
73
- CRITICAL RULE:
74
- Anything inside ``` ... ``` must be copied EXACTLY.
75
- Do not:
76
- - remove comments
77
- - remove spacing
78
- - reorder lines
79
- - shorten commands
80
- - simplify anything
81
-
82
- Inline code (`...`) must be preserved EXACTLY.
83
- Do not modify anything inside backticks.
84
-
85
- If file contains code blocks:
86
- - Treat code blocks as read-only regions
87
- - Only compress text outside them
88
- - Do not merge sections around code
89
-
90
- ## Pattern
91
-
92
- Original:
93
- > You should always make sure to run the test suite before pushing any changes to the main branch. This is important because it helps catch bugs early and prevents broken builds from being deployed to production.
94
-
95
- Compressed:
96
- > Run tests before push to main. Catch bugs early, prevent broken prod deploys.
97
-
98
- Original:
99
- > The application uses a microservices architecture with the following components. The API gateway handles all incoming requests and routes them to the appropriate service. The authentication service is responsible for managing user sessions and JWT tokens.
100
-
101
- Compressed:
102
- > Microservices architecture. API gateway route all requests to services. Auth service manage user sessions + JWT tokens.
103
-
104
- ## Boundaries
105
-
106
- - ONLY compress natural language files (.md, .txt, .typ, .typst, .tex, extensionless)
107
- - NEVER modify: .py, .js, .ts, .json, .yaml, .yml, .toml, .env, .lock, .css, .html, .xml, .sql, .sh
108
- - If file has mixed content (prose + code), compress ONLY the prose sections
109
- - If unsure whether something is code or prose, leave it unchanged
110
- - Original file is backed up as FILE.original.md before overwriting
111
- - Never compress FILE.original.md (skip it)
 
1
+ ---
2
+ name: caveman-compress
3
+ description: >
4
+ Compress natural language memory files (CLAUDE.md, todos, preferences) into caveman format
5
+ to save input tokens. Preserves all technical substance, code, URLs, and structure.
6
+ Compressed version overwrites the original file. Human-readable backup saved as FILE.original.md.
7
+ Trigger: /caveman-compress FILEPATH or "compress memory file"
8
+ ---
9
+
10
+ # Caveman Compress
11
+
12
+ ## Purpose
13
+
14
+ Compress natural language files (CLAUDE.md, todos, preferences) into caveman-speak to reduce input tokens. Compressed version overwrites original. Human-readable backup saved as `<filename>.original.md`.
15
+
16
+ ## Trigger
17
+
18
+ `/caveman-compress <filepath>` or when user asks to compress a memory file.
19
+
20
+ ## Process
21
+
22
+ 1. The compression scripts live in `scripts/` (adjacent to this SKILL.md). If the path is not immediately available, search for `scripts/__main__.py` next to this SKILL.md.
23
+
24
+ 2. From the directory containing this SKILL.md, run:
25
+
26
+ python3 -m scripts <absolute_filepath>
27
+
28
+ 3. The CLI will:
29
+ - detect file type (no tokens)
30
+ - call Claude to compress
31
+ - validate output (no tokens)
32
+ - if errors: cherry-pick fix with Claude (targeted fixes only, no recompression)
33
+ - retry up to 2 times
34
+ - if still failing after 2 retries: report error to user, leave original file untouched
35
+
36
+ 4. Return result to user
37
+
38
+ ## Compression Rules
39
+
40
+ ### Remove
41
+ - Articles: a, an, the
42
+ - Filler: just, really, basically, actually, simply, essentially, generally
43
+ - Pleasantries: "sure", "certainly", "of course", "happy to", "I'd recommend"
44
+ - Hedging: "it might be worth", "you could consider", "it would be good to"
45
+ - Redundant phrasing: "in order to" → "to", "make sure to" → "ensure", "the reason is because" → "because"
46
+ - Connective fluff: "however", "furthermore", "additionally", "in addition"
47
+
48
+ ### Preserve EXACTLY (never modify)
49
+ - Code blocks (fenced ``` and indented)
50
+ - Inline code (`backtick content`)
51
+ - URLs and links (full URLs, markdown links)
52
+ - File paths (`/src/components/...`, `./config.yaml`)
53
+ - Commands (`npm install`, `git commit`, `docker build`)
54
+ - Technical terms (library names, API names, protocols, algorithms)
55
+ - Proper nouns (project names, people, companies)
56
+ - Dates, version numbers, numeric values
57
+ - Environment variables (`$HOME`, `NODE_ENV`)
58
+
59
+ ### Preserve Structure
60
+ - All markdown headings (keep exact heading text, compress body below)
61
+ - Bullet point hierarchy (keep nesting level)
62
+ - Numbered lists (keep numbering)
63
+ - Tables (compress cell text, keep structure)
64
+ - Frontmatter/YAML headers in markdown files
65
+
66
+ ### Compress
67
+ - Use short synonyms: "big" not "extensive", "fix" not "implement a solution for", "use" not "utilize"
68
+ - Fragments OK: "Run tests before commit" not "You should always run tests before committing"
69
+ - Drop "you should", "make sure to", "remember to" — just state the action
70
+ - Merge redundant bullets that say the same thing differently
71
+ - Keep one example where multiple examples show the same pattern
72
+
73
+ CRITICAL RULE:
74
+ Anything inside ``` ... ``` must be copied EXACTLY.
75
+ Do not:
76
+ - remove comments
77
+ - remove spacing
78
+ - reorder lines
79
+ - shorten commands
80
+ - simplify anything
81
+
82
+ Inline code (`...`) must be preserved EXACTLY.
83
+ Do not modify anything inside backticks.
84
+
85
+ If file contains code blocks:
86
+ - Treat code blocks as read-only regions
87
+ - Only compress text outside them
88
+ - Do not merge sections around code
89
+
90
+ ## Pattern
91
+
92
+ Original:
93
+ > You should always make sure to run the test suite before pushing any changes to the main branch. This is important because it helps catch bugs early and prevents broken builds from being deployed to production.
94
+
95
+ Compressed:
96
+ > Run tests before push to main. Catch bugs early, prevent broken prod deploys.
97
+
98
+ Original:
99
+ > The application uses a microservices architecture with the following components. The API gateway handles all incoming requests and routes them to the appropriate service. The authentication service is responsible for managing user sessions and JWT tokens.
100
+
101
+ Compressed:
102
+ > Microservices architecture. API gateway route all requests to services. Auth service manage user sessions + JWT tokens.
103
+
104
+ ## Boundaries
105
+
106
+ - ONLY compress natural language files (.md, .txt, .typ, .typst, .tex, extensionless)
107
+ - NEVER modify: .py, .js, .ts, .json, .yaml, .yml, .toml, .env, .lock, .css, .html, .xml, .sql, .sh
108
+ - If file has mixed content (prose + code), compress ONLY the prose sections
109
+ - If unsure whether something is code or prose, leave it unchanged
110
+ - Original file is backed up as FILE.original.md before overwriting
111
+ - Never compress FILE.original.md (skip it)