Sync ctx d2429c6
Browse filesGitHub commit: d2429c6d8f11d1d68cacc61083c1eba4a9e7717c
- .gitattributes +0 -2
- .github/workflows/publish.yml +10 -5
- .github/workflows/test.yml +81 -1
- CHANGELOG.md +19 -0
- README.md +1 -1
- docs/index.md +2 -2
- docs/knowledge-graph.md +1 -0
- graph/README.md +7 -2
- graph/sample-top60.html +0 -0
- graph/viz-ai-agents.html +0 -0
- graph/viz-overview.html +0 -0
- graph/viz-overview.png +0 -3
- graph/viz-python.html +0 -0
- graph/viz-security.html +0 -0
- graph/viz-security.png +0 -3
- pyproject.toml +1 -1
- scripts/ci_classifier.py +1 -0
- src/__init__.py +1 -1
- src/ctx/__init__.py +1 -1
- src/ctx_init.py +127 -6
- src/harness_install.py +44 -2
- src/tests/test_ci_classifier.py +23 -3
- src/tests/test_ctx_init.py +80 -0
- src/tests/test_harness_install.py +99 -0
- src/tests/test_validate_graph_artifacts.py +54 -0
- src/tests/test_wiki_visualize.py +50 -0
- src/validate_graph_artifacts.py +49 -0
- src/wiki_visualize.py +55 -14
.gitattributes
CHANGED
|
@@ -1,4 +1,2 @@
|
|
| 1 |
graph/wiki-graph.tar.gz filter=lfs diff=lfs merge=lfs -text
|
| 2 |
-
graph/viz-overview.png filter=lfs diff=lfs merge=lfs -text
|
| 3 |
-
graph/viz-security.png filter=lfs diff=lfs merge=lfs -text
|
| 4 |
graph/skills-sh-catalog.json.gz filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 1 |
graph/wiki-graph.tar.gz filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
| 2 |
graph/skills-sh-catalog.json.gz filter=lfs diff=lfs merge=lfs -text
|
.github/workflows/publish.yml
CHANGED
|
@@ -5,9 +5,9 @@ name: Publish to PyPI
|
|
| 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 via workflow_dispatch.
|
| 9 |
-
#
|
| 10 |
-
#
|
| 11 |
|
| 12 |
on:
|
| 13 |
push:
|
|
@@ -66,6 +66,11 @@ jobs:
|
|
| 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 == "testpypi":
|
| 70 |
print(f"manual TestPyPI publish allowed from {ref_type}:{ref_name}")
|
| 71 |
raise SystemExit(0)
|
|
@@ -417,7 +422,7 @@ jobs:
|
|
| 417 |
needs:
|
| 418 |
- build
|
| 419 |
- release-assets
|
| 420 |
-
if: ${{ always() && needs.build.result == 'success' && (github.event_name == 'workflow_dispatch'
|
| 421 |
runs-on: ubuntu-latest
|
| 422 |
permissions:
|
| 423 |
contents: read
|
|
@@ -433,7 +438,7 @@ jobs:
|
|
| 433 |
path: dist/
|
| 434 |
|
| 435 |
- name: Publish to PyPI
|
| 436 |
-
if: github.event_name == 'push'
|
| 437 |
uses: pypa/gh-action-pypi-publish@release/v1
|
| 438 |
|
| 439 |
- name: Publish to TestPyPI
|
|
|
|
| 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:
|
|
|
|
| 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)
|
|
|
|
| 422 |
needs:
|
| 423 |
- build
|
| 424 |
- release-assets
|
| 425 |
+
if: ${{ always() && needs.build.result == 'success' && (needs.release-assets.result == 'success' || (github.event_name == 'workflow_dispatch' && github.event.inputs.repository == 'testpypi')) }}
|
| 426 |
runs-on: ubuntu-latest
|
| 427 |
permissions:
|
| 428 |
contents: read
|
|
|
|
| 438 |
path: dist/
|
| 439 |
|
| 440 |
- name: Publish to PyPI
|
| 441 |
+
if: github.event_name == 'push'
|
| 442 |
uses: pypa/gh-action-pypi-publish@release/v1
|
| 443 |
|
| 444 |
- name: Publish to TestPyPI
|
.github/workflows/test.yml
CHANGED
|
@@ -299,10 +299,90 @@ jobs:
|
|
| 299 |
|
| 300 |
- name: Resolve graph LFS artifacts
|
| 301 |
shell: bash
|
|
|
|
|
|
|
| 302 |
run: |
|
| 303 |
set -euo pipefail
|
| 304 |
git lfs install --local
|
| 305 |
-
git lfs pull --include="graph/wiki-graph.tar.gz
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
|
| 307 |
- name: Validate shipped graph artifacts
|
| 308 |
run: |
|
|
|
|
| 299 |
|
| 300 |
- name: Resolve graph LFS artifacts
|
| 301 |
shell: bash
|
| 302 |
+
env:
|
| 303 |
+
GH_TOKEN: ${{ github.token }}
|
| 304 |
run: |
|
| 305 |
set -euo pipefail
|
| 306 |
git lfs install --local
|
| 307 |
+
if git lfs pull --include="graph/wiki-graph.tar.gz" --exclude=""; then
|
| 308 |
+
exit 0
|
| 309 |
+
fi
|
| 310 |
+
echo "Git LFS download failed; trying matching prior release asset."
|
| 311 |
+
python - <<'PY'
|
| 312 |
+
import hashlib
|
| 313 |
+
import json
|
| 314 |
+
import os
|
| 315 |
+
from pathlib import Path
|
| 316 |
+
import subprocess
|
| 317 |
+
import urllib.request
|
| 318 |
+
|
| 319 |
+
graph_tar = Path("graph/wiki-graph.tar.gz")
|
| 320 |
+
pointer = graph_tar.read_text(encoding="utf-8", errors="replace")
|
| 321 |
+
expected_oid = ""
|
| 322 |
+
expected_size = 0
|
| 323 |
+
for line in pointer.splitlines():
|
| 324 |
+
if line.startswith("oid sha256:"):
|
| 325 |
+
expected_oid = line.split(":", 1)[1].strip()
|
| 326 |
+
elif line.startswith("size "):
|
| 327 |
+
expected_size = int(line.split(" ", 1)[1].strip())
|
| 328 |
+
if not expected_oid:
|
| 329 |
+
if graph_tar.stat().st_size > 100_000_000:
|
| 330 |
+
print(f"{graph_tar} is already hydrated")
|
| 331 |
+
raise SystemExit(0)
|
| 332 |
+
raise SystemExit("graph/wiki-graph.tar.gz is neither hydrated nor an LFS pointer")
|
| 333 |
+
|
| 334 |
+
repo = os.environ["GITHUB_REPOSITORY"]
|
| 335 |
+
releases = json.loads(subprocess.check_output(
|
| 336 |
+
["gh", "api", f"repos/{repo}/releases?per_page=50"],
|
| 337 |
+
text=True,
|
| 338 |
+
))
|
| 339 |
+
candidates = []
|
| 340 |
+
for release in releases:
|
| 341 |
+
if release.get("draft") or release.get("prerelease"):
|
| 342 |
+
continue
|
| 343 |
+
for asset in release.get("assets", []):
|
| 344 |
+
if asset.get("name") != "wiki-graph.tar.gz":
|
| 345 |
+
continue
|
| 346 |
+
digest = str(asset.get("digest") or "")
|
| 347 |
+
size = int(asset.get("size") or 0)
|
| 348 |
+
if size != expected_size:
|
| 349 |
+
continue
|
| 350 |
+
if digest and digest != f"sha256:{expected_oid}":
|
| 351 |
+
continue
|
| 352 |
+
candidates.append((release.get("tag_name"), asset))
|
| 353 |
+
|
| 354 |
+
if not candidates:
|
| 355 |
+
raise SystemExit(
|
| 356 |
+
"No previous release asset matches graph/wiki-graph.tar.gz "
|
| 357 |
+
f"sha256:{expected_oid} size:{expected_size}"
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
source_tag, asset = candidates[0]
|
| 361 |
+
tmp = graph_tar.with_name("wiki-graph.tar.gz.download")
|
| 362 |
+
sha = hashlib.sha256()
|
| 363 |
+
total = 0
|
| 364 |
+
with urllib.request.urlopen(asset["browser_download_url"], timeout=300) as resp: # noqa: S310
|
| 365 |
+
with tmp.open("wb") as fh:
|
| 366 |
+
while True:
|
| 367 |
+
chunk = resp.read(1024 * 1024)
|
| 368 |
+
if not chunk:
|
| 369 |
+
break
|
| 370 |
+
sha.update(chunk)
|
| 371 |
+
total += len(chunk)
|
| 372 |
+
fh.write(chunk)
|
| 373 |
+
actual_oid = sha.hexdigest()
|
| 374 |
+
if actual_oid != expected_oid or total != expected_size:
|
| 375 |
+
tmp.unlink(missing_ok=True)
|
| 376 |
+
raise SystemExit(
|
| 377 |
+
"Downloaded graph tar does not match LFS pointer: "
|
| 378 |
+
f"sha256:{actual_oid} size:{total}"
|
| 379 |
+
)
|
| 380 |
+
tmp.replace(graph_tar)
|
| 381 |
+
print(
|
| 382 |
+
"Hydrated graph/wiki-graph.tar.gz from "
|
| 383 |
+
f"{source_tag} release asset sha256:{actual_oid} size:{total}"
|
| 384 |
+
)
|
| 385 |
+
PY
|
| 386 |
|
| 387 |
- name: Validate shipped graph artifacts
|
| 388 |
run: |
|
CHANGELOG.md
CHANGED
|
@@ -7,6 +7,24 @@ Format loosely follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
| 7 |
|
| 8 |
- No unreleased changes yet.
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
## [0.7.18] - 2026-05-09
|
| 11 |
|
| 12 |
### Fixed
|
|
@@ -1424,6 +1442,7 @@ pass. Full test suite: **1316 passed, 2 skipped**.
|
|
| 1424 |
- 5 dead imports removed (`os`, `Mapping`, `timedelta` from
|
| 1425 |
`ctx_lifecycle`; `Path` from `intake_gate`, `intake_pipeline`).
|
| 1426 |
|
|
|
|
| 1427 |
[0.5.1]: https://github.com/stevesolun/ctx/releases/tag/v0.5.1
|
| 1428 |
[0.5.0]: https://github.com/stevesolun/ctx/releases/tag/v0.5.0
|
| 1429 |
[0.5.0-rc1]: https://github.com/stevesolun/ctx/releases/tag/v0.5.0-rc1
|
|
|
|
| 7 |
|
| 8 |
- No unreleased changes yet.
|
| 9 |
|
| 10 |
+
## [1.0.0] - 2026-05-10
|
| 11 |
+
|
| 12 |
+
### Added
|
| 13 |
+
|
| 14 |
+
- Promoted ctx to the first stable release with shipped graph/wiki
|
| 15 |
+
recommendations for skills, agents, MCP servers, and harnesses.
|
| 16 |
+
- Captured structured custom-model harness requirements during `ctx-init`
|
| 17 |
+
and `ctx-harness-install --recommend`: runtime/OS, autonomy, allowed tools,
|
| 18 |
+
verification, privacy/network constraints, and ctx attachment mode.
|
| 19 |
+
|
| 20 |
+
### Fixed
|
| 21 |
+
|
| 22 |
+
- Made graph HTML previews export-aware and covered them in the graph artifact
|
| 23 |
+
validator, so stale preview pages cannot ship beside a newer graph export.
|
| 24 |
+
- Removed stale static graph PNG previews from the repository.
|
| 25 |
+
- Classified `graph/*.html` as graph artifacts in CI so docs/graph checks run
|
| 26 |
+
when shipped graph previews change.
|
| 27 |
+
|
| 28 |
## [0.7.18] - 2026-05-09
|
| 29 |
|
| 30 |
### Fixed
|
|
|
|
| 1442 |
- 5 dead imports removed (`os`, `Mapping`, `timedelta` from
|
| 1443 |
`ctx_lifecycle`; `Path` from `intake_gate`, `intake_pipeline`).
|
| 1444 |
|
| 1445 |
+
[1.0.0]: https://github.com/stevesolun/ctx/releases/tag/v1.0.0
|
| 1446 |
[0.5.1]: https://github.com/stevesolun/ctx/releases/tag/v0.5.1
|
| 1447 |
[0.5.0]: https://github.com/stevesolun/ctx/releases/tag/v0.5.0
|
| 1448 |
[0.5.0-rc1]: https://github.com/stevesolun/ctx/releases/tag/v0.5.0-rc1
|
README.md
CHANGED
|
@@ -18,7 +18,7 @@ tags:
|
|
| 18 |
[](LICENSE)
|
| 19 |
[](https://python.org)
|
| 20 |
[](https://pypi.org/project/claude-ctx/)
|
| 21 |
-
[](graph/)
|
| 23 |
[](https://stevesolun.github.io/ctx/)
|
| 24 |
|
|
|
|
| 18 |
[](LICENSE)
|
| 19 |
[](https://python.org)
|
| 20 |
[](https://pypi.org/project/claude-ctx/)
|
| 21 |
+
[](#)
|
| 22 |
[](graph/)
|
| 23 |
[](https://stevesolun.github.io/ctx/)
|
| 24 |
|
docs/index.md
CHANGED
|
@@ -185,8 +185,8 @@ ones are flagged. New ones self-ingest.
|
|
| 185 |
|
| 186 |
---
|
| 187 |
|
| 188 |
-
**
|
| 189 |
-
3,
|
| 190 |
`ctx-monitor` (local dashboard with graph + wiki + load/unload for
|
| 191 |
skills, agents, and MCP servers, plus harness wiki/graph browsing),
|
| 192 |
`ctx-dedup-check` (pre-ship near-duplicate gate), and
|
|
|
|
| 185 |
|
| 186 |
---
|
| 187 |
|
| 188 |
+
**v1.0.0** — MIT, CI-matrixed (Ubuntu + Windows × Python 3.11/3.12),
|
| 189 |
+
3,706 tests collected. Ships console scripts including `ctx-init`,
|
| 190 |
`ctx-monitor` (local dashboard with graph + wiki + load/unload for
|
| 191 |
skills, agents, and MCP servers, plus harness wiki/graph browsing),
|
| 192 |
`ctx-dedup-check` (pre-ship near-duplicate gate), and
|
docs/knowledge-graph.md
CHANGED
|
@@ -261,6 +261,7 @@ next run rebuilds instead of trusting mixed graph files.
|
|
| 261 |
| 2026-05-04 v0.7.3 artifact refresh | **2,960,215** | Hydrated one recoverable Skills.sh command-injection-testing body, raising hydrated Skills.sh `SKILL.md` files to 89,463; generated micro-skill markdown now defangs high-risk command-injection payloads before packaging. Graph topology unchanged. |
|
| 262 |
| 2026-05-04 body-backed Skills.sh prune | **2,900,834** | Removed 1,383 Skills.sh records that had no packaged `SKILL.md` body and no parseable Skills.sh prose body. Remaining Skills.sh catalog entries, graph nodes, entity pages, and converted `SKILL.md` bodies are all **89,463**. |
|
| 263 |
| 2026-05-05 artifact hygiene refresh | **2,900,834** | Repacked `graph/wiki-graph.tar.gz` to remove transient `.lock` files from the shipped LLM-wiki. Topology unchanged; current tar members: **598,135**. |
|
|
|
|
| 264 |
|
| 265 |
The full audit history lives in `CHANGELOG.md`. The current build is
|
| 266 |
fully reproducible from the wiki content.
|
|
|
|
| 261 |
| 2026-05-04 v0.7.3 artifact refresh | **2,960,215** | Hydrated one recoverable Skills.sh command-injection-testing body, raising hydrated Skills.sh `SKILL.md` files to 89,463; generated micro-skill markdown now defangs high-risk command-injection payloads before packaging. Graph topology unchanged. |
|
| 262 |
| 2026-05-04 body-backed Skills.sh prune | **2,900,834** | Removed 1,383 Skills.sh records that had no packaged `SKILL.md` body and no parseable Skills.sh prose body. Remaining Skills.sh catalog entries, graph nodes, entity pages, and converted `SKILL.md` bodies are all **89,463**. |
|
| 263 |
| 2026-05-05 artifact hygiene refresh | **2,900,834** | Repacked `graph/wiki-graph.tar.gz` to remove transient `.lock` files from the shipped LLM-wiki. Topology unchanged; current tar members: **598,135**. |
|
| 264 |
+
| 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. |
|
| 265 |
|
| 266 |
The full audit history lives in `CHANGELOG.md`. The current build is
|
| 267 |
fully reproducible from the wiki content.
|
graph/README.md
CHANGED
|
@@ -26,12 +26,17 @@ The runtime recommendation paths use this graph in two ways:
|
|
| 26 |
| `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, external catalogs, and Obsidian metadata |
|
| 27 |
| `skills-sh-catalog.json.gz` | Compressed Skills.sh catalog for the 89,463 body-backed entries shipped in the wiki |
|
| 28 |
| `communities.json` | Current Louvain community export |
|
| 29 |
-
| `viz-overview.html`
|
| 30 |
| `viz-python.html` | Python-focused graph view |
|
| 31 |
-
| `viz-security.html`
|
| 32 |
| `viz-ai-agents.html` | AI-agent-focused graph view |
|
| 33 |
| `sample-top60.html` | Interactive top-degree sample |
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
## What Is Inside `wiki-graph.tar.gz`
|
| 36 |
|
| 37 |
- `entities/skills/` - all skill entity pages, including `skills-sh-*` pages
|
|
|
|
| 26 |
| `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, external catalogs, and Obsidian metadata |
|
| 27 |
| `skills-sh-catalog.json.gz` | Compressed Skills.sh catalog for the 89,463 body-backed entries shipped in the wiki |
|
| 28 |
| `communities.json` | Current Louvain community export |
|
| 29 |
+
| `viz-overview.html` | Plotly overview of the graph |
|
| 30 |
| `viz-python.html` | Python-focused graph view |
|
| 31 |
+
| `viz-security.html` | Security-focused graph view |
|
| 32 |
| `viz-ai-agents.html` | AI-agent-focused graph view |
|
| 33 |
| `sample-top60.html` | Interactive top-degree sample |
|
| 34 |
|
| 35 |
+
Preview HTML files are generated from the shipped `graphify-out/graph.json`
|
| 36 |
+
and embed the graph export ID in `<meta name="ctx-graph-export-id">`. Static
|
| 37 |
+
PNG snapshots are intentionally not shipped because they can drift from the
|
| 38 |
+
current tarball without an executable freshness check.
|
| 39 |
+
|
| 40 |
## What Is Inside `wiki-graph.tar.gz`
|
| 41 |
|
| 42 |
- `entities/skills/` - all skill entity pages, including `skills-sh-*` pages
|
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-overview.png
DELETED
Git LFS Details
|
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
|
|
|
graph/viz-security.png
DELETED
Git LFS Details
|
pyproject.toml
CHANGED
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
| 4 |
|
| 5 |
[project]
|
| 6 |
name = "claude-ctx"
|
| 7 |
-
version = "0.
|
| 8 |
description = "Skill and agent recommendation system for Claude Code — knowledge graph, wiki, and intake quality gates"
|
| 9 |
authors = [{ name = "Steve Solun" }]
|
| 10 |
license = "MIT"
|
|
|
|
| 4 |
|
| 5 |
[project]
|
| 6 |
name = "claude-ctx"
|
| 7 |
+
version = "1.0.0"
|
| 8 |
description = "Skill and agent recommendation system for Claude Code — knowledge graph, wiki, and intake quality gates"
|
| 9 |
authors = [{ name = "Steve Solun" }]
|
| 10 |
license = "MIT"
|
scripts/ci_classifier.py
CHANGED
|
@@ -33,6 +33,7 @@ GRAPH_ARTIFACT_PATTERNS = (
|
|
| 33 |
"graph/communities.json",
|
| 34 |
"graph/skills-sh-catalog.json.gz",
|
| 35 |
"graph/wiki-graph.tar.gz",
|
|
|
|
| 36 |
)
|
| 37 |
BROWSER_PATTERNS = (
|
| 38 |
".github/workflows/test.yml",
|
|
|
|
| 33 |
"graph/communities.json",
|
| 34 |
"graph/skills-sh-catalog.json.gz",
|
| 35 |
"graph/wiki-graph.tar.gz",
|
| 36 |
+
"graph/*.html",
|
| 37 |
)
|
| 38 |
BROWSER_PATTERNS = (
|
| 39 |
".github/workflows/test.yml",
|
src/__init__.py
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
"""ctx — skill and agent recommendation for Claude Code."""
|
| 2 |
|
| 3 |
-
__version__ = "0.
|
|
|
|
| 1 |
"""ctx — skill and agent recommendation for Claude Code."""
|
| 2 |
|
| 3 |
+
__version__ = "1.0.0"
|
src/ctx/__init__.py
CHANGED
|
@@ -30,7 +30,7 @@ Package layout:
|
|
| 30 |
ctx.utils - low-level primitives (safe names, atomic IO)
|
| 31 |
"""
|
| 32 |
|
| 33 |
-
__version__ = "0.
|
| 34 |
|
| 35 |
|
| 36 |
# Public library surface — anything listed here is safe for third-
|
|
|
|
| 30 |
ctx.utils - low-level primitives (safe names, atomic IO)
|
| 31 |
"""
|
| 32 |
|
| 33 |
+
__version__ = "1.0.0"
|
| 34 |
|
| 35 |
|
| 36 |
# Public library surface — anything listed here is safe for third-
|
src/ctx_init.py
CHANGED
|
@@ -585,6 +585,24 @@ _PROVIDER_KEY_ENV: dict[str, str] = {
|
|
| 585 |
"ollama": "",
|
| 586 |
}
|
| 587 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 588 |
|
| 589 |
def _model_provider_prefix(model: str) -> str:
|
| 590 |
return model.split("/", 1)[0] if "/" in model else model
|
|
@@ -1156,6 +1174,72 @@ def _prompt_knowledge_mode(default: str = "shipped") -> str:
|
|
| 1156 |
print(" Please choose shipped, local, enriched, or skip.")
|
| 1157 |
|
| 1158 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1159 |
def _stdio_is_interactive() -> bool:
|
| 1160 |
return bool(
|
| 1161 |
getattr(sys.stdin, "isatty", lambda: False)()
|
|
@@ -1221,6 +1305,7 @@ def run_wizard(args: argparse.Namespace) -> None:
|
|
| 1221 |
default=args.goal,
|
| 1222 |
)
|
| 1223 |
if args.model_mode == "custom":
|
|
|
|
| 1224 |
args.validate_model = _prompt_yes_no(
|
| 1225 |
"Validate the model with one tiny provider call now?",
|
| 1226 |
default=args.validate_model,
|
|
@@ -1246,6 +1331,9 @@ def run_model_onboarding(args: argparse.Namespace, claude: Path) -> int:
|
|
| 1246 |
_model_provider_prefix(args.model) if args.model else None
|
| 1247 |
)
|
| 1248 |
api_key_env = _resolve_api_key_env(args.api_key_env, args.model, provider)
|
|
|
|
|
|
|
|
|
|
| 1249 |
profile: dict[str, Any] = {
|
| 1250 |
"mode": mode,
|
| 1251 |
"provider": provider,
|
|
@@ -1255,6 +1343,8 @@ def run_model_onboarding(args: argparse.Namespace, claude: Path) -> int:
|
|
| 1255 |
"goal": goal,
|
| 1256 |
"knowledge_mode": getattr(args, "knowledge_mode", "shipped"),
|
| 1257 |
}
|
|
|
|
|
|
|
| 1258 |
written = write_model_profile(claude, profile, force=args.force)
|
| 1259 |
if written:
|
| 1260 |
print(f" [ok] wrote {written.name}")
|
|
@@ -1277,7 +1367,13 @@ def run_model_onboarding(args: argparse.Namespace, claude: Path) -> int:
|
|
| 1277 |
return rc
|
| 1278 |
|
| 1279 |
recommendation_query = " ".join(
|
| 1280 |
-
part for part in [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1281 |
if part
|
| 1282 |
)
|
| 1283 |
harnesses = recommend_harnesses(
|
|
@@ -1294,11 +1390,12 @@ def run_model_onboarding(args: argparse.Namespace, claude: Path) -> int:
|
|
| 1294 |
print(f" install: ctx-harness-install {name} --dry-run")
|
| 1295 |
elif goal or mode == "custom":
|
| 1296 |
print(" [info] no harness recommendations matched yet")
|
| 1297 |
-
print(
|
| 1298 |
-
|
| 1299 |
-
|
| 1300 |
-
|
| 1301 |
-
|
|
|
|
| 1302 |
return rc
|
| 1303 |
|
| 1304 |
|
|
@@ -1363,6 +1460,30 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 1363 |
"--goal",
|
| 1364 |
help="What the user wants to build; used for harness recommendations",
|
| 1365 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1366 |
parser.add_argument(
|
| 1367 |
"--validate-model",
|
| 1368 |
action="store_true",
|
|
|
|
| 585 |
"ollama": "",
|
| 586 |
}
|
| 587 |
|
| 588 |
+
_HARNESS_REQUIREMENT_FIELDS = (
|
| 589 |
+
("runtime", "harness_runtime"),
|
| 590 |
+
("autonomy", "harness_autonomy"),
|
| 591 |
+
("tools", "harness_tools"),
|
| 592 |
+
("verification", "harness_verify"),
|
| 593 |
+
("privacy", "harness_privacy"),
|
| 594 |
+
("attach_mode", "harness_attach_mode"),
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
_HARNESS_REQUIREMENT_FLAGS = {
|
| 598 |
+
"runtime": "--harness-runtime",
|
| 599 |
+
"autonomy": "--harness-autonomy",
|
| 600 |
+
"tools": "--harness-tools",
|
| 601 |
+
"verification": "--harness-verify",
|
| 602 |
+
"privacy": "--harness-privacy",
|
| 603 |
+
"attach_mode": "--harness-attach-mode",
|
| 604 |
+
}
|
| 605 |
+
|
| 606 |
|
| 607 |
def _model_provider_prefix(model: str) -> str:
|
| 608 |
return model.split("/", 1)[0] if "/" in model else model
|
|
|
|
| 1174 |
print(" Please choose shipped, local, enriched, or skip.")
|
| 1175 |
|
| 1176 |
|
| 1177 |
+
def _harness_requirements_from_args(args: argparse.Namespace) -> dict[str, str]:
|
| 1178 |
+
requirements: dict[str, str] = {}
|
| 1179 |
+
for key, attr in _HARNESS_REQUIREMENT_FIELDS:
|
| 1180 |
+
value = str(getattr(args, attr, "") or "").strip()
|
| 1181 |
+
if value:
|
| 1182 |
+
requirements[key] = value
|
| 1183 |
+
return requirements
|
| 1184 |
+
|
| 1185 |
+
|
| 1186 |
+
def _harness_requirements_text(requirements: dict[str, str]) -> str:
|
| 1187 |
+
return " ".join(
|
| 1188 |
+
value for _key, value in requirements.items()
|
| 1189 |
+
if value.strip()
|
| 1190 |
+
)
|
| 1191 |
+
|
| 1192 |
+
|
| 1193 |
+
def _harness_plan_command(
|
| 1194 |
+
*,
|
| 1195 |
+
goal: str,
|
| 1196 |
+
model_provider: str | None,
|
| 1197 |
+
model: str | None,
|
| 1198 |
+
harness_requirements: dict[str, str],
|
| 1199 |
+
) -> str:
|
| 1200 |
+
parts = [
|
| 1201 |
+
"ctx-harness-install --recommend",
|
| 1202 |
+
f"--goal {json.dumps(goal or model or 'custom model work')}",
|
| 1203 |
+
]
|
| 1204 |
+
if model_provider:
|
| 1205 |
+
parts.append(f"--model-provider {json.dumps(model_provider)}")
|
| 1206 |
+
if model:
|
| 1207 |
+
parts.append(f"--model {json.dumps(model)}")
|
| 1208 |
+
for key, _attr in _HARNESS_REQUIREMENT_FIELDS:
|
| 1209 |
+
value = harness_requirements.get(key)
|
| 1210 |
+
if value:
|
| 1211 |
+
parts.append(f"{_HARNESS_REQUIREMENT_FLAGS[key]} {json.dumps(value)}")
|
| 1212 |
+
parts.append("--plan-on-no-fit")
|
| 1213 |
+
return " ".join(parts)
|
| 1214 |
+
|
| 1215 |
+
|
| 1216 |
+
def _prompt_harness_requirements(args: argparse.Namespace) -> None:
|
| 1217 |
+
args.harness_runtime = _prompt_text(
|
| 1218 |
+
"Runtime / OS target for the harness",
|
| 1219 |
+
default=getattr(args, "harness_runtime", None),
|
| 1220 |
+
)
|
| 1221 |
+
args.harness_autonomy = _prompt_text(
|
| 1222 |
+
"Autonomy level, e.g. supervised or autonomous",
|
| 1223 |
+
default=getattr(args, "harness_autonomy", None) or "supervised",
|
| 1224 |
+
)
|
| 1225 |
+
args.harness_tools = _prompt_text(
|
| 1226 |
+
"Allowed tools/access, e.g. filesystem shell browser",
|
| 1227 |
+
default=getattr(args, "harness_tools", None),
|
| 1228 |
+
)
|
| 1229 |
+
args.harness_verify = _prompt_text(
|
| 1230 |
+
"Verification commands or gates, e.g. pytest ruff",
|
| 1231 |
+
default=getattr(args, "harness_verify", None),
|
| 1232 |
+
)
|
| 1233 |
+
args.harness_privacy = _prompt_text(
|
| 1234 |
+
"Privacy/network constraints",
|
| 1235 |
+
default=getattr(args, "harness_privacy", None),
|
| 1236 |
+
)
|
| 1237 |
+
args.harness_attach_mode = _prompt_text(
|
| 1238 |
+
"How ctx should attach, e.g. mcp, cli, or api",
|
| 1239 |
+
default=getattr(args, "harness_attach_mode", None) or "mcp",
|
| 1240 |
+
)
|
| 1241 |
+
|
| 1242 |
+
|
| 1243 |
def _stdio_is_interactive() -> bool:
|
| 1244 |
return bool(
|
| 1245 |
getattr(sys.stdin, "isatty", lambda: False)()
|
|
|
|
| 1305 |
default=args.goal,
|
| 1306 |
)
|
| 1307 |
if args.model_mode == "custom":
|
| 1308 |
+
_prompt_harness_requirements(args)
|
| 1309 |
args.validate_model = _prompt_yes_no(
|
| 1310 |
"Validate the model with one tiny provider call now?",
|
| 1311 |
default=args.validate_model,
|
|
|
|
| 1331 |
_model_provider_prefix(args.model) if args.model else None
|
| 1332 |
)
|
| 1333 |
api_key_env = _resolve_api_key_env(args.api_key_env, args.model, provider)
|
| 1334 |
+
harness_requirements = (
|
| 1335 |
+
_harness_requirements_from_args(args) if mode == "custom" else {}
|
| 1336 |
+
)
|
| 1337 |
profile: dict[str, Any] = {
|
| 1338 |
"mode": mode,
|
| 1339 |
"provider": provider,
|
|
|
|
| 1343 |
"goal": goal,
|
| 1344 |
"knowledge_mode": getattr(args, "knowledge_mode", "shipped"),
|
| 1345 |
}
|
| 1346 |
+
if harness_requirements:
|
| 1347 |
+
profile["harness_requirements"] = harness_requirements
|
| 1348 |
written = write_model_profile(claude, profile, force=args.force)
|
| 1349 |
if written:
|
| 1350 |
print(f" [ok] wrote {written.name}")
|
|
|
|
| 1367 |
return rc
|
| 1368 |
|
| 1369 |
recommendation_query = " ".join(
|
| 1370 |
+
part for part in [
|
| 1371 |
+
goal,
|
| 1372 |
+
_harness_requirements_text(harness_requirements),
|
| 1373 |
+
provider or "",
|
| 1374 |
+
args.model or "",
|
| 1375 |
+
"harness",
|
| 1376 |
+
]
|
| 1377 |
if part
|
| 1378 |
)
|
| 1379 |
harnesses = recommend_harnesses(
|
|
|
|
| 1390 |
print(f" install: ctx-harness-install {name} --dry-run")
|
| 1391 |
elif goal or mode == "custom":
|
| 1392 |
print(" [info] no harness recommendations matched yet")
|
| 1393 |
+
print(" build plan: " + _harness_plan_command(
|
| 1394 |
+
goal=goal,
|
| 1395 |
+
model_provider=provider,
|
| 1396 |
+
model=args.model,
|
| 1397 |
+
harness_requirements=harness_requirements,
|
| 1398 |
+
))
|
| 1399 |
return rc
|
| 1400 |
|
| 1401 |
|
|
|
|
| 1460 |
"--goal",
|
| 1461 |
help="What the user wants to build; used for harness recommendations",
|
| 1462 |
)
|
| 1463 |
+
parser.add_argument(
|
| 1464 |
+
"--harness-runtime",
|
| 1465 |
+
help="Runtime/OS target for custom-model harness recommendations",
|
| 1466 |
+
)
|
| 1467 |
+
parser.add_argument(
|
| 1468 |
+
"--harness-autonomy",
|
| 1469 |
+
help="Desired harness autonomy level, e.g. supervised or autonomous",
|
| 1470 |
+
)
|
| 1471 |
+
parser.add_argument(
|
| 1472 |
+
"--harness-tools",
|
| 1473 |
+
help="Allowed harness tools/access, e.g. filesystem shell browser",
|
| 1474 |
+
)
|
| 1475 |
+
parser.add_argument(
|
| 1476 |
+
"--harness-verify",
|
| 1477 |
+
help="Verification commands or gates the harness should run",
|
| 1478 |
+
)
|
| 1479 |
+
parser.add_argument(
|
| 1480 |
+
"--harness-privacy",
|
| 1481 |
+
help="Privacy, network, or data-access constraints for the harness",
|
| 1482 |
+
)
|
| 1483 |
+
parser.add_argument(
|
| 1484 |
+
"--harness-attach-mode",
|
| 1485 |
+
help="Preferred ctx attachment mode, e.g. mcp, cli, or api",
|
| 1486 |
+
)
|
| 1487 |
parser.add_argument(
|
| 1488 |
"--validate-model",
|
| 1489 |
action="store_true",
|
src/harness_install.py
CHANGED
|
@@ -809,11 +809,18 @@ def recommend_harnesses_for_cli(
|
|
| 809 |
model_provider: str | None,
|
| 810 |
model: str | None,
|
| 811 |
top_k: int,
|
|
|
|
| 812 |
) -> list[dict[str, Any]]:
|
| 813 |
-
from ctx_init import recommend_harnesses # noqa: PLC0415
|
| 814 |
|
| 815 |
query = " ".join(
|
| 816 |
-
part for part in [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 817 |
)
|
| 818 |
return recommend_harnesses(
|
| 819 |
query,
|
|
@@ -828,11 +835,13 @@ def render_no_fit_harness_plan(
|
|
| 828 |
goal: str,
|
| 829 |
model_provider: str | None,
|
| 830 |
model: str | None,
|
|
|
|
| 831 |
) -> str:
|
| 832 |
"""Render a build handoff when no catalog harness fits the user's setup."""
|
| 833 |
provider = model_provider or _provider_from_model_slug(model) or "unknown provider"
|
| 834 |
model_name = model or "unspecified model"
|
| 835 |
goal_text = goal.strip() or "unspecified development goal"
|
|
|
|
| 836 |
return "\n".join([
|
| 837 |
"# Custom Harness PRD",
|
| 838 |
"",
|
|
@@ -845,6 +854,7 @@ def render_no_fit_harness_plan(
|
|
| 845 |
f"- Model provider: {provider}",
|
| 846 |
f"- Model: {model_name}",
|
| 847 |
"- Target operating systems: Windows, macOS, and Linux unless narrowed by the user",
|
|
|
|
| 848 |
"",
|
| 849 |
"## Required Interview Before Building",
|
| 850 |
"",
|
|
@@ -895,12 +905,31 @@ def _provider_from_model_slug(model: str | None) -> str | None:
|
|
| 895 |
return provider or None
|
| 896 |
|
| 897 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 898 |
def write_no_fit_harness_plan(
|
| 899 |
path: Path,
|
| 900 |
*,
|
| 901 |
goal: str,
|
| 902 |
model_provider: str | None,
|
| 903 |
model: str | None,
|
|
|
|
| 904 |
) -> Path:
|
| 905 |
target = path.expanduser()
|
| 906 |
reject_symlink_path(target)
|
|
@@ -910,6 +939,7 @@ def write_no_fit_harness_plan(
|
|
| 910 |
goal=goal,
|
| 911 |
model_provider=model_provider,
|
| 912 |
model=model,
|
|
|
|
| 913 |
),
|
| 914 |
)
|
| 915 |
return target
|
|
@@ -956,6 +986,12 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 956 |
parser.add_argument("--goal", help="What you want to build or automate")
|
| 957 |
parser.add_argument("--model-provider", help="Model provider prefix, e.g. openai or ollama")
|
| 958 |
parser.add_argument("--model", help="Model slug, e.g. openrouter/openai/gpt-5.5")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 959 |
parser.add_argument("--top-k", type=int, default=5, help="Maximum recommendations to print")
|
| 960 |
parser.add_argument(
|
| 961 |
"--plan-on-no-fit",
|
|
@@ -1021,11 +1057,15 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 1021 |
if not goal.strip():
|
| 1022 |
print("Error: --recommend requires --goal or a free-text query", file=sys.stderr)
|
| 1023 |
return 2
|
|
|
|
|
|
|
|
|
|
| 1024 |
results = recommend_harnesses_for_cli(
|
| 1025 |
goal=goal,
|
| 1026 |
model_provider=args.model_provider,
|
| 1027 |
model=args.model,
|
| 1028 |
top_k=max(1, min(int(args.top_k), 5)),
|
|
|
|
| 1029 |
)
|
| 1030 |
print_recommendations(results)
|
| 1031 |
if not results and args.plan_on_no_fit:
|
|
@@ -1035,6 +1075,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 1035 |
goal=goal,
|
| 1036 |
model_provider=args.model_provider,
|
| 1037 |
model=args.model,
|
|
|
|
| 1038 |
)
|
| 1039 |
print(f"Custom harness plan: {path}")
|
| 1040 |
else:
|
|
@@ -1043,6 +1084,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 1043 |
goal=goal,
|
| 1044 |
model_provider=args.model_provider,
|
| 1045 |
model=args.model,
|
|
|
|
| 1046 |
), end="")
|
| 1047 |
elif not results:
|
| 1048 |
print("Use --plan-on-no-fit to generate a custom harness PRD.")
|
|
|
|
| 809 |
model_provider: str | None,
|
| 810 |
model: str | None,
|
| 811 |
top_k: int,
|
| 812 |
+
harness_requirements: dict[str, str] | None = None,
|
| 813 |
) -> list[dict[str, Any]]:
|
| 814 |
+
from ctx_init import _harness_requirements_text, recommend_harnesses # noqa: PLC0415
|
| 815 |
|
| 816 |
query = " ".join(
|
| 817 |
+
part for part in [
|
| 818 |
+
goal,
|
| 819 |
+
_harness_requirements_text(harness_requirements or {}),
|
| 820 |
+
model_provider or "",
|
| 821 |
+
model or "",
|
| 822 |
+
"harness",
|
| 823 |
+
] if part
|
| 824 |
)
|
| 825 |
return recommend_harnesses(
|
| 826 |
query,
|
|
|
|
| 835 |
goal: str,
|
| 836 |
model_provider: str | None,
|
| 837 |
model: str | None,
|
| 838 |
+
harness_requirements: dict[str, str] | None = None,
|
| 839 |
) -> str:
|
| 840 |
"""Render a build handoff when no catalog harness fits the user's setup."""
|
| 841 |
provider = model_provider or _provider_from_model_slug(model) or "unknown provider"
|
| 842 |
model_name = model or "unspecified model"
|
| 843 |
goal_text = goal.strip() or "unspecified development goal"
|
| 844 |
+
requirement_lines = _format_harness_requirement_lines(harness_requirements or {})
|
| 845 |
return "\n".join([
|
| 846 |
"# Custom Harness PRD",
|
| 847 |
"",
|
|
|
|
| 854 |
f"- Model provider: {provider}",
|
| 855 |
f"- Model: {model_name}",
|
| 856 |
"- Target operating systems: Windows, macOS, and Linux unless narrowed by the user",
|
| 857 |
+
*requirement_lines,
|
| 858 |
"",
|
| 859 |
"## Required Interview Before Building",
|
| 860 |
"",
|
|
|
|
| 905 |
return provider or None
|
| 906 |
|
| 907 |
|
| 908 |
+
def _format_harness_requirement_lines(
|
| 909 |
+
requirements: dict[str, str],
|
| 910 |
+
) -> list[str]:
|
| 911 |
+
labels = {
|
| 912 |
+
"runtime": "Runtime / OS",
|
| 913 |
+
"autonomy": "Autonomy",
|
| 914 |
+
"tools": "Allowed tools/access",
|
| 915 |
+
"verification": "Verification",
|
| 916 |
+
"privacy": "Privacy/network",
|
| 917 |
+
"attach_mode": "Preferred ctx attachment",
|
| 918 |
+
}
|
| 919 |
+
return [
|
| 920 |
+
f"- {label}: {requirements[key]}"
|
| 921 |
+
for key, label in labels.items()
|
| 922 |
+
if requirements.get(key)
|
| 923 |
+
]
|
| 924 |
+
|
| 925 |
+
|
| 926 |
def write_no_fit_harness_plan(
|
| 927 |
path: Path,
|
| 928 |
*,
|
| 929 |
goal: str,
|
| 930 |
model_provider: str | None,
|
| 931 |
model: str | None,
|
| 932 |
+
harness_requirements: dict[str, str] | None = None,
|
| 933 |
) -> Path:
|
| 934 |
target = path.expanduser()
|
| 935 |
reject_symlink_path(target)
|
|
|
|
| 939 |
goal=goal,
|
| 940 |
model_provider=model_provider,
|
| 941 |
model=model,
|
| 942 |
+
harness_requirements=harness_requirements,
|
| 943 |
),
|
| 944 |
)
|
| 945 |
return target
|
|
|
|
| 986 |
parser.add_argument("--goal", help="What you want to build or automate")
|
| 987 |
parser.add_argument("--model-provider", help="Model provider prefix, e.g. openai or ollama")
|
| 988 |
parser.add_argument("--model", help="Model slug, e.g. openrouter/openai/gpt-5.5")
|
| 989 |
+
parser.add_argument("--harness-runtime", help="Runtime/OS target for harness fit")
|
| 990 |
+
parser.add_argument("--harness-autonomy", help="Desired autonomy level")
|
| 991 |
+
parser.add_argument("--harness-tools", help="Allowed tools/access for the harness")
|
| 992 |
+
parser.add_argument("--harness-verify", help="Verification commands or gates")
|
| 993 |
+
parser.add_argument("--harness-privacy", help="Privacy, network, or data constraints")
|
| 994 |
+
parser.add_argument("--harness-attach-mode", help="Preferred ctx attachment mode")
|
| 995 |
parser.add_argument("--top-k", type=int, default=5, help="Maximum recommendations to print")
|
| 996 |
parser.add_argument(
|
| 997 |
"--plan-on-no-fit",
|
|
|
|
| 1057 |
if not goal.strip():
|
| 1058 |
print("Error: --recommend requires --goal or a free-text query", file=sys.stderr)
|
| 1059 |
return 2
|
| 1060 |
+
from ctx_init import _harness_requirements_from_args # noqa: PLC0415
|
| 1061 |
+
|
| 1062 |
+
harness_requirements = _harness_requirements_from_args(args)
|
| 1063 |
results = recommend_harnesses_for_cli(
|
| 1064 |
goal=goal,
|
| 1065 |
model_provider=args.model_provider,
|
| 1066 |
model=args.model,
|
| 1067 |
top_k=max(1, min(int(args.top_k), 5)),
|
| 1068 |
+
harness_requirements=harness_requirements,
|
| 1069 |
)
|
| 1070 |
print_recommendations(results)
|
| 1071 |
if not results and args.plan_on_no_fit:
|
|
|
|
| 1075 |
goal=goal,
|
| 1076 |
model_provider=args.model_provider,
|
| 1077 |
model=args.model,
|
| 1078 |
+
harness_requirements=harness_requirements,
|
| 1079 |
)
|
| 1080 |
print(f"Custom harness plan: {path}")
|
| 1081 |
else:
|
|
|
|
| 1084 |
goal=goal,
|
| 1085 |
model_provider=args.model_provider,
|
| 1086 |
model=args.model,
|
| 1087 |
+
harness_requirements=harness_requirements,
|
| 1088 |
), end="")
|
| 1089 |
elif not results:
|
| 1090 |
print("Use --plan-on-no-fit to generate a custom harness PRD.")
|
src/tests/test_ci_classifier.py
CHANGED
|
@@ -56,6 +56,16 @@ def test_graph_artifacts_are_graph_only_not_docs_only() -> None:
|
|
| 56 |
assert flags["source_changed"] is False
|
| 57 |
|
| 58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
def test_graph_readme_is_docs_not_graph_artifact() -> None:
|
| 60 |
flags = classify_paths(["graph/README.md"])
|
| 61 |
|
|
@@ -138,12 +148,14 @@ def test_ci_workflows_default_to_read_only_token_permissions() -> None:
|
|
| 138 |
assert "\npermissions:\n contents: read\n" in workflow
|
| 139 |
|
| 140 |
|
| 141 |
-
def
|
| 142 |
workflow = Path(".github/workflows/test.yml").read_text(encoding="utf-8")
|
| 143 |
|
| 144 |
assert "Resolve graph LFS artifacts" in workflow
|
| 145 |
-
assert "
|
| 146 |
-
assert "
|
|
|
|
|
|
|
| 147 |
assert "validating pointer metadata only" not in workflow
|
| 148 |
|
| 149 |
|
|
@@ -177,12 +189,20 @@ def test_publish_workflow_validates_and_uploads_graph_assets() -> None:
|
|
| 177 |
assert "gh release upload" in workflow
|
| 178 |
assert '--repo "$GITHUB_REPOSITORY"' in workflow
|
| 179 |
assert "needs.release-assets.result == 'success'" in workflow
|
|
|
|
| 180 |
assert "continue-on-error: true" not in workflow
|
| 181 |
assert "needs.release-assets.result == 'skipped'" not in workflow
|
| 182 |
assert "PyPI publish will continue without release asset upload" not in workflow
|
| 183 |
assert "graph_assets_available" in workflow
|
| 184 |
|
| 185 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
def test_pre_commit_refreshes_all_repo_stats_outputs() -> None:
|
| 187 |
hook = Path(".githooks/pre-commit").read_text(encoding="utf-8")
|
| 188 |
|
|
|
|
| 56 |
assert flags["source_changed"] is False
|
| 57 |
|
| 58 |
|
| 59 |
+
def test_graph_preview_html_is_graph_artifact() -> None:
|
| 60 |
+
flags = classify_paths(["graph/viz-overview.html"])
|
| 61 |
+
|
| 62 |
+
assert flags["docs_changed"] is False
|
| 63 |
+
assert flags["docs_only"] is False
|
| 64 |
+
assert flags["graph_artifact_changed"] is True
|
| 65 |
+
assert flags["graph_changed"] is True
|
| 66 |
+
assert flags["graph_only"] is True
|
| 67 |
+
|
| 68 |
+
|
| 69 |
def test_graph_readme_is_docs_not_graph_artifact() -> None:
|
| 70 |
flags = classify_paths(["graph/README.md"])
|
| 71 |
|
|
|
|
| 148 |
assert "\npermissions:\n contents: read\n" in workflow
|
| 149 |
|
| 150 |
|
| 151 |
+
def test_graph_artifact_job_uses_release_asset_fallback_for_lfs_budget() -> None:
|
| 152 |
workflow = Path(".github/workflows/test.yml").read_text(encoding="utf-8")
|
| 153 |
|
| 154 |
assert "Resolve graph LFS artifacts" in workflow
|
| 155 |
+
assert "Git LFS download failed; trying matching prior release asset." in workflow
|
| 156 |
+
assert "sha256:{expected_oid} size:{expected_size}" in workflow
|
| 157 |
+
assert "Hydrated graph/wiki-graph.tar.gz from" in workflow
|
| 158 |
+
assert "python src/validate_graph_artifacts.py" in workflow
|
| 159 |
assert "validating pointer metadata only" not in workflow
|
| 160 |
|
| 161 |
|
|
|
|
| 189 |
assert "gh release upload" in workflow
|
| 190 |
assert '--repo "$GITHUB_REPOSITORY"' in workflow
|
| 191 |
assert "needs.release-assets.result == 'success'" in workflow
|
| 192 |
+
assert "github.event_name == 'workflow_dispatch' || needs.release-assets.result == 'success'" not in workflow
|
| 193 |
assert "continue-on-error: true" not in workflow
|
| 194 |
assert "needs.release-assets.result == 'skipped'" not in workflow
|
| 195 |
assert "PyPI publish will continue without release asset upload" not in workflow
|
| 196 |
assert "graph_assets_available" in workflow
|
| 197 |
|
| 198 |
|
| 199 |
+
def test_changelog_defines_current_release_link() -> None:
|
| 200 |
+
changelog = Path("CHANGELOG.md").read_text(encoding="utf-8")
|
| 201 |
+
|
| 202 |
+
assert "## [1.0.0] - 2026-05-10" in changelog
|
| 203 |
+
assert "[1.0.0]: https://github.com/stevesolun/ctx/releases/tag/v1.0.0" in changelog
|
| 204 |
+
|
| 205 |
+
|
| 206 |
def test_pre_commit_refreshes_all_repo_stats_outputs() -> None:
|
| 207 |
hook = Path(".githooks/pre-commit").read_text(encoding="utf-8")
|
| 208 |
|
src/tests/test_ctx_init.py
CHANGED
|
@@ -140,6 +140,12 @@ def test_main_auto_wizard_in_terminal_configures_custom_model(
|
|
| 140 |
"", # api key env default: OPENAI_API_KEY
|
| 141 |
"", # base URL
|
| 142 |
"build CAD artifacts",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
"n", # validate model
|
| 144 |
])
|
| 145 |
monkeypatch.setattr(builtins, "input", lambda _prompt: next(answers))
|
|
@@ -168,6 +174,14 @@ def test_main_auto_wizard_in_terminal_configures_custom_model(
|
|
| 168 |
assert profile["api_key_env"] == "OPENAI_API_KEY"
|
| 169 |
assert profile["goal"] == "build CAD artifacts"
|
| 170 |
assert profile["knowledge_mode"] == "enriched"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
user_config = json.loads((tmp_path / "skill-system-config.json").read_text())
|
| 172 |
assert user_config["knowledge"]["mode"] == "enriched"
|
| 173 |
|
|
@@ -450,6 +464,60 @@ def test_main_custom_model_writes_profile_and_recommends_harness(
|
|
| 450 |
assert "text-to-cad" in capsys.readouterr().out
|
| 451 |
|
| 452 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 453 |
def test_main_custom_model_no_fit_points_to_harness_plan(
|
| 454 |
tmp_path: Path,
|
| 455 |
monkeypatch,
|
|
@@ -462,13 +530,25 @@ def test_main_custom_model_no_fit_points_to_harness_plan(
|
|
| 462 |
rc = ci.main([
|
| 463 |
"--model-mode", "custom",
|
| 464 |
"--model", "ollama/llama3.1",
|
|
|
|
| 465 |
"--goal", "private local CAD workflow",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 466 |
])
|
| 467 |
|
| 468 |
assert rc == 0
|
| 469 |
output = capsys.readouterr().out
|
| 470 |
assert "no harness recommendations matched yet" in output
|
| 471 |
assert "ctx-harness-install --recommend" in output
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 472 |
assert "--plan-on-no-fit" in output
|
| 473 |
|
| 474 |
|
|
|
|
| 140 |
"", # api key env default: OPENAI_API_KEY
|
| 141 |
"", # base URL
|
| 142 |
"build CAD artifacts",
|
| 143 |
+
"windows python", # runtime / OS
|
| 144 |
+
"supervised", # autonomy
|
| 145 |
+
"filesystem shell", # allowed tools
|
| 146 |
+
"pytest ruff", # verification
|
| 147 |
+
"private repo", # privacy / network
|
| 148 |
+
"mcp", # attach mode
|
| 149 |
"n", # validate model
|
| 150 |
])
|
| 151 |
monkeypatch.setattr(builtins, "input", lambda _prompt: next(answers))
|
|
|
|
| 174 |
assert profile["api_key_env"] == "OPENAI_API_KEY"
|
| 175 |
assert profile["goal"] == "build CAD artifacts"
|
| 176 |
assert profile["knowledge_mode"] == "enriched"
|
| 177 |
+
assert profile["harness_requirements"] == {
|
| 178 |
+
"runtime": "windows python",
|
| 179 |
+
"autonomy": "supervised",
|
| 180 |
+
"tools": "filesystem shell",
|
| 181 |
+
"verification": "pytest ruff",
|
| 182 |
+
"privacy": "private repo",
|
| 183 |
+
"attach_mode": "mcp",
|
| 184 |
+
}
|
| 185 |
user_config = json.loads((tmp_path / "skill-system-config.json").read_text())
|
| 186 |
assert user_config["knowledge"]["mode"] == "enriched"
|
| 187 |
|
|
|
|
| 464 |
assert "text-to-cad" in capsys.readouterr().out
|
| 465 |
|
| 466 |
|
| 467 |
+
def test_main_custom_model_records_structured_harness_requirements(
|
| 468 |
+
tmp_path: Path,
|
| 469 |
+
monkeypatch,
|
| 470 |
+
) -> None:
|
| 471 |
+
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 472 |
+
monkeypatch.setattr(ci, "seed_toolboxes", lambda force=False: 0)
|
| 473 |
+
recommendation_calls: list[dict[str, object]] = []
|
| 474 |
+
|
| 475 |
+
def fake_recommend(
|
| 476 |
+
goal: str,
|
| 477 |
+
top_k: int = 5,
|
| 478 |
+
model_provider: str | None = None,
|
| 479 |
+
model: str | None = None,
|
| 480 |
+
) -> list[dict[str, object]]:
|
| 481 |
+
recommendation_calls.append({
|
| 482 |
+
"goal": goal,
|
| 483 |
+
"top_k": top_k,
|
| 484 |
+
"model_provider": model_provider,
|
| 485 |
+
"model": model,
|
| 486 |
+
})
|
| 487 |
+
return []
|
| 488 |
+
|
| 489 |
+
monkeypatch.setattr(ci, "recommend_harnesses", fake_recommend)
|
| 490 |
+
|
| 491 |
+
rc = ci.main([
|
| 492 |
+
"--model-mode", "custom",
|
| 493 |
+
"--model", "openai/gpt-5.5",
|
| 494 |
+
"--goal", "build a code agent",
|
| 495 |
+
"--harness-runtime", "windows python",
|
| 496 |
+
"--harness-autonomy", "supervised",
|
| 497 |
+
"--harness-tools", "filesystem shell browser",
|
| 498 |
+
"--harness-verify", "pytest ruff",
|
| 499 |
+
"--harness-privacy", "private repo no secrets",
|
| 500 |
+
"--harness-attach-mode", "mcp",
|
| 501 |
+
])
|
| 502 |
+
|
| 503 |
+
assert rc == 0
|
| 504 |
+
profile = json.loads((tmp_path / "ctx-model-profile.json").read_text())
|
| 505 |
+
assert profile["harness_requirements"] == {
|
| 506 |
+
"runtime": "windows python",
|
| 507 |
+
"autonomy": "supervised",
|
| 508 |
+
"tools": "filesystem shell browser",
|
| 509 |
+
"verification": "pytest ruff",
|
| 510 |
+
"privacy": "private repo no secrets",
|
| 511 |
+
"attach_mode": "mcp",
|
| 512 |
+
}
|
| 513 |
+
query = str(recommendation_calls[0]["goal"])
|
| 514 |
+
assert "windows python" in query
|
| 515 |
+
assert "filesystem shell browser" in query
|
| 516 |
+
assert "pytest ruff" in query
|
| 517 |
+
assert "private repo no secrets" in query
|
| 518 |
+
assert "mcp" in query
|
| 519 |
+
|
| 520 |
+
|
| 521 |
def test_main_custom_model_no_fit_points_to_harness_plan(
|
| 522 |
tmp_path: Path,
|
| 523 |
monkeypatch,
|
|
|
|
| 530 |
rc = ci.main([
|
| 531 |
"--model-mode", "custom",
|
| 532 |
"--model", "ollama/llama3.1",
|
| 533 |
+
"--model-provider", "ollama",
|
| 534 |
"--goal", "private local CAD workflow",
|
| 535 |
+
"--harness-runtime", "linux server",
|
| 536 |
+
"--harness-tools", "filesystem shell",
|
| 537 |
+
"--harness-verify", "pytest",
|
| 538 |
+
"--harness-privacy", "offline source code",
|
| 539 |
+
"--harness-attach-mode", "mcp",
|
| 540 |
])
|
| 541 |
|
| 542 |
assert rc == 0
|
| 543 |
output = capsys.readouterr().out
|
| 544 |
assert "no harness recommendations matched yet" in output
|
| 545 |
assert "ctx-harness-install --recommend" in output
|
| 546 |
+
assert "--model-provider \"ollama\"" in output
|
| 547 |
+
assert "--harness-runtime \"linux server\"" in output
|
| 548 |
+
assert "--harness-tools \"filesystem shell\"" in output
|
| 549 |
+
assert "--harness-verify \"pytest\"" in output
|
| 550 |
+
assert "--harness-privacy \"offline source code\"" in output
|
| 551 |
+
assert "--harness-attach-mode \"mcp\"" in output
|
| 552 |
assert "--plan-on-no-fit" in output
|
| 553 |
|
| 554 |
|
src/tests/test_harness_install.py
CHANGED
|
@@ -764,6 +764,93 @@ def test_recommend_mode_prints_install_handoff(
|
|
| 764 |
assert "ctx-harness-install text-to-cad --dry-run" in output
|
| 765 |
|
| 766 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 767 |
def test_recommend_no_fit_prints_custom_harness_plan(
|
| 768 |
monkeypatch: Any,
|
| 769 |
capsys: Any,
|
|
@@ -778,6 +865,14 @@ def test_recommend_no_fit_prints_custom_harness_plan(
|
|
| 778 |
"ollama",
|
| 779 |
"--model",
|
| 780 |
"ollama/llama3.1",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 781 |
"--plan-on-no-fit",
|
| 782 |
])
|
| 783 |
|
|
@@ -788,6 +883,10 @@ def test_recommend_no_fit_prints_custom_harness_plan(
|
|
| 788 |
assert "ctx-mcp-server" in output
|
| 789 |
assert "ctx.recommend_bundle" in output
|
| 790 |
assert "Windows, macOS, and Linux" in output
|
|
|
|
|
|
|
|
|
|
|
|
|
| 791 |
|
| 792 |
|
| 793 |
def test_recommend_no_fit_writes_custom_harness_plan(
|
|
|
|
| 764 |
assert "ctx-harness-install text-to-cad --dry-run" in output
|
| 765 |
|
| 766 |
|
| 767 |
+
def test_recommend_mode_passes_structured_harness_requirements(
|
| 768 |
+
monkeypatch: Any,
|
| 769 |
+
) -> None:
|
| 770 |
+
calls: list[dict[str, object]] = []
|
| 771 |
+
|
| 772 |
+
def fake_recommend(**kwargs: Any) -> list[dict[str, object]]:
|
| 773 |
+
calls.append(kwargs)
|
| 774 |
+
return []
|
| 775 |
+
|
| 776 |
+
monkeypatch.setattr(harness_install, "recommend_harnesses_for_cli", fake_recommend)
|
| 777 |
+
|
| 778 |
+
rc = harness_install.main([
|
| 779 |
+
"--recommend",
|
| 780 |
+
"--goal",
|
| 781 |
+
"build a code agent",
|
| 782 |
+
"--model",
|
| 783 |
+
"openai/gpt-5.5",
|
| 784 |
+
"--harness-runtime",
|
| 785 |
+
"windows python",
|
| 786 |
+
"--harness-autonomy",
|
| 787 |
+
"supervised",
|
| 788 |
+
"--harness-tools",
|
| 789 |
+
"filesystem shell browser",
|
| 790 |
+
"--harness-verify",
|
| 791 |
+
"pytest ruff",
|
| 792 |
+
"--harness-privacy",
|
| 793 |
+
"private repo no secrets",
|
| 794 |
+
"--harness-attach-mode",
|
| 795 |
+
"mcp",
|
| 796 |
+
])
|
| 797 |
+
|
| 798 |
+
assert rc == 0
|
| 799 |
+
assert calls[0]["harness_requirements"] == {
|
| 800 |
+
"runtime": "windows python",
|
| 801 |
+
"autonomy": "supervised",
|
| 802 |
+
"tools": "filesystem shell browser",
|
| 803 |
+
"verification": "pytest ruff",
|
| 804 |
+
"privacy": "private repo no secrets",
|
| 805 |
+
"attach_mode": "mcp",
|
| 806 |
+
}
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
def test_recommend_cli_query_includes_structured_harness_requirements(
|
| 810 |
+
monkeypatch: Any,
|
| 811 |
+
) -> None:
|
| 812 |
+
import ctx_init
|
| 813 |
+
|
| 814 |
+
calls: list[dict[str, object]] = []
|
| 815 |
+
|
| 816 |
+
def fake_recommend(
|
| 817 |
+
goal: str,
|
| 818 |
+
top_k: int = 5,
|
| 819 |
+
model_provider: str | None = None,
|
| 820 |
+
model: str | None = None,
|
| 821 |
+
) -> list[dict[str, object]]:
|
| 822 |
+
calls.append({
|
| 823 |
+
"goal": goal,
|
| 824 |
+
"top_k": top_k,
|
| 825 |
+
"model_provider": model_provider,
|
| 826 |
+
"model": model,
|
| 827 |
+
})
|
| 828 |
+
return []
|
| 829 |
+
|
| 830 |
+
monkeypatch.setattr(ctx_init, "recommend_harnesses", fake_recommend)
|
| 831 |
+
|
| 832 |
+
harness_install.recommend_harnesses_for_cli(
|
| 833 |
+
goal="build a code agent",
|
| 834 |
+
model_provider="openai",
|
| 835 |
+
model="openai/gpt-5.5",
|
| 836 |
+
top_k=5,
|
| 837 |
+
harness_requirements={
|
| 838 |
+
"runtime": "windows python",
|
| 839 |
+
"tools": "filesystem shell browser",
|
| 840 |
+
"verification": "pytest ruff",
|
| 841 |
+
"privacy": "private repo no secrets",
|
| 842 |
+
"attach_mode": "mcp",
|
| 843 |
+
},
|
| 844 |
+
)
|
| 845 |
+
|
| 846 |
+
query = str(calls[0]["goal"])
|
| 847 |
+
assert "windows python" in query
|
| 848 |
+
assert "filesystem shell browser" in query
|
| 849 |
+
assert "pytest ruff" in query
|
| 850 |
+
assert "private repo no secrets" in query
|
| 851 |
+
assert "mcp" in query
|
| 852 |
+
|
| 853 |
+
|
| 854 |
def test_recommend_no_fit_prints_custom_harness_plan(
|
| 855 |
monkeypatch: Any,
|
| 856 |
capsys: Any,
|
|
|
|
| 865 |
"ollama",
|
| 866 |
"--model",
|
| 867 |
"ollama/llama3.1",
|
| 868 |
+
"--harness-runtime",
|
| 869 |
+
"linux server",
|
| 870 |
+
"--harness-tools",
|
| 871 |
+
"filesystem shell",
|
| 872 |
+
"--harness-verify",
|
| 873 |
+
"pytest",
|
| 874 |
+
"--harness-privacy",
|
| 875 |
+
"offline source code",
|
| 876 |
"--plan-on-no-fit",
|
| 877 |
])
|
| 878 |
|
|
|
|
| 883 |
assert "ctx-mcp-server" in output
|
| 884 |
assert "ctx.recommend_bundle" in output
|
| 885 |
assert "Windows, macOS, and Linux" in output
|
| 886 |
+
assert "Runtime / OS: linux server" in output
|
| 887 |
+
assert "Allowed tools/access: filesystem shell" in output
|
| 888 |
+
assert "Verification: pytest" in output
|
| 889 |
+
assert "Privacy/network: offline source code" in output
|
| 890 |
|
| 891 |
|
| 892 |
def test_recommend_no_fit_writes_custom_harness_plan(
|
src/tests/test_validate_graph_artifacts.py
CHANGED
|
@@ -17,6 +17,14 @@ from validate_graph_artifacts import (
|
|
| 17 |
validate_graph_artifacts,
|
| 18 |
)
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
def _add_text(tf: tarfile.TarFile, name: str, text: str) -> None:
|
| 22 |
payload = text.encode("utf-8")
|
|
@@ -125,6 +133,23 @@ def _write_archive(
|
|
| 125 |
_add_text(tf, "./converted/skills-sh-example-skill/SKILL.md.original", "# Raw\n")
|
| 126 |
if include_lock:
|
| 127 |
_add_text(tf, "./index.md.lock", "")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
|
| 130 |
def test_validate_graph_artifacts_checks_catalog_paths_and_deep_graph_stats(
|
|
@@ -212,6 +237,35 @@ def test_validate_graph_artifacts_rejects_mixed_export_generation(
|
|
| 212 |
)
|
| 213 |
|
| 214 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
@pytest.mark.parametrize(
|
| 216 |
("archive_kwargs", "missing_name"),
|
| 217 |
[
|
|
|
|
| 17 |
validate_graph_artifacts,
|
| 18 |
)
|
| 19 |
|
| 20 |
+
_PREVIEW_HTML_FILES = (
|
| 21 |
+
"sample-top60.html",
|
| 22 |
+
"viz-ai-agents.html",
|
| 23 |
+
"viz-overview.html",
|
| 24 |
+
"viz-python.html",
|
| 25 |
+
"viz-security.html",
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
|
| 29 |
def _add_text(tf: tarfile.TarFile, name: str, text: str) -> None:
|
| 30 |
payload = text.encode("utf-8")
|
|
|
|
| 133 |
_add_text(tf, "./converted/skills-sh-example-skill/SKILL.md.original", "# Raw\n")
|
| 134 |
if include_lock:
|
| 135 |
_add_text(tf, "./index.md.lock", "")
|
| 136 |
+
for preview in _PREVIEW_HTML_FILES:
|
| 137 |
+
(graph_dir / preview).write_text(
|
| 138 |
+
"\n".join([
|
| 139 |
+
"<!DOCTYPE html>",
|
| 140 |
+
"<html><head>",
|
| 141 |
+
f'<meta name="ctx-graph-export-id" content="{manifest_export_id}">',
|
| 142 |
+
"</head><body>",
|
| 143 |
+
"const CTX_GRAPH_METADATA = "
|
| 144 |
+
+ json.dumps({
|
| 145 |
+
"export_id": manifest_export_id,
|
| 146 |
+
"source_graph_nodes": 2,
|
| 147 |
+
"source_graph_edges": 1,
|
| 148 |
+
}),
|
| 149 |
+
"</body></html>",
|
| 150 |
+
]),
|
| 151 |
+
encoding="utf-8",
|
| 152 |
+
)
|
| 153 |
|
| 154 |
|
| 155 |
def test_validate_graph_artifacts_checks_catalog_paths_and_deep_graph_stats(
|
|
|
|
| 237 |
)
|
| 238 |
|
| 239 |
|
| 240 |
+
def test_validate_graph_artifacts_rejects_stale_preview_html(
|
| 241 |
+
tmp_path: Path,
|
| 242 |
+
) -> None:
|
| 243 |
+
_write_catalog(
|
| 244 |
+
tmp_path,
|
| 245 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 246 |
+
)
|
| 247 |
+
(tmp_path / "communities.json").write_text(
|
| 248 |
+
json.dumps({"total_communities": 1}),
|
| 249 |
+
encoding="utf-8",
|
| 250 |
+
)
|
| 251 |
+
_write_archive(tmp_path)
|
| 252 |
+
(tmp_path / "viz-overview.html").write_text(
|
| 253 |
+
'<meta name="ctx-graph-export-id" content="old-export">',
|
| 254 |
+
encoding="utf-8",
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
with pytest.raises(GraphArtifactError, match="stale graph preview"):
|
| 258 |
+
validate_graph_artifacts(
|
| 259 |
+
tmp_path,
|
| 260 |
+
deep=True,
|
| 261 |
+
min_nodes=2,
|
| 262 |
+
min_edges=1,
|
| 263 |
+
min_skills_sh_nodes=1,
|
| 264 |
+
min_semantic_edges=1,
|
| 265 |
+
expected_harnesses={"langgraph"},
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
@pytest.mark.parametrize(
|
| 270 |
("archive_kwargs", "missing_name"),
|
| 271 |
[
|
src/tests/test_wiki_visualize.py
CHANGED
|
@@ -13,6 +13,7 @@ and assert that the payload never appears in an executable form.
|
|
| 13 |
|
| 14 |
from __future__ import annotations
|
| 15 |
|
|
|
|
| 16 |
import sys
|
| 17 |
from pathlib import Path
|
| 18 |
|
|
@@ -118,3 +119,52 @@ def test_visualizer_renders_mcp_and_harness_type_filters():
|
|
| 118 |
assert 'data-type="harness"' in html
|
| 119 |
assert '"mcp-server": "#06b6d4"' in html
|
| 120 |
assert '"harness": "#22c55e"' in html
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
from __future__ import annotations
|
| 15 |
|
| 16 |
+
import json
|
| 17 |
import sys
|
| 18 |
from pathlib import Path
|
| 19 |
|
|
|
|
| 119 |
assert 'data-type="harness"' in html
|
| 120 |
assert '"mcp-server": "#06b6d4"' in html
|
| 121 |
assert '"harness": "#22c55e"' in html
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def test_visualizer_can_load_explicit_graph_and_communities(tmp_path):
|
| 125 |
+
import wiki_visualize as wv
|
| 126 |
+
|
| 127 |
+
graph_path = tmp_path / "graph.json"
|
| 128 |
+
communities_path = tmp_path / "communities.json"
|
| 129 |
+
graph_path.write_text(json.dumps({
|
| 130 |
+
"directed": False,
|
| 131 |
+
"multigraph": False,
|
| 132 |
+
"graph": {"export_id": "ctx-graph-test-2-1"},
|
| 133 |
+
"nodes": [
|
| 134 |
+
{"id": "skill:a", "label": "alpha", "type": "skill", "tags": ["python"]},
|
| 135 |
+
{"id": "harness:b", "label": "beta", "type": "harness", "tags": ["agent"]},
|
| 136 |
+
],
|
| 137 |
+
"edges": [{"source": "skill:a", "target": "harness:b", "weight": 0.9}],
|
| 138 |
+
}), encoding="utf-8")
|
| 139 |
+
communities_path.write_text(json.dumps({
|
| 140 |
+
"communities": {"7": {"members": ["skill:a", "harness:b"]}},
|
| 141 |
+
}), encoding="utf-8")
|
| 142 |
+
|
| 143 |
+
G = wv.load_graph(graph_path)
|
| 144 |
+
communities = wv.load_communities(communities_path)
|
| 145 |
+
|
| 146 |
+
assert G.graph["export_id"] == "ctx-graph-test-2-1"
|
| 147 |
+
assert G.number_of_nodes() == 2
|
| 148 |
+
assert communities["communities"]["7"]["members"] == ["skill:a", "harness:b"]
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def test_visualizer_embeds_export_metadata_for_preview_freshness():
|
| 152 |
+
import wiki_visualize as wv
|
| 153 |
+
|
| 154 |
+
G = nx.Graph(export_id="ctx-graph-test-2-1")
|
| 155 |
+
G.add_node("skill:a", label="alpha", type="skill", tags=["python"])
|
| 156 |
+
G.add_node("harness:b", label="beta", type="harness", tags=["agent"])
|
| 157 |
+
G.add_edge("skill:a", "harness:b", weight=0.9)
|
| 158 |
+
pos = {"skill:a": (0.0, 0.0), "harness:b": (1.0, 1.0)}
|
| 159 |
+
|
| 160 |
+
html = wv.build_html_with_filters(
|
| 161 |
+
G,
|
| 162 |
+
pos,
|
| 163 |
+
title="Knowledge Graph",
|
| 164 |
+
metadata={"export_id": "ctx-graph-test-2-1", "nodes": 2, "edges": 1},
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
assert '<meta name="ctx-graph-export-id" content="ctx-graph-test-2-1">' in html
|
| 168 |
+
assert '"export_id": "ctx-graph-test-2-1"' in html
|
| 169 |
+
assert '"nodes": 2' in html
|
| 170 |
+
assert '"edges": 1' in html
|
src/validate_graph_artifacts.py
CHANGED
|
@@ -34,10 +34,21 @@ _SOURCE_SKILLS_SH_RE = re.compile(rb'"source_catalog"\s*:\s*"skills\.sh"')
|
|
| 34 |
_HARNESS_TYPE_RE = re.compile(rb'"type"\s*:\s*"harness"')
|
| 35 |
_GRAPH_KEY_RE = re.compile(rb'"graph"\s*:\s*\{')
|
| 36 |
_REPORT_EXPORT_ID_RE = re.compile(r"^>\s*Export ID:\s*(\S+)\s*$", re.MULTILINE)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
_SEMANTIC_SIM_RE = re.compile(
|
| 38 |
rb'"semantic_sim"\s*:\s*(-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)',
|
| 39 |
)
|
| 40 |
_WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
|
| 43 |
class GraphArtifactError(RuntimeError):
|
|
@@ -351,6 +362,7 @@ def validate_graph_artifacts(
|
|
| 351 |
if "graphify-out/graph.json" not in export_ids:
|
| 352 |
raise GraphArtifactError("graphify-out/graph.json is missing export_id")
|
| 353 |
_validate_export_ids(export_ids, expected=manifest_export_id)
|
|
|
|
| 354 |
missing_pages = sorted(required_skill_pages - names)
|
| 355 |
if missing_pages:
|
| 356 |
raise GraphArtifactError(f"missing Skills.sh entity pages: {missing_pages[:5]}")
|
|
@@ -428,6 +440,43 @@ def validate_graph_artifacts(
|
|
| 428 |
return stats
|
| 429 |
|
| 430 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 431 |
def _read_tar_json(tf: tarfile.TarFile, member: tarfile.TarInfo, name: str) -> Any:
|
| 432 |
f = tf.extractfile(member)
|
| 433 |
if f is None:
|
|
|
|
| 34 |
_HARNESS_TYPE_RE = re.compile(rb'"type"\s*:\s*"harness"')
|
| 35 |
_GRAPH_KEY_RE = re.compile(rb'"graph"\s*:\s*\{')
|
| 36 |
_REPORT_EXPORT_ID_RE = re.compile(r"^>\s*Export ID:\s*(\S+)\s*$", re.MULTILINE)
|
| 37 |
+
_PREVIEW_EXPORT_ID_RE = re.compile(
|
| 38 |
+
r'<meta\s+name=["\']ctx-graph-export-id["\']\s+content=["\']([^"\']+)["\']',
|
| 39 |
+
re.IGNORECASE,
|
| 40 |
+
)
|
| 41 |
_SEMANTIC_SIM_RE = re.compile(
|
| 42 |
rb'"semantic_sim"\s*:\s*(-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)',
|
| 43 |
)
|
| 44 |
_WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:")
|
| 45 |
+
_PREVIEW_HTML_FILES = (
|
| 46 |
+
"sample-top60.html",
|
| 47 |
+
"viz-ai-agents.html",
|
| 48 |
+
"viz-overview.html",
|
| 49 |
+
"viz-python.html",
|
| 50 |
+
"viz-security.html",
|
| 51 |
+
)
|
| 52 |
|
| 53 |
|
| 54 |
class GraphArtifactError(RuntimeError):
|
|
|
|
| 362 |
if "graphify-out/graph.json" not in export_ids:
|
| 363 |
raise GraphArtifactError("graphify-out/graph.json is missing export_id")
|
| 364 |
_validate_export_ids(export_ids, expected=manifest_export_id)
|
| 365 |
+
_validate_graph_previews(graph_dir, export_id=manifest_export_id, manifest=manifest)
|
| 366 |
missing_pages = sorted(required_skill_pages - names)
|
| 367 |
if missing_pages:
|
| 368 |
raise GraphArtifactError(f"missing Skills.sh entity pages: {missing_pages[:5]}")
|
|
|
|
| 440 |
return stats
|
| 441 |
|
| 442 |
|
| 443 |
+
def _validate_graph_previews(
|
| 444 |
+
graph_dir: Path,
|
| 445 |
+
*,
|
| 446 |
+
export_id: str,
|
| 447 |
+
manifest: dict[str, Any] | None,
|
| 448 |
+
) -> None:
|
| 449 |
+
counts = manifest.get("counts") if isinstance(manifest, dict) else None
|
| 450 |
+
source_nodes = counts.get("nodes") if isinstance(counts, dict) else None
|
| 451 |
+
source_edges = counts.get("edges") if isinstance(counts, dict) else None
|
| 452 |
+
for filename in _PREVIEW_HTML_FILES:
|
| 453 |
+
path = graph_dir / filename
|
| 454 |
+
if not path.is_file() or path.stat().st_size == 0:
|
| 455 |
+
raise GraphArtifactError(f"missing graph preview: {filename}")
|
| 456 |
+
text = path.read_text(encoding="utf-8", errors="replace")
|
| 457 |
+
match = _PREVIEW_EXPORT_ID_RE.search(text)
|
| 458 |
+
actual_export = match.group(1).strip() if match else ""
|
| 459 |
+
if actual_export != export_id:
|
| 460 |
+
raise GraphArtifactError(
|
| 461 |
+
f"stale graph preview {filename}: expected export_id {export_id}, "
|
| 462 |
+
f"got {actual_export or 'missing'}",
|
| 463 |
+
)
|
| 464 |
+
if isinstance(source_nodes, int) and not re.search(
|
| 465 |
+
rf'"source_graph_nodes"\s*:\s*{source_nodes}\b',
|
| 466 |
+
text,
|
| 467 |
+
):
|
| 468 |
+
raise GraphArtifactError(
|
| 469 |
+
f"stale graph preview {filename}: missing source_graph_nodes {source_nodes}",
|
| 470 |
+
)
|
| 471 |
+
if isinstance(source_edges, int) and not re.search(
|
| 472 |
+
rf'"source_graph_edges"\s*:\s*{source_edges}\b',
|
| 473 |
+
text,
|
| 474 |
+
):
|
| 475 |
+
raise GraphArtifactError(
|
| 476 |
+
f"stale graph preview {filename}: missing source_graph_edges {source_edges}",
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
|
| 480 |
def _read_tar_json(tf: tarfile.TarFile, member: tarfile.TarInfo, name: str) -> Any:
|
| 481 |
f = tf.extractfile(member)
|
| 482 |
if f is None:
|
src/wiki_visualize.py
CHANGED
|
@@ -72,12 +72,13 @@ COMMUNITY_COLORS = [
|
|
| 72 |
]
|
| 73 |
|
| 74 |
|
| 75 |
-
def load_graph() -> nx.Graph:
|
| 76 |
"""Load the knowledge graph."""
|
| 77 |
-
if not GRAPH_PATH
|
| 78 |
-
|
|
|
|
| 79 |
sys.exit(1)
|
| 80 |
-
with open(
|
| 81 |
data = json.load(f)
|
| 82 |
# Auto-detect NetworkX 2.x "links" vs 3.x "edges" schema — graph.json
|
| 83 |
# was written with the legacy key on build machines that had the old
|
|
@@ -86,11 +87,12 @@ def load_graph() -> nx.Graph:
|
|
| 86 |
return node_link_graph(data, edges=edges_key)
|
| 87 |
|
| 88 |
|
| 89 |
-
def load_communities() -> dict:
|
| 90 |
"""Load community assignments."""
|
| 91 |
-
if not COMMUNITIES_PATH
|
|
|
|
| 92 |
return {}
|
| 93 |
-
with open(
|
| 94 |
return json.load(f)
|
| 95 |
|
| 96 |
|
|
@@ -101,6 +103,7 @@ def extract_subgraph(
|
|
| 101 |
hops: int = 1,
|
| 102 |
min_weight: float = 0.0,
|
| 103 |
community_id: int | None = None,
|
|
|
|
| 104 |
tag_filter: str | None = None,
|
| 105 |
top_n: int | None = None,
|
| 106 |
) -> nx.Graph:
|
|
@@ -131,8 +134,8 @@ def extract_subgraph(
|
|
| 131 |
frontier = next_frontier
|
| 132 |
|
| 133 |
elif community_id is not None:
|
| 134 |
-
|
| 135 |
-
comm_data =
|
| 136 |
if not comm_data:
|
| 137 |
print(f"Error: community {community_id} not found", file=sys.stderr)
|
| 138 |
return nx.Graph()
|
|
@@ -177,11 +180,23 @@ def compute_layout(G: nx.Graph) -> dict[str, tuple[float, float]]:
|
|
| 177 |
return nx.spring_layout(G, k=2.0 / math.sqrt(max(G.number_of_nodes(), 1)), iterations=50, seed=42)
|
| 178 |
|
| 179 |
|
| 180 |
-
def build_html_with_filters(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
"""Build a self-contained HTML page with sidebar filter controls."""
|
| 182 |
# Prepare node data as JSON for the JS frontend
|
| 183 |
nodes_data = []
|
| 184 |
-
communities = load_communities()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
node_community: dict[str, int] = {}
|
| 186 |
for cid, comm_data in communities.get("communities", {}).items():
|
| 187 |
for member in comm_data.get("members", []):
|
|
@@ -217,10 +232,16 @@ def build_html_with_filters(G: nx.Graph, pos: dict, title: str = "Knowledge Grap
|
|
| 217 |
|
| 218 |
top_tags = sorted(tag_counts.items(), key=lambda x: -x[1])[:25]
|
| 219 |
safe_title = html.escape(title)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
|
| 221 |
return f"""<!DOCTYPE html>
|
| 222 |
<html><head><meta charset="utf-8">
|
| 223 |
<title>{safe_title}</title>
|
|
|
|
| 224 |
<!-- Pinned to an explicit version (not -latest) so served content can't change
|
| 225 |
silently. A real SRI hash would be better but must be generated from the
|
| 226 |
published release — see https://cdn.plot.ly/ for hashes. -->
|
|
@@ -288,6 +309,7 @@ def build_html_with_filters(G: nx.Graph, pos: dict, title: str = "Knowledge Grap
|
|
| 288 |
const NODES = {_safe_json_for_script(nodes_data)};
|
| 289 |
const EDGES = {_safe_json_for_script(edges_data)};
|
| 290 |
const TYPE_COLORS = {_safe_json_for_script(TYPE_COLORS)};
|
|
|
|
| 291 |
const COMM_COLORS = ["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#14b8a6","#f43f5e","#84cc16","#0ea5e9","#a855f7","#e11d48","#10b981"];
|
| 292 |
|
| 293 |
function esc(s) {{ return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,'''); }}
|
|
@@ -668,9 +690,16 @@ def main() -> None:
|
|
| 668 |
parser.add_argument("--top", type=int, help="Show only the top-N most connected nodes")
|
| 669 |
parser.add_argument("--output", help="Save to HTML file instead of opening browser")
|
| 670 |
parser.add_argument("--stats", action="store_true", help="Print graph stats and exit")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 671 |
args = parser.parse_args()
|
| 672 |
|
| 673 |
-
G = load_graph()
|
|
|
|
| 674 |
|
| 675 |
if args.stats:
|
| 676 |
print(f"Full graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")
|
|
@@ -681,7 +710,6 @@ def main() -> None:
|
|
| 681 |
print("\nTop 10 by connections:")
|
| 682 |
for n in top:
|
| 683 |
print(f" {G.nodes[n].get('label', n)} ({G.degree(n)} connections)")
|
| 684 |
-
communities = load_communities()
|
| 685 |
print(f"\nCommunities: {len(communities.get('communities', {}))}")
|
| 686 |
return
|
| 687 |
|
|
@@ -699,6 +727,7 @@ def main() -> None:
|
|
| 699 |
hops=args.hops,
|
| 700 |
min_weight=args.min_weight,
|
| 701 |
community_id=args.community,
|
|
|
|
| 702 |
tag_filter=args.tag,
|
| 703 |
top_n=args.top,
|
| 704 |
)
|
|
@@ -724,7 +753,19 @@ def main() -> None:
|
|
| 724 |
# Layout + render with embedded filter sidebar
|
| 725 |
pos = compute_layout(sub)
|
| 726 |
output_path = args.output or "graph-view.html"
|
| 727 |
-
html = build_html_with_filters(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 728 |
Path(output_path).write_text(html, encoding="utf-8")
|
| 729 |
print(f"Saved to {output_path}")
|
| 730 |
|
|
|
|
| 72 |
]
|
| 73 |
|
| 74 |
|
| 75 |
+
def load_graph(path: Path | str | None = None) -> nx.Graph:
|
| 76 |
"""Load the knowledge graph."""
|
| 77 |
+
graph_path = Path(path) if path is not None else GRAPH_PATH
|
| 78 |
+
if not graph_path.exists():
|
| 79 |
+
print(f"Error: {graph_path} not found. Run wiki_graphify.py first.", file=sys.stderr)
|
| 80 |
sys.exit(1)
|
| 81 |
+
with open(graph_path, encoding="utf-8") as f:
|
| 82 |
data = json.load(f)
|
| 83 |
# Auto-detect NetworkX 2.x "links" vs 3.x "edges" schema — graph.json
|
| 84 |
# was written with the legacy key on build machines that had the old
|
|
|
|
| 87 |
return node_link_graph(data, edges=edges_key)
|
| 88 |
|
| 89 |
|
| 90 |
+
def load_communities(path: Path | str | None = None) -> dict:
|
| 91 |
"""Load community assignments."""
|
| 92 |
+
communities_path = Path(path) if path is not None else COMMUNITIES_PATH
|
| 93 |
+
if not communities_path.exists():
|
| 94 |
return {}
|
| 95 |
+
with open(communities_path, encoding="utf-8") as f:
|
| 96 |
return json.load(f)
|
| 97 |
|
| 98 |
|
|
|
|
| 103 |
hops: int = 1,
|
| 104 |
min_weight: float = 0.0,
|
| 105 |
community_id: int | None = None,
|
| 106 |
+
communities: dict | None = None,
|
| 107 |
tag_filter: str | None = None,
|
| 108 |
top_n: int | None = None,
|
| 109 |
) -> nx.Graph:
|
|
|
|
| 134 |
frontier = next_frontier
|
| 135 |
|
| 136 |
elif community_id is not None:
|
| 137 |
+
community_data = communities if communities is not None else load_communities()
|
| 138 |
+
comm_data = community_data.get("communities", {}).get(str(community_id))
|
| 139 |
if not comm_data:
|
| 140 |
print(f"Error: community {community_id} not found", file=sys.stderr)
|
| 141 |
return nx.Graph()
|
|
|
|
| 180 |
return nx.spring_layout(G, k=2.0 / math.sqrt(max(G.number_of_nodes(), 1)), iterations=50, seed=42)
|
| 181 |
|
| 182 |
|
| 183 |
+
def build_html_with_filters(
|
| 184 |
+
G: nx.Graph,
|
| 185 |
+
pos: dict,
|
| 186 |
+
title: str = "Knowledge Graph",
|
| 187 |
+
*,
|
| 188 |
+
communities: dict | None = None,
|
| 189 |
+
metadata: dict | None = None,
|
| 190 |
+
) -> str:
|
| 191 |
"""Build a self-contained HTML page with sidebar filter controls."""
|
| 192 |
# Prepare node data as JSON for the JS frontend
|
| 193 |
nodes_data = []
|
| 194 |
+
communities = communities if communities is not None else load_communities()
|
| 195 |
+
metadata = dict(metadata or {})
|
| 196 |
+
if "export_id" not in metadata and G.graph.get("export_id"):
|
| 197 |
+
metadata["export_id"] = G.graph.get("export_id")
|
| 198 |
+
metadata.setdefault("nodes", G.number_of_nodes())
|
| 199 |
+
metadata.setdefault("edges", G.number_of_edges())
|
| 200 |
node_community: dict[str, int] = {}
|
| 201 |
for cid, comm_data in communities.get("communities", {}).items():
|
| 202 |
for member in comm_data.get("members", []):
|
|
|
|
| 232 |
|
| 233 |
top_tags = sorted(tag_counts.items(), key=lambda x: -x[1])[:25]
|
| 234 |
safe_title = html.escape(title)
|
| 235 |
+
export_id = str(metadata.get("export_id") or "")
|
| 236 |
+
export_meta = (
|
| 237 |
+
f'<meta name="ctx-graph-export-id" content="{html.escape(export_id, quote=True)}">'
|
| 238 |
+
if export_id else ""
|
| 239 |
+
)
|
| 240 |
|
| 241 |
return f"""<!DOCTYPE html>
|
| 242 |
<html><head><meta charset="utf-8">
|
| 243 |
<title>{safe_title}</title>
|
| 244 |
+
{export_meta}
|
| 245 |
<!-- Pinned to an explicit version (not -latest) so served content can't change
|
| 246 |
silently. A real SRI hash would be better but must be generated from the
|
| 247 |
published release — see https://cdn.plot.ly/ for hashes. -->
|
|
|
|
| 309 |
const NODES = {_safe_json_for_script(nodes_data)};
|
| 310 |
const EDGES = {_safe_json_for_script(edges_data)};
|
| 311 |
const TYPE_COLORS = {_safe_json_for_script(TYPE_COLORS)};
|
| 312 |
+
const CTX_GRAPH_METADATA = {_safe_json_for_script(metadata)};
|
| 313 |
const COMM_COLORS = ["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#14b8a6","#f43f5e","#84cc16","#0ea5e9","#a855f7","#e11d48","#10b981"];
|
| 314 |
|
| 315 |
function esc(s) {{ return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,'''); }}
|
|
|
|
| 690 |
parser.add_argument("--top", type=int, help="Show only the top-N most connected nodes")
|
| 691 |
parser.add_argument("--output", help="Save to HTML file instead of opening browser")
|
| 692 |
parser.add_argument("--stats", action="store_true", help="Print graph stats and exit")
|
| 693 |
+
parser.add_argument("--graph-json", type=Path, help="Load this graph.json instead of ~/.claude")
|
| 694 |
+
parser.add_argument(
|
| 695 |
+
"--communities-json",
|
| 696 |
+
type=Path,
|
| 697 |
+
help="Load this communities.json instead of ~/.claude",
|
| 698 |
+
)
|
| 699 |
args = parser.parse_args()
|
| 700 |
|
| 701 |
+
G = load_graph(args.graph_json)
|
| 702 |
+
communities = load_communities(args.communities_json)
|
| 703 |
|
| 704 |
if args.stats:
|
| 705 |
print(f"Full graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")
|
|
|
|
| 710 |
print("\nTop 10 by connections:")
|
| 711 |
for n in top:
|
| 712 |
print(f" {G.nodes[n].get('label', n)} ({G.degree(n)} connections)")
|
|
|
|
| 713 |
print(f"\nCommunities: {len(communities.get('communities', {}))}")
|
| 714 |
return
|
| 715 |
|
|
|
|
| 727 |
hops=args.hops,
|
| 728 |
min_weight=args.min_weight,
|
| 729 |
community_id=args.community,
|
| 730 |
+
communities=communities,
|
| 731 |
tag_filter=args.tag,
|
| 732 |
top_n=args.top,
|
| 733 |
)
|
|
|
|
| 753 |
# Layout + render with embedded filter sidebar
|
| 754 |
pos = compute_layout(sub)
|
| 755 |
output_path = args.output or "graph-view.html"
|
| 756 |
+
html = build_html_with_filters(
|
| 757 |
+
sub,
|
| 758 |
+
pos,
|
| 759 |
+
title=title,
|
| 760 |
+
communities=communities,
|
| 761 |
+
metadata={
|
| 762 |
+
"export_id": G.graph.get("export_id"),
|
| 763 |
+
"source_graph_nodes": G.number_of_nodes(),
|
| 764 |
+
"source_graph_edges": G.number_of_edges(),
|
| 765 |
+
"view_nodes": sub.number_of_nodes(),
|
| 766 |
+
"view_edges": sub.number_of_edges(),
|
| 767 |
+
},
|
| 768 |
+
)
|
| 769 |
Path(output_path).write_text(html, encoding="utf-8")
|
| 770 |
print(f"Saved to {output_path}")
|
| 771 |
|