Sync ctx 03af985 (part 2)
Browse filesGitHub commit: 03af985401f8dd95b559ecb86c10322a86d14af5
This view is limited to 50 files because it contains too many changes. See raw diff
- mkdocs.yml +3 -2
- pyproject.toml +27 -4
- scripts/audit_backup.py +9 -9
- scripts/build_dashboard_graph_index.py +1 -1
- scripts/ci_classifier.py +24 -0
- scripts/ci_no_test_policy.py +11 -17
- scripts/ci_preflight.py +28 -10
- scripts/ci_required.py +12 -0
- scripts/clean_host_contract.py +1 -0
- scripts/dashboard_smoke.py +169 -0
- scripts/pack_full_wiki_tar.py +260 -0
- scripts/prune_skillspector_wiki.py +590 -0
- scripts/sync_huggingface.py +56 -61
- skills/repo-stats-autoupdate/SKILL.md +3 -2
- src/__init__.py +1 -1
- src/agent_add.py +40 -14
- src/backup_mirror.py +0 -6
- src/catalog_builder.py +39 -10
- src/config.json +70 -0
- src/ctx/__init__.py +1 -1
- src/ctx/adapters/claude_code/hooks/context_monitor.py +6 -1
- src/ctx/adapters/claude_code/install/mcp_install.py +22 -2
- src/ctx/adapters/claude_code/install/skill_unload.py +279 -80
- src/ctx/adapters/claude_code/install/skillspector_scan.py +12 -181
- src/ctx/adapters/generic/ctx_core_tools.py +353 -67
- src/ctx/adapters/generic/runtime_lifecycle.py +61 -2
- src/ctx/api.py +170 -27
- src/ctx/assets/__init__.py +1 -0
- src/ctx/assets/monitor-docs.js +91 -0
- src/ctx/assets/monitor-manage.js +156 -0
- src/ctx/assets/monitor-nav.js +76 -0
- src/ctx/assets/monitor.css +424 -0
- src/ctx/cli/run.py +444 -220
- src/ctx/cli/telemetry.py +388 -0
- src/ctx/config.json +70 -0
- src/ctx/core/entity_types.py +54 -0
- src/ctx/core/graph/graph_packs.py +797 -0
- src/ctx/core/graph/graph_store.py +561 -0
- src/ctx/core/graph/incremental_attach.py +230 -6
- src/ctx/core/graph/incremental_shadow.py +10 -2
- src/ctx/core/graph/resolve_graph.py +42 -2
- src/ctx/core/graph/vector_index.py +146 -0
- src/ctx/core/quality/dedup_check.py +75 -0
- src/ctx/core/quality/skillspector_audit.py +888 -0
- src/ctx/core/quality/skillspector_monitor.py +301 -0
- src/ctx/core/quality/skillspector_remediation.py +215 -0
- src/ctx/core/quality/skillspector_service.py +259 -0
- src/ctx/core/resolve/resolve_skills.py +33 -6
- src/ctx/core/wiki/pack_compaction.py +654 -0
- src/ctx/core/wiki/pack_validation.py +264 -0
mkdocs.yml
CHANGED
|
@@ -5,8 +5,8 @@
|
|
| 5 |
# Publish: handled by .github/workflows/docs.yml on push to main.
|
| 6 |
site_name: ctx
|
| 7 |
site_description: >-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
site_url: https://stevesolun.github.io/ctx/
|
| 11 |
repo_url: https://github.com/stevesolun/ctx
|
| 12 |
repo_name: stevesolun/ctx
|
|
@@ -102,6 +102,7 @@ nav:
|
|
| 102 |
- Hugging Face publish: huggingface-publish.md
|
| 103 |
- Entity onboarding: entity-onboarding.md
|
| 104 |
- Dashboard: dashboard.md
|
|
|
|
| 105 |
- Harness:
|
| 106 |
- Attach to hosts: harness/attaching-to-hosts.md
|
| 107 |
- Clean-host contract: harness/clean-host-contract.md
|
|
|
|
| 5 |
# Publish: handled by .github/workflows/docs.yml on push to main.
|
| 6 |
site_name: ctx
|
| 7 |
site_description: >-
|
| 8 |
+
Not a catalog: a repo-aware recommendation layer that loads the right
|
| 9 |
+
skills, agents, MCPs, and harnesses from your tools or the shipped graph.
|
| 10 |
site_url: https://stevesolun.github.io/ctx/
|
| 11 |
repo_url: https://github.com/stevesolun/ctx
|
| 12 |
repo_name: stevesolun/ctx
|
|
|
|
| 102 |
- Hugging Face publish: huggingface-publish.md
|
| 103 |
- Entity onboarding: entity-onboarding.md
|
| 104 |
- Dashboard: dashboard.md
|
| 105 |
+
- Telemetry: telemetry.md
|
| 106 |
- Harness:
|
| 107 |
- Attach to hosts: harness/attaching-to-hosts.md
|
| 108 |
- Clean-host contract: harness/clean-host-contract.md
|
pyproject.toml
CHANGED
|
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
|
|
| 4 |
|
| 5 |
[project]
|
| 6 |
name = "claude-ctx"
|
| 7 |
-
version = "1.0.
|
| 8 |
-
description = "
|
| 9 |
authors = [{ name = "Steve Solun" }]
|
| 10 |
license = "MIT"
|
| 11 |
readme = "README.md"
|
|
@@ -15,7 +15,6 @@ dependencies = [
|
|
| 15 |
"markdown>=3.6,<4",
|
| 16 |
"networkx>=3,<4",
|
| 17 |
"numpy>=1.24,<3",
|
| 18 |
-
"plotly>=5,<7",
|
| 19 |
"pymdown-extensions>=10,<11",
|
| 20 |
"pyyaml>=6,<7",
|
| 21 |
]
|
|
@@ -42,12 +41,16 @@ ctx-toolbox = "toolbox:main"
|
|
| 42 |
ctx-lifecycle = "ctx_lifecycle:main"
|
| 43 |
ctx-skill-add = "skill_add:main"
|
| 44 |
ctx-skill-install = "ctx.adapters.claude_code.install.skill_install:main"
|
|
|
|
| 45 |
ctx-skill-mirror = "skill_mirror:main"
|
| 46 |
ctx-bundle-suggest = "ctx.adapters.claude_code.hooks.bundle_orchestrator:main"
|
| 47 |
ctx-recommend = "ctx.cli.recommend:main"
|
|
|
|
|
|
|
| 48 |
ctx-agent-add = "agent_add:main"
|
| 49 |
ctx-agent-mirror = "agent_mirror:main"
|
| 50 |
ctx-agent-install = "ctx.adapters.claude_code.install.agent_install:main"
|
|
|
|
| 51 |
ctx-harness-add = "harness_add:main"
|
| 52 |
ctx-harness-install = "harness_install:main"
|
| 53 |
ctx-mcp-add = "mcp_add:main"
|
|
@@ -60,6 +63,8 @@ ctx-mcp-quality = "mcp_quality:main"
|
|
| 60 |
ctx-mcp-rebuild-index = "mcp_rebuild_index:main"
|
| 61 |
ctx-wiki-graphify = "ctx.core.wiki.wiki_graphify:main"
|
| 62 |
ctx-wiki-worker = "ctx.core.wiki.wiki_queue_worker:main"
|
|
|
|
|
|
|
| 63 |
ctx-incremental-attach = "ctx.core.graph.incremental_attach:main"
|
| 64 |
ctx-incremental-shadow = "ctx.core.graph.incremental_shadow:main"
|
| 65 |
ctx-source-registry = "ctx.core.source_registry:main"
|
|
@@ -72,6 +77,11 @@ ctx-dedup-check = "ctx.core.quality.dedup_check:main"
|
|
| 72 |
# keywords + the existing tag vocabulary. Report-only by default;
|
| 73 |
# `--apply` to write.
|
| 74 |
ctx-tag-backfill = "ctx.core.quality.tag_backfill:main"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
# Plan 001 phase H7: the generic harness CLI — `ctx run`,
|
| 76 |
# `ctx resume`, `ctx sessions`. Ships v1 of the model-agnostic
|
| 77 |
# harness; requires the [harness] optional dep for LiteLLM.
|
|
@@ -89,11 +99,15 @@ dev = [
|
|
| 89 |
"pytest-cov>=5",
|
| 90 |
"hypothesis>=6",
|
| 91 |
"mypy>=1.8",
|
|
|
|
| 92 |
"ruff>=0.4",
|
| 93 |
]
|
| 94 |
browser = [
|
| 95 |
"playwright>=1.52",
|
| 96 |
]
|
|
|
|
|
|
|
|
|
|
| 97 |
embeddings = [
|
| 98 |
"sentence-transformers>=2,<4",
|
| 99 |
"torch>=2,<3",
|
|
@@ -101,6 +115,9 @@ embeddings = [
|
|
| 101 |
ann = [
|
| 102 |
"hnswlib>=0.8,<0.9; platform_python_implementation == 'CPython'",
|
| 103 |
]
|
|
|
|
|
|
|
|
|
|
| 104 |
harness = [
|
| 105 |
# LiteLLM is the substrate for the model-agnostic harness
|
| 106 |
# (ctx.adapters.generic.providers). Every remote provider —
|
|
@@ -195,6 +212,7 @@ py-modules = [
|
|
| 195 |
packages = [
|
| 196 |
"mcp_sources",
|
| 197 |
"ctx",
|
|
|
|
| 198 |
"ctx.core",
|
| 199 |
"ctx.core.graph",
|
| 200 |
"ctx.core.quality",
|
|
@@ -209,12 +227,17 @@ packages = [
|
|
| 209 |
"ctx.adapters.generic.providers",
|
| 210 |
"ctx.adapters.generic.tools",
|
| 211 |
"ctx.cli",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
"ctx.mcp_server",
|
|
|
|
| 213 |
"ctx.utils",
|
| 214 |
]
|
| 215 |
|
| 216 |
[tool.setuptools.package-data]
|
| 217 |
-
ctx = ["config.json", "skill-registry.json"]
|
| 218 |
|
| 219 |
[tool.pytest.ini_options]
|
| 220 |
testpaths = ["src/tests"]
|
|
|
|
| 4 |
|
| 5 |
[project]
|
| 6 |
name = "claude-ctx"
|
| 7 |
+
version = "1.0.20"
|
| 8 |
+
description = "Not an Amazon-style catalog: a recommendation layer for loading the right skills, agents, MCPs, and harnesses at the right development moment"
|
| 9 |
authors = [{ name = "Steve Solun" }]
|
| 10 |
license = "MIT"
|
| 11 |
readme = "README.md"
|
|
|
|
| 15 |
"markdown>=3.6,<4",
|
| 16 |
"networkx>=3,<4",
|
| 17 |
"numpy>=1.24,<3",
|
|
|
|
| 18 |
"pymdown-extensions>=10,<11",
|
| 19 |
"pyyaml>=6,<7",
|
| 20 |
]
|
|
|
|
| 41 |
ctx-lifecycle = "ctx_lifecycle:main"
|
| 42 |
ctx-skill-add = "skill_add:main"
|
| 43 |
ctx-skill-install = "ctx.adapters.claude_code.install.skill_install:main"
|
| 44 |
+
ctx-skill-unload = "ctx.adapters.claude_code.install.skill_unload:skill_main"
|
| 45 |
ctx-skill-mirror = "skill_mirror:main"
|
| 46 |
ctx-bundle-suggest = "ctx.adapters.claude_code.hooks.bundle_orchestrator:main"
|
| 47 |
ctx-recommend = "ctx.cli.recommend:main"
|
| 48 |
+
ctx-telemetry-export = "ctx.cli.telemetry:main"
|
| 49 |
+
ctx-telemetry-retention = "ctx.cli.telemetry:retention_main"
|
| 50 |
ctx-agent-add = "agent_add:main"
|
| 51 |
ctx-agent-mirror = "agent_mirror:main"
|
| 52 |
ctx-agent-install = "ctx.adapters.claude_code.install.agent_install:main"
|
| 53 |
+
ctx-agent-unload = "ctx.adapters.claude_code.install.skill_unload:agent_main"
|
| 54 |
ctx-harness-add = "harness_add:main"
|
| 55 |
ctx-harness-install = "harness_install:main"
|
| 56 |
ctx-mcp-add = "mcp_add:main"
|
|
|
|
| 63 |
ctx-mcp-rebuild-index = "mcp_rebuild_index:main"
|
| 64 |
ctx-wiki-graphify = "ctx.core.wiki.wiki_graphify:main"
|
| 65 |
ctx-wiki-worker = "ctx.core.wiki.wiki_queue_worker:main"
|
| 66 |
+
ctx-graph-store = "ctx.core.graph.graph_store:main"
|
| 67 |
+
ctx-pack-compact = "ctx.core.wiki.pack_compaction:main"
|
| 68 |
ctx-incremental-attach = "ctx.core.graph.incremental_attach:main"
|
| 69 |
ctx-incremental-shadow = "ctx.core.graph.incremental_shadow:main"
|
| 70 |
ctx-source-registry = "ctx.core.source_registry:main"
|
|
|
|
| 77 |
# keywords + the existing tag vocabulary. Report-only by default;
|
| 78 |
# `--apply` to write.
|
| 79 |
ctx-tag-backfill = "ctx.core.quality.tag_backfill:main"
|
| 80 |
+
# Optional release-audit helper. SkillSpector itself remains external because
|
| 81 |
+
# it currently requires Python 3.12+ while ctx supports Python 3.11.
|
| 82 |
+
ctx-skillspector-scan = "ctx.core.quality.skillspector_service:main"
|
| 83 |
+
ctx-skillspector-audit = "ctx.core.quality.skillspector_audit:main"
|
| 84 |
+
ctx-skillspector-remediation = "ctx.core.quality.skillspector_remediation:main"
|
| 85 |
# Plan 001 phase H7: the generic harness CLI — `ctx run`,
|
| 86 |
# `ctx resume`, `ctx sessions`. Ships v1 of the model-agnostic
|
| 87 |
# harness; requires the [harness] optional dep for LiteLLM.
|
|
|
|
| 99 |
"pytest-cov>=5",
|
| 100 |
"hypothesis>=6",
|
| 101 |
"mypy>=1.8",
|
| 102 |
+
"types-PyYAML>=6.0",
|
| 103 |
"ruff>=0.4",
|
| 104 |
]
|
| 105 |
browser = [
|
| 106 |
"playwright>=1.52",
|
| 107 |
]
|
| 108 |
+
viz = [
|
| 109 |
+
"plotly>=5,<7",
|
| 110 |
+
]
|
| 111 |
embeddings = [
|
| 112 |
"sentence-transformers>=2,<4",
|
| 113 |
"torch>=2,<3",
|
|
|
|
| 115 |
ann = [
|
| 116 |
"hnswlib>=0.8,<0.9; platform_python_implementation == 'CPython'",
|
| 117 |
]
|
| 118 |
+
gcf = [
|
| 119 |
+
"gcf-python>=2.1.0,<3",
|
| 120 |
+
]
|
| 121 |
harness = [
|
| 122 |
# LiteLLM is the substrate for the model-agnostic harness
|
| 123 |
# (ctx.adapters.generic.providers). Every remote provider —
|
|
|
|
| 212 |
packages = [
|
| 213 |
"mcp_sources",
|
| 214 |
"ctx",
|
| 215 |
+
"ctx.assets",
|
| 216 |
"ctx.core",
|
| 217 |
"ctx.core.graph",
|
| 218 |
"ctx.core.quality",
|
|
|
|
| 227 |
"ctx.adapters.generic.providers",
|
| 228 |
"ctx.adapters.generic.tools",
|
| 229 |
"ctx.cli",
|
| 230 |
+
"ctx.monitor",
|
| 231 |
+
"ctx.monitor.api",
|
| 232 |
+
"ctx.monitor.pages",
|
| 233 |
+
"ctx.monitor.services",
|
| 234 |
"ctx.mcp_server",
|
| 235 |
+
"ctx.telemetry",
|
| 236 |
"ctx.utils",
|
| 237 |
]
|
| 238 |
|
| 239 |
[tool.setuptools.package-data]
|
| 240 |
+
ctx = ["config.json", "skill-registry.json", "assets/*.js", "assets/*.css"]
|
| 241 |
|
| 242 |
[tool.pytest.ini_options]
|
| 243 |
testpaths = ["src/tests"]
|
scripts/audit_backup.py
CHANGED
|
@@ -19,7 +19,7 @@ def latest_snapshot() -> Path:
|
|
| 19 |
|
| 20 |
def main() -> int:
|
| 21 |
snap = Path(sys.argv[1]) if len(sys.argv) > 1 else latest_snapshot()
|
| 22 |
-
manifest = json.loads((snap / "manifest.json").read_text(encoding="utf-8"))
|
| 23 |
|
| 24 |
print(f"snapshot: {snap}")
|
| 25 |
print(f"entries: {len(manifest['entries'])}")
|
|
@@ -37,8 +37,8 @@ def main() -> int:
|
|
| 37 |
for e in manifest["entries"]:
|
| 38 |
head = e["dest"].replace("\\", "/").split("/", 1)[0]
|
| 39 |
roots[head] += 1
|
| 40 |
-
for
|
| 41 |
-
print(f" {
|
| 42 |
|
| 43 |
# Audit what's in ~/.claude but NOT in the backup.
|
| 44 |
print("\n--- Candidate files in ~/.claude NOT backed up ---")
|
|
@@ -51,13 +51,13 @@ def main() -> int:
|
|
| 51 |
CLAUDE_HOME / "claude.json",
|
| 52 |
CLAUDE_HOME / ".claude.json",
|
| 53 |
]
|
| 54 |
-
for
|
| 55 |
-
if
|
| 56 |
-
print(f" MISSING: {
|
| 57 |
-
elif
|
| 58 |
-
print(f" OK: {
|
| 59 |
else:
|
| 60 |
-
print(f" absent: {
|
| 61 |
|
| 62 |
# Also check common config locations.
|
| 63 |
cfg_glob = list((CLAUDE_HOME).glob("*.json")) + list((CLAUDE_HOME).glob("*.md"))
|
|
|
|
| 19 |
|
| 20 |
def main() -> int:
|
| 21 |
snap = Path(sys.argv[1]) if len(sys.argv) > 1 else latest_snapshot()
|
| 22 |
+
manifest = json.loads((snap / "manifest.json").read_text(encoding="utf-8-sig"))
|
| 23 |
|
| 24 |
print(f"snapshot: {snap}")
|
| 25 |
print(f"entries: {len(manifest['entries'])}")
|
|
|
|
| 37 |
for e in manifest["entries"]:
|
| 38 |
head = e["dest"].replace("\\", "/").split("/", 1)[0]
|
| 39 |
roots[head] += 1
|
| 40 |
+
for root_name, count in roots.most_common():
|
| 41 |
+
print(f" {root_name:<32} {count:>5} files")
|
| 42 |
|
| 43 |
# Audit what's in ~/.claude but NOT in the backup.
|
| 44 |
print("\n--- Candidate files in ~/.claude NOT backed up ---")
|
|
|
|
| 51 |
CLAUDE_HOME / "claude.json",
|
| 52 |
CLAUDE_HOME / ".claude.json",
|
| 53 |
]
|
| 54 |
+
for candidate in candidates:
|
| 55 |
+
if candidate.is_file() and candidate.resolve() not in backed_up_sources:
|
| 56 |
+
print(f" MISSING: {candidate} ({candidate.stat().st_size}B)")
|
| 57 |
+
elif candidate.is_file():
|
| 58 |
+
print(f" OK: {candidate}")
|
| 59 |
else:
|
| 60 |
+
print(f" absent: {candidate}")
|
| 61 |
|
| 62 |
# Also check common config locations.
|
| 63 |
cfg_glob = list((CLAUDE_HOME).glob("*.json")) + list((CLAUDE_HOME).glob("*.md"))
|
scripts/build_dashboard_graph_index.py
CHANGED
|
@@ -20,7 +20,7 @@ def _graph_edges(data: dict[str, Any]) -> list[dict[str, Any]]:
|
|
| 20 |
|
| 21 |
|
| 22 |
def build_dashboard_index(graph_json: Path, output: Path, *, top_k: int = 40) -> None:
|
| 23 |
-
data = json.loads(graph_json.read_text(encoding="utf-8"))
|
| 24 |
nodes_raw = [item for item in data.get("nodes", []) if isinstance(item, dict)]
|
| 25 |
edges_raw = _graph_edges(data)
|
| 26 |
nodes: dict[str, dict[str, Any]] = {}
|
|
|
|
| 20 |
|
| 21 |
|
| 22 |
def build_dashboard_index(graph_json: Path, output: Path, *, top_k: int = 40) -> None:
|
| 23 |
+
data = json.loads(graph_json.read_text(encoding="utf-8-sig"))
|
| 24 |
nodes_raw = [item for item in data.get("nodes", []) if isinstance(item, dict)]
|
| 25 |
edges_raw = _graph_edges(data)
|
| 26 |
nodes: dict[str, dict[str, Any]] = {}
|
scripts/ci_classifier.py
CHANGED
|
@@ -19,6 +19,7 @@ OUTPUT_NAMES = (
|
|
| 19 |
"package_changed",
|
| 20 |
"similarity_changed",
|
| 21 |
"source_changed",
|
|
|
|
| 22 |
)
|
| 23 |
|
| 24 |
DOCS_PATTERNS = (
|
|
@@ -76,6 +77,27 @@ SIMILARITY_PATTERNS = (
|
|
| 76 |
"src/intake_gate.py",
|
| 77 |
"src/tests/test_similarity_precision_recall.py",
|
| 78 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
|
| 81 |
def _matches(path: str, patterns: Iterable[str]) -> bool:
|
|
@@ -117,6 +139,8 @@ def classify_paths(paths: Iterable[str]) -> dict[str, bool]:
|
|
| 117 |
or any(_matches(path, SIMILARITY_PATTERNS) for path in files),
|
| 118 |
"source_changed": ci_changed
|
| 119 |
or any(_matches(path, SOURCE_PATTERNS) for path in files),
|
|
|
|
|
|
|
| 120 |
}
|
| 121 |
|
| 122 |
|
|
|
|
| 19 |
"package_changed",
|
| 20 |
"similarity_changed",
|
| 21 |
"source_changed",
|
| 22 |
+
"telemetry_changed",
|
| 23 |
)
|
| 24 |
|
| 25 |
DOCS_PATTERNS = (
|
|
|
|
| 77 |
"src/intake_gate.py",
|
| 78 |
"src/tests/test_similarity_precision_recall.py",
|
| 79 |
)
|
| 80 |
+
TELEMETRY_PATTERNS = (
|
| 81 |
+
".github/workflows/test.yml",
|
| 82 |
+
"docs/telemetry.md",
|
| 83 |
+
"scripts/ci_classifier.py",
|
| 84 |
+
"scripts/ci_preflight.py",
|
| 85 |
+
"scripts/ci_required.py",
|
| 86 |
+
"src/config.json",
|
| 87 |
+
"src/ctx/config.json",
|
| 88 |
+
"src/ctx/adapters/generic/ctx_core_tools.py",
|
| 89 |
+
"src/ctx/adapters/generic/runtime_lifecycle.py",
|
| 90 |
+
"src/ctx/api.py",
|
| 91 |
+
"src/ctx/cli/run.py",
|
| 92 |
+
"src/ctx/cli/telemetry.py",
|
| 93 |
+
"src/ctx/mcp_server/server.py",
|
| 94 |
+
"src/ctx/telemetry/**",
|
| 95 |
+
"src/tests/test_enterprise_telemetry.py",
|
| 96 |
+
"src/tests/test_harness_cli_run.py",
|
| 97 |
+
"src/tests/test_harness_ctx_core.py",
|
| 98 |
+
"src/tests/test_mcp_server.py",
|
| 99 |
+
"src/tests/test_public_api.py",
|
| 100 |
+
)
|
| 101 |
|
| 102 |
|
| 103 |
def _matches(path: str, patterns: Iterable[str]) -> bool:
|
|
|
|
| 139 |
or any(_matches(path, SIMILARITY_PATTERNS) for path in files),
|
| 140 |
"source_changed": ci_changed
|
| 141 |
or any(_matches(path, SOURCE_PATTERNS) for path in files),
|
| 142 |
+
"telemetry_changed": ci_changed
|
| 143 |
+
or any(_matches(path, TELEMETRY_PATTERNS) for path in files),
|
| 144 |
}
|
| 145 |
|
| 146 |
|
scripts/ci_no_test_policy.py
CHANGED
|
@@ -21,11 +21,9 @@ RELEASE_GENERATED_STATS_FILES = {
|
|
| 21 |
"docs/knowledge-graph.md",
|
| 22 |
}
|
| 23 |
VERSION_LINE_RE = re.compile(r'version = "\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?"')
|
| 24 |
-
INIT_VERSION_LINE_RE = re.compile(
|
| 25 |
-
r'__version__ = "\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?"'
|
| 26 |
-
)
|
| 27 |
TEST_COUNT_STATS_RE = re.compile(
|
| 28 |
-
r".*(Tests-\d+
|
| 29 |
)
|
| 30 |
RELEASE_DOCS_LINE_RE = re.compile(r"\*\*v\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?\*\*.*")
|
| 31 |
KNOWLEDGE_GRAPH_STATS_LINE_RE = re.compile(
|
|
@@ -59,10 +57,7 @@ def is_contract_file(path: str) -> bool:
|
|
| 59 |
or path.startswith("scripts/ci_")
|
| 60 |
or path == "scripts/clean_host_contract.py"
|
| 61 |
or path == "pyproject.toml"
|
| 62 |
-
or (
|
| 63 |
-
path.startswith(".github/workflows/")
|
| 64 |
-
and path.endswith((".yml", ".yaml"))
|
| 65 |
-
)
|
| 66 |
) and not path.startswith("src/tests/")
|
| 67 |
|
| 68 |
|
|
@@ -89,11 +84,13 @@ def is_release_metadata_only(
|
|
| 89 |
if not line.startswith(("+", "-")) or line.startswith(("+++", "---")):
|
| 90 |
continue
|
| 91 |
text = line[1:].strip()
|
| 92 |
-
if
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
| 97 |
):
|
| 98 |
return False
|
| 99 |
continue
|
|
@@ -150,10 +147,7 @@ def _changed_files(base: str, head: str) -> tuple[str, ...]:
|
|
| 150 |
|
| 151 |
|
| 152 |
def _diffs_by_file(base: str, head: str, files: Iterable[str]) -> dict[str, str]:
|
| 153 |
-
return {
|
| 154 |
-
path: _git_text("diff", "--unified=0", base, head, "--", path)
|
| 155 |
-
for path in files
|
| 156 |
-
}
|
| 157 |
|
| 158 |
|
| 159 |
def _parse_labels(raw: str) -> tuple[str, ...]:
|
|
|
|
| 21 |
"docs/knowledge-graph.md",
|
| 22 |
}
|
| 23 |
VERSION_LINE_RE = re.compile(r'version = "\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?"')
|
| 24 |
+
INIT_VERSION_LINE_RE = re.compile(r'__version__ = "\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?"')
|
|
|
|
|
|
|
| 25 |
TEST_COUNT_STATS_RE = re.compile(
|
| 26 |
+
r".*(Tests-\d+_(?:collected|inventory)|[\d,]+ (?:tests collected|test inventory)).*"
|
| 27 |
)
|
| 28 |
RELEASE_DOCS_LINE_RE = re.compile(r"\*\*v\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?\*\*.*")
|
| 29 |
KNOWLEDGE_GRAPH_STATS_LINE_RE = re.compile(
|
|
|
|
| 57 |
or path.startswith("scripts/ci_")
|
| 58 |
or path == "scripts/clean_host_contract.py"
|
| 59 |
or path == "pyproject.toml"
|
| 60 |
+
or (path.startswith(".github/workflows/") and path.endswith((".yml", ".yaml")))
|
|
|
|
|
|
|
|
|
|
| 61 |
) and not path.startswith("src/tests/")
|
| 62 |
|
| 63 |
|
|
|
|
| 84 |
if not line.startswith(("+", "-")) or line.startswith(("+++", "---")):
|
| 85 |
continue
|
| 86 |
text = line[1:].strip()
|
| 87 |
+
if (
|
| 88 |
+
not TEST_COUNT_STATS_RE.fullmatch(text)
|
| 89 |
+
and not (path == "docs/index.md" and RELEASE_DOCS_LINE_RE.fullmatch(text))
|
| 90 |
+
and not (
|
| 91 |
+
path == "docs/knowledge-graph.md"
|
| 92 |
+
and KNOWLEDGE_GRAPH_STATS_LINE_RE.fullmatch(text)
|
| 93 |
+
)
|
| 94 |
):
|
| 95 |
return False
|
| 96 |
continue
|
|
|
|
| 147 |
|
| 148 |
|
| 149 |
def _diffs_by_file(base: str, head: str, files: Iterable[str]) -> dict[str, str]:
|
| 150 |
+
return {path: _git_text("diff", "--unified=0", base, head, "--", path) for path in files}
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
|
| 153 |
def _parse_labels(raw: str) -> tuple[str, ...]:
|
scripts/ci_preflight.py
CHANGED
|
@@ -30,29 +30,29 @@ GRAPH_VALIDATE_ARGS = (
|
|
| 30 |
"graph",
|
| 31 |
"--deep",
|
| 32 |
"--min-nodes",
|
| 33 |
-
"
|
| 34 |
"--min-edges",
|
| 35 |
-
"
|
| 36 |
"--min-skills-sh-nodes",
|
| 37 |
-
"
|
| 38 |
"--min-semantic-edges",
|
| 39 |
"1000000",
|
| 40 |
"--expected-nodes",
|
| 41 |
-
"
|
| 42 |
"--expected-edges",
|
| 43 |
-
"
|
| 44 |
"--expected-semantic-edges",
|
| 45 |
-
"
|
| 46 |
"--expected-harness-nodes",
|
| 47 |
"207",
|
| 48 |
"--expected-skills-sh-nodes",
|
| 49 |
-
"
|
| 50 |
"--expected-skills-sh-catalog-entries",
|
| 51 |
-
"
|
| 52 |
"--expected-skills-sh-converted",
|
| 53 |
-
"
|
| 54 |
"--expected-skill-pages",
|
| 55 |
-
"
|
| 56 |
"--expected-agent-pages",
|
| 57 |
"467",
|
| 58 |
"--expected-mcp-pages",
|
|
@@ -184,6 +184,24 @@ def select_checks(
|
|
| 184 |
Check("docs strict build", (python, "-m", "mkdocs", "build", "--strict"))
|
| 185 |
)
|
| 186 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
if flags["graph_artifact_changed"]:
|
| 188 |
checks.append(Check("graph artifact validation", (python, *GRAPH_VALIDATE_ARGS)))
|
| 189 |
|
|
|
|
| 30 |
"graph",
|
| 31 |
"--deep",
|
| 32 |
"--min-nodes",
|
| 33 |
+
"79000",
|
| 34 |
"--min-edges",
|
| 35 |
+
"1700000",
|
| 36 |
"--min-skills-sh-nodes",
|
| 37 |
+
"67000",
|
| 38 |
"--min-semantic-edges",
|
| 39 |
"1000000",
|
| 40 |
"--expected-nodes",
|
| 41 |
+
"79958",
|
| 42 |
"--expected-edges",
|
| 43 |
+
"1778069",
|
| 44 |
"--expected-semantic-edges",
|
| 45 |
+
"1088763",
|
| 46 |
"--expected-harness-nodes",
|
| 47 |
"207",
|
| 48 |
"--expected-skills-sh-nodes",
|
| 49 |
+
"67028",
|
| 50 |
"--expected-skills-sh-catalog-entries",
|
| 51 |
+
"67024",
|
| 52 |
"--expected-skills-sh-converted",
|
| 53 |
+
"67024",
|
| 54 |
"--expected-skill-pages",
|
| 55 |
+
"68494",
|
| 56 |
"--expected-agent-pages",
|
| 57 |
"467",
|
| 58 |
"--expected-mcp-pages",
|
|
|
|
| 184 |
Check("docs strict build", (python, "-m", "mkdocs", "build", "--strict"))
|
| 185 |
)
|
| 186 |
|
| 187 |
+
if profile == "full" or flags["telemetry_changed"]:
|
| 188 |
+
checks.append(
|
| 189 |
+
Check(
|
| 190 |
+
"telemetry enterprise",
|
| 191 |
+
(
|
| 192 |
+
python,
|
| 193 |
+
"-m",
|
| 194 |
+
"pytest",
|
| 195 |
+
"-q",
|
| 196 |
+
"--no-cov",
|
| 197 |
+
"src/tests/test_enterprise_telemetry.py",
|
| 198 |
+
"src/tests/test_harness_cli_run.py",
|
| 199 |
+
"-k",
|
| 200 |
+
"telemetry or runtime_lifecycle",
|
| 201 |
+
),
|
| 202 |
+
)
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
if flags["graph_artifact_changed"]:
|
| 206 |
checks.append(Check("graph artifact validation", (python, *GRAPH_VALIDATE_ARGS)))
|
| 207 |
|
scripts/ci_required.py
CHANGED
|
@@ -30,6 +30,7 @@ REQUIRED_JOBS = {
|
|
| 30 |
"package-smoke",
|
| 31 |
"similarity-integration",
|
| 32 |
"static",
|
|
|
|
| 33 |
"test",
|
| 34 |
"unit-linux",
|
| 35 |
}
|
|
@@ -75,6 +76,10 @@ def failed_required_jobs(
|
|
| 75 |
event_name == "pull_request"
|
| 76 |
and _job_output(needs, "classify", "similarity_changed") == "true"
|
| 77 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
cheap_pr = docs_only_pr or graph_only_pr
|
| 79 |
for name, details in sorted(needs.items()):
|
| 80 |
result = details.get("result")
|
|
@@ -121,6 +126,13 @@ def failed_required_jobs(
|
|
| 121 |
and _job_output(needs, "classify", "similarity_changed") == "false"
|
| 122 |
):
|
| 123 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
if event_name == "pull_request" and name == "test" and result == "skipped":
|
| 125 |
continue
|
| 126 |
failures[name] = result
|
|
|
|
| 30 |
"package-smoke",
|
| 31 |
"similarity-integration",
|
| 32 |
"static",
|
| 33 |
+
"telemetry-enterprise",
|
| 34 |
"test",
|
| 35 |
"unit-linux",
|
| 36 |
}
|
|
|
|
| 76 |
event_name == "pull_request"
|
| 77 |
and _job_output(needs, "classify", "similarity_changed") == "true"
|
| 78 |
)
|
| 79 |
+
telemetry_changed_pr = (
|
| 80 |
+
event_name == "pull_request"
|
| 81 |
+
and _job_output(needs, "classify", "telemetry_changed") == "true"
|
| 82 |
+
)
|
| 83 |
cheap_pr = docs_only_pr or graph_only_pr
|
| 84 |
for name, details in sorted(needs.items()):
|
| 85 |
result = details.get("result")
|
|
|
|
| 126 |
and _job_output(needs, "classify", "similarity_changed") == "false"
|
| 127 |
):
|
| 128 |
continue
|
| 129 |
+
if (
|
| 130 |
+
event_name == "pull_request"
|
| 131 |
+
and name == "telemetry-enterprise"
|
| 132 |
+
and result == "skipped"
|
| 133 |
+
and not telemetry_changed_pr
|
| 134 |
+
):
|
| 135 |
+
continue
|
| 136 |
if event_name == "pull_request" and name == "test" and result == "skipped":
|
| 137 |
continue
|
| 138 |
failures[name] = result
|
scripts/clean_host_contract.py
CHANGED
|
@@ -179,6 +179,7 @@ def isolated_env(paths: ContractPaths, *, extra_pythonpath: Path | None = None)
|
|
| 179 |
"XDG_CONFIG_HOME": str(paths.xdg_config),
|
| 180 |
"XDG_CACHE_HOME": str(paths.xdg_cache),
|
| 181 |
"PIP_CACHE_DIR": str(paths.pip_cache),
|
|
|
|
| 182 |
"PYTHONUTF8": "1",
|
| 183 |
})
|
| 184 |
if extra_pythonpath is not None:
|
|
|
|
| 179 |
"XDG_CONFIG_HOME": str(paths.xdg_config),
|
| 180 |
"XDG_CACHE_HOME": str(paths.xdg_cache),
|
| 181 |
"PIP_CACHE_DIR": str(paths.pip_cache),
|
| 182 |
+
"CTX_ALLOW_MISSING_GRAPH": "1",
|
| 183 |
"PYTHONUTF8": "1",
|
| 184 |
})
|
| 185 |
if extra_pythonpath is not None:
|
scripts/dashboard_smoke.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import sys
|
| 6 |
+
import time
|
| 7 |
+
import urllib.error
|
| 8 |
+
import urllib.request
|
| 9 |
+
from dataclasses import asdict
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@dataclass(frozen=True)
|
| 14 |
+
class CheckSpec:
|
| 15 |
+
name: str
|
| 16 |
+
path: str
|
| 17 |
+
marker: str
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class CheckResult:
|
| 22 |
+
name: str
|
| 23 |
+
path: str
|
| 24 |
+
status: int
|
| 25 |
+
elapsed: float
|
| 26 |
+
ok: bool
|
| 27 |
+
reason: str
|
| 28 |
+
bytes_read: int
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
DEFAULT_CHECKS = (
|
| 32 |
+
CheckSpec("home", "/", "ctx monitor"),
|
| 33 |
+
CheckSpec("loaded", "/loaded", "Loaded"),
|
| 34 |
+
CheckSpec("skills", "/skills", "Skills"),
|
| 35 |
+
CheckSpec("wiki", "/wiki", "Wiki"),
|
| 36 |
+
CheckSpec("graph", "/graph", "Knowledge graph"),
|
| 37 |
+
CheckSpec("manage", "/manage", "Manage catalog"),
|
| 38 |
+
CheckSpec("harness", "/harness", "Harness Setup"),
|
| 39 |
+
CheckSpec("docs", "/docs", "Docs"),
|
| 40 |
+
CheckSpec("config", "/config", "Config"),
|
| 41 |
+
CheckSpec("status", "/status", "Status"),
|
| 42 |
+
CheckSpec("kpi", "/kpi", "KPIs"),
|
| 43 |
+
CheckSpec("runtime", "/runtime", "Runtime"),
|
| 44 |
+
CheckSpec("sessions", "/sessions", "Sessions"),
|
| 45 |
+
CheckSpec("logs", "/logs", "Logs"),
|
| 46 |
+
CheckSpec("events", "/events", "Live events"),
|
| 47 |
+
CheckSpec("live", "/live", "Live events"),
|
| 48 |
+
CheckSpec("catalog-page", "/catalog?type=skill&q=code", "Catalog"),
|
| 49 |
+
CheckSpec("graph-api-cold", "/api/graph/github.json?type=mcp-server&limit=20", "nodes"),
|
| 50 |
+
CheckSpec("catalog-search", "/api/entities/search.json?q=code%20review&type=skill&limit=10", "results"),
|
| 51 |
+
CheckSpec("entity-detail", "/api/entity/github.json?type=mcp-server", "frontmatter"),
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
WARM_CHECKS = (
|
| 55 |
+
CheckSpec("graph-api-warm", "/api/graph/github.json?type=mcp-server&limit=20", "nodes"),
|
| 56 |
+
CheckSpec("graph-warm", "/graph", "Knowledge graph"),
|
| 57 |
+
CheckSpec("wiki-detail-warm", "/wiki/github?type=mcp-server", "github"),
|
| 58 |
+
CheckSpec("kpi-warm", "/kpi", "KPIs"),
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _join_url(base_url: str, path: str) -> str:
|
| 63 |
+
return base_url.rstrip("/") + path
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _fetch(base_url: str, spec: CheckSpec, *, timeout: float) -> CheckResult:
|
| 67 |
+
started = time.perf_counter()
|
| 68 |
+
status = 0
|
| 69 |
+
body = ""
|
| 70 |
+
try:
|
| 71 |
+
with urllib.request.urlopen(_join_url(base_url, spec.path), timeout=timeout) as response:
|
| 72 |
+
status = response.status
|
| 73 |
+
body = response.read().decode("utf-8", errors="replace")
|
| 74 |
+
except urllib.error.HTTPError as exc:
|
| 75 |
+
status = exc.code
|
| 76 |
+
body = exc.read().decode("utf-8", errors="replace")
|
| 77 |
+
except OSError as exc:
|
| 78 |
+
elapsed = time.perf_counter() - started
|
| 79 |
+
return CheckResult(spec.name, spec.path, status, elapsed, False, str(exc), 0)
|
| 80 |
+
elapsed = time.perf_counter() - started
|
| 81 |
+
ok = status == 200 and spec.marker in body
|
| 82 |
+
if status != 200:
|
| 83 |
+
reason = f"status {status}"
|
| 84 |
+
elif spec.marker not in body:
|
| 85 |
+
reason = f"missing marker {spec.marker!r}"
|
| 86 |
+
else:
|
| 87 |
+
reason = "ok"
|
| 88 |
+
return CheckResult(spec.name, spec.path, status, elapsed, ok, reason, len(body))
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def run_smoke(
|
| 92 |
+
base_url: str,
|
| 93 |
+
*,
|
| 94 |
+
timeout: float,
|
| 95 |
+
include_warm: bool = False,
|
| 96 |
+
) -> list[CheckResult]:
|
| 97 |
+
specs = list(DEFAULT_CHECKS)
|
| 98 |
+
if include_warm:
|
| 99 |
+
specs.extend(WARM_CHECKS)
|
| 100 |
+
return [_fetch(base_url, spec, timeout=timeout) for spec in specs]
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def apply_latency_thresholds(results: list[CheckResult], thresholds: dict[str, float]) -> None:
|
| 104 |
+
for result in results:
|
| 105 |
+
threshold = thresholds.get(result.name)
|
| 106 |
+
if threshold is None or result.elapsed <= threshold:
|
| 107 |
+
continue
|
| 108 |
+
result.ok = False
|
| 109 |
+
result.reason = f"slow: {result.elapsed:.2f}s > {threshold:.2f}s"
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def results_to_jsonl(results: list[CheckResult]) -> str:
|
| 113 |
+
rows = []
|
| 114 |
+
for result in results:
|
| 115 |
+
row = asdict(result)
|
| 116 |
+
row["bytes"] = row.pop("bytes_read")
|
| 117 |
+
rows.append(json.dumps(row, sort_keys=True))
|
| 118 |
+
return "\n".join(rows)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _parse_thresholds(raw: list[str]) -> dict[str, float]:
|
| 122 |
+
thresholds: dict[str, float] = {}
|
| 123 |
+
for item in raw:
|
| 124 |
+
name, sep, value = item.partition("=")
|
| 125 |
+
if not sep:
|
| 126 |
+
raise argparse.ArgumentTypeError(f"threshold must be name=seconds: {item}")
|
| 127 |
+
try:
|
| 128 |
+
thresholds[name] = float(value)
|
| 129 |
+
except ValueError as exc:
|
| 130 |
+
raise argparse.ArgumentTypeError(f"invalid threshold seconds: {item}") from exc
|
| 131 |
+
return thresholds
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _parser() -> argparse.ArgumentParser:
|
| 135 |
+
parser = argparse.ArgumentParser(
|
| 136 |
+
description="Smoke-test a running ctx-monitor dashboard using stdlib HTTP checks.",
|
| 137 |
+
)
|
| 138 |
+
parser.add_argument("--base-url", default="http://127.0.0.1:8765")
|
| 139 |
+
parser.add_argument("--timeout", type=float, default=60.0)
|
| 140 |
+
parser.add_argument("--warm", action="store_true", help="Repeat key routes after caches are warm.")
|
| 141 |
+
parser.add_argument(
|
| 142 |
+
"--fail-on-slow",
|
| 143 |
+
action="append",
|
| 144 |
+
default=[],
|
| 145 |
+
metavar="NAME=SECONDS",
|
| 146 |
+
help="Fail when a named check exceeds a latency threshold. Repeatable.",
|
| 147 |
+
)
|
| 148 |
+
parser.add_argument("--jsonl", action="store_true", help="Emit machine-readable JSONL.")
|
| 149 |
+
return parser
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def main(argv: list[str] | None = None) -> int:
|
| 153 |
+
args = _parser().parse_args(argv)
|
| 154 |
+
results = run_smoke(args.base_url, timeout=args.timeout, include_warm=args.warm)
|
| 155 |
+
apply_latency_thresholds(results, _parse_thresholds(args.fail_on_slow))
|
| 156 |
+
if args.jsonl:
|
| 157 |
+
print(results_to_jsonl(results))
|
| 158 |
+
else:
|
| 159 |
+
for result in results:
|
| 160 |
+
status = "PASS" if result.ok else "FAIL"
|
| 161 |
+
print(
|
| 162 |
+
f"{status:4} {result.name:16} status={result.status:<3} "
|
| 163 |
+
f"elapsed={result.elapsed:6.2f}s bytes={result.bytes_read:<7} {result.reason}"
|
| 164 |
+
)
|
| 165 |
+
return 0 if all(result.ok for result in results) else 1
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
if __name__ == "__main__":
|
| 169 |
+
sys.exit(main())
|
scripts/pack_full_wiki_tar.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import io
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import re
|
| 8 |
+
import tarfile
|
| 9 |
+
import tempfile
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
from pathlib import Path, PurePosixPath
|
| 12 |
+
|
| 13 |
+
from ctx.core.wiki.wiki_packs import load_merged_wiki_pages, write_wiki_base_pack
|
| 14 |
+
|
| 15 |
+
_WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:")
|
| 16 |
+
_GRAPH_MANIFEST = "graphify-out/graph-export-manifest.json"
|
| 17 |
+
_REQUIRED_EXPANDED_MARKDOWN = frozenset({"graphify-out/graph-report.md"})
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass(frozen=True)
|
| 21 |
+
class RepackStats:
|
| 22 |
+
export_id: str
|
| 23 |
+
packed_pages: int
|
| 24 |
+
removed_expanded_markdown_pages: int
|
| 25 |
+
target: Path
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def repack_full_wiki_tar(source: Path, target: Path | None = None) -> RepackStats:
|
| 29 |
+
"""Write a full wiki tarball that carries entity pages in wiki-packs."""
|
| 30 |
+
source = Path(source)
|
| 31 |
+
target = source if target is None else Path(target)
|
| 32 |
+
if not source.is_file():
|
| 33 |
+
raise FileNotFoundError(source)
|
| 34 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 35 |
+
|
| 36 |
+
with tempfile.TemporaryDirectory(prefix="ctx-wiki-pack-") as tmp_name:
|
| 37 |
+
tmp_root = Path(tmp_name)
|
| 38 |
+
existing_pack_root = tmp_root / "existing-wiki-packs"
|
| 39 |
+
pages: dict[str, str] = {}
|
| 40 |
+
export_id: str | None = None
|
| 41 |
+
with tarfile.open(source, "r:gz") as src:
|
| 42 |
+
for member in src:
|
| 43 |
+
name = _safe_tar_name(member.name)
|
| 44 |
+
if name.startswith("wiki-packs/"):
|
| 45 |
+
_copy_existing_wiki_pack_member(src, member, name, existing_pack_root)
|
| 46 |
+
continue
|
| 47 |
+
if not member.isfile():
|
| 48 |
+
continue
|
| 49 |
+
if name == _GRAPH_MANIFEST:
|
| 50 |
+
export_id = _read_export_id(src, member)
|
| 51 |
+
if not _should_pack_markdown_page(name):
|
| 52 |
+
continue
|
| 53 |
+
extracted = src.extractfile(member)
|
| 54 |
+
if extracted is None:
|
| 55 |
+
raise ValueError(f"archive file is unreadable: {member.name}")
|
| 56 |
+
with extracted:
|
| 57 |
+
pages[name] = _normalise_page_text(
|
| 58 |
+
extracted.read().decode("utf-8", errors="replace")
|
| 59 |
+
)
|
| 60 |
+
if not export_id:
|
| 61 |
+
raise ValueError(f"{source} is missing graph export id")
|
| 62 |
+
if existing_pack_root.exists():
|
| 63 |
+
pages.update(load_merged_wiki_pages(existing_pack_root))
|
| 64 |
+
|
| 65 |
+
pack_root = tmp_root / "wiki-packs"
|
| 66 |
+
write_wiki_base_pack(
|
| 67 |
+
pack_dir=pack_root / f"base-{export_id}",
|
| 68 |
+
pack_id=f"base-{export_id}",
|
| 69 |
+
base_export_id=export_id,
|
| 70 |
+
pages=pages,
|
| 71 |
+
)
|
| 72 |
+
_validate_pack_payload(pack_root, pages)
|
| 73 |
+
removed = _rewrite_tar_with_pack(source, target, pack_root, pages)
|
| 74 |
+
return RepackStats(
|
| 75 |
+
export_id=export_id,
|
| 76 |
+
packed_pages=len(pages),
|
| 77 |
+
removed_expanded_markdown_pages=removed,
|
| 78 |
+
target=target,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _rewrite_tar_with_pack(
|
| 83 |
+
source: Path,
|
| 84 |
+
target: Path,
|
| 85 |
+
pack_root: Path,
|
| 86 |
+
pages: dict[str, str],
|
| 87 |
+
) -> int:
|
| 88 |
+
tmp_target = target.with_name(f".{target.name}.tmp")
|
| 89 |
+
tmp_target.unlink(missing_ok=True)
|
| 90 |
+
removed = 0
|
| 91 |
+
written_names: set[str] = set()
|
| 92 |
+
try:
|
| 93 |
+
with tarfile.open(source, "r:gz") as src, tarfile.open(
|
| 94 |
+
tmp_target,
|
| 95 |
+
"w:gz",
|
| 96 |
+
compresslevel=9,
|
| 97 |
+
) as dst:
|
| 98 |
+
for member in src:
|
| 99 |
+
name = _safe_tar_name(member.name)
|
| 100 |
+
if name.startswith("wiki-packs/"):
|
| 101 |
+
continue
|
| 102 |
+
if _is_transient_member(name):
|
| 103 |
+
continue
|
| 104 |
+
if _should_skip_expanded_markdown_member(name):
|
| 105 |
+
removed += 1
|
| 106 |
+
continue
|
| 107 |
+
if member.isfile():
|
| 108 |
+
extracted = src.extractfile(member)
|
| 109 |
+
if extracted is None:
|
| 110 |
+
raise ValueError(f"archive file is unreadable: {member.name}")
|
| 111 |
+
with extracted:
|
| 112 |
+
member.name = name
|
| 113 |
+
dst.addfile(member, extracted)
|
| 114 |
+
written_names.add(name)
|
| 115 |
+
elif member.isdir():
|
| 116 |
+
member.name = name
|
| 117 |
+
dst.addfile(member)
|
| 118 |
+
written_names.add(name)
|
| 119 |
+
else:
|
| 120 |
+
raise ValueError(f"unsupported archive member: {member.name}")
|
| 121 |
+
for name in sorted(_REQUIRED_EXPANDED_MARKDOWN - written_names):
|
| 122 |
+
text = pages.get(name)
|
| 123 |
+
if text is not None:
|
| 124 |
+
_add_text(dst, name=name, text=text)
|
| 125 |
+
for path in sorted(pack_root.rglob("*")):
|
| 126 |
+
if path.is_file():
|
| 127 |
+
dst.add(path, arcname=path.relative_to(pack_root.parent).as_posix())
|
| 128 |
+
os.replace(tmp_target, target)
|
| 129 |
+
finally:
|
| 130 |
+
tmp_target.unlink(missing_ok=True)
|
| 131 |
+
return removed
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _copy_existing_wiki_pack_member(
|
| 135 |
+
tf: tarfile.TarFile,
|
| 136 |
+
member: tarfile.TarInfo,
|
| 137 |
+
name: str,
|
| 138 |
+
packs_dir: Path,
|
| 139 |
+
) -> None:
|
| 140 |
+
if not member.isfile():
|
| 141 |
+
return
|
| 142 |
+
relpath = name.removeprefix("wiki-packs/")
|
| 143 |
+
if not relpath:
|
| 144 |
+
return
|
| 145 |
+
target = packs_dir.joinpath(*PurePosixPath(relpath).parts)
|
| 146 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 147 |
+
extracted = tf.extractfile(member)
|
| 148 |
+
if extracted is None:
|
| 149 |
+
raise ValueError(f"archive file is unreadable: {member.name}")
|
| 150 |
+
with extracted, target.open("wb") as out:
|
| 151 |
+
out.write(extracted.read())
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _read_export_id(tf: tarfile.TarFile, member: tarfile.TarInfo) -> str:
|
| 155 |
+
extracted = tf.extractfile(member)
|
| 156 |
+
if extracted is None:
|
| 157 |
+
raise ValueError(f"archive file is unreadable: {member.name}")
|
| 158 |
+
with extracted:
|
| 159 |
+
payload = json.loads(extracted.read().decode("utf-8"))
|
| 160 |
+
if not isinstance(payload, dict):
|
| 161 |
+
raise ValueError(f"{_GRAPH_MANIFEST} must contain a JSON object")
|
| 162 |
+
export_id = payload.get("export_id")
|
| 163 |
+
if not isinstance(export_id, str) or not export_id.strip():
|
| 164 |
+
raise ValueError(f"{_GRAPH_MANIFEST} is missing export_id")
|
| 165 |
+
return export_id.strip()
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _validate_pack_payload(pack_root: Path, expected_pages: dict[str, str]) -> None:
|
| 169 |
+
pages = load_merged_wiki_pages(pack_root)
|
| 170 |
+
if pages != expected_pages:
|
| 171 |
+
raise ValueError("wiki pack payload does not match source markdown pages")
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _normalise_page_text(text: str) -> str:
|
| 175 |
+
return text if text.strip() else "<!-- empty markdown page -->\n"
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _safe_tar_name(raw_name: str) -> str:
|
| 179 |
+
name = raw_name.replace("\\", "/")
|
| 180 |
+
while name.startswith("./"):
|
| 181 |
+
name = name[2:]
|
| 182 |
+
path = PurePosixPath(name)
|
| 183 |
+
if (
|
| 184 |
+
not name
|
| 185 |
+
or name.startswith("/")
|
| 186 |
+
or _WINDOWS_DRIVE_RE.match(name)
|
| 187 |
+
or any(part in {"", ".", ".."} for part in path.parts)
|
| 188 |
+
):
|
| 189 |
+
raise ValueError(f"unsafe archive member path: {raw_name}")
|
| 190 |
+
return path.as_posix()
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def _is_transient_member(name: str) -> bool:
|
| 194 |
+
return (
|
| 195 |
+
name.endswith(".original")
|
| 196 |
+
or name.endswith(".lock")
|
| 197 |
+
or name == ".ctx"
|
| 198 |
+
or name.startswith(".ctx/")
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _is_high_fanout_entity_page(name: str) -> bool:
|
| 203 |
+
prefixes = (
|
| 204 |
+
"entities/skills/",
|
| 205 |
+
"entities/agents/",
|
| 206 |
+
"entities/mcp-servers/",
|
| 207 |
+
)
|
| 208 |
+
return name.startswith(prefixes) and name.endswith(".md")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def _should_pack_markdown_page(name: str) -> bool:
|
| 212 |
+
return name.endswith(".md") and not name.startswith("wiki-packs/")
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def _should_skip_expanded_markdown_member(name: str) -> bool:
|
| 216 |
+
return (
|
| 217 |
+
name.endswith(".md")
|
| 218 |
+
and name not in _REQUIRED_EXPANDED_MARKDOWN
|
| 219 |
+
and "/" in name
|
| 220 |
+
and not name.startswith("entities/harnesses/")
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _add_text(tf: tarfile.TarFile, *, name: str, text: str) -> None:
|
| 225 |
+
payload = text.encode("utf-8")
|
| 226 |
+
info = tarfile.TarInfo(name)
|
| 227 |
+
info.size = len(payload)
|
| 228 |
+
info.mode = 0o644
|
| 229 |
+
info.mtime = 0
|
| 230 |
+
tf.addfile(info, io.BytesIO(payload))
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def main(argv: list[str] | None = None) -> int:
|
| 234 |
+
parser = argparse.ArgumentParser(
|
| 235 |
+
description="Repack ctx full wiki tarball with markdown pages in wiki-packs.",
|
| 236 |
+
)
|
| 237 |
+
parser.add_argument(
|
| 238 |
+
"--source",
|
| 239 |
+
type=Path,
|
| 240 |
+
default=Path("graph/wiki-graph.tar.gz"),
|
| 241 |
+
help="Existing full wiki tarball.",
|
| 242 |
+
)
|
| 243 |
+
parser.add_argument(
|
| 244 |
+
"--target",
|
| 245 |
+
type=Path,
|
| 246 |
+
help="Destination tarball. Defaults to rewriting --source atomically.",
|
| 247 |
+
)
|
| 248 |
+
args = parser.parse_args(argv)
|
| 249 |
+
stats = repack_full_wiki_tar(args.source, args.target)
|
| 250 |
+
print(
|
| 251 |
+
"packed "
|
| 252 |
+
f"{stats.packed_pages:,} markdown pages for {stats.export_id}; "
|
| 253 |
+
f"removed {stats.removed_expanded_markdown_pages:,} expanded markdown pages; "
|
| 254 |
+
f"wrote {stats.target}"
|
| 255 |
+
)
|
| 256 |
+
return 0
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
if __name__ == "__main__":
|
| 260 |
+
raise SystemExit(main())
|
scripts/prune_skillspector_wiki.py
ADDED
|
@@ -0,0 +1,590 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Prune SkillSpector removal candidates from shipped graph artifacts.
|
| 3 |
+
|
| 4 |
+
This is a release-maintenance tool. It does not decide what should be removed;
|
| 5 |
+
that policy lives in ``ctx.core.quality.skillspector_remediation``. This script
|
| 6 |
+
applies only the plan's ``remove_slugs`` to wiki tarballs, graph JSON, the
|
| 7 |
+
dashboard index, and the fallback skill catalog.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import gzip
|
| 14 |
+
from io import BytesIO
|
| 15 |
+
import json
|
| 16 |
+
import re
|
| 17 |
+
import sys
|
| 18 |
+
import tarfile
|
| 19 |
+
import tempfile
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from datetime import UTC, datetime
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from typing import Any, Iterable
|
| 24 |
+
|
| 25 |
+
REPO_ROOT = Path(__file__).resolve().parent.parent
|
| 26 |
+
if str(REPO_ROOT) not in sys.path:
|
| 27 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 28 |
+
|
| 29 |
+
from ctx.core.quality.skillspector_audit import ( # noqa: E402
|
| 30 |
+
SkillSpectorAuditRecord,
|
| 31 |
+
load_audit_records,
|
| 32 |
+
)
|
| 33 |
+
from ctx.core.quality.skillspector_remediation import build_remediation_plan # noqa: E402
|
| 34 |
+
from ctx.core.wiki.artifact_promotion import promote_staged_artifact # noqa: E402
|
| 35 |
+
from ctx.utils._fs_utils import atomic_write_bytes, atomic_write_text, reject_symlink_path # noqa: E402
|
| 36 |
+
from scripts.build_dashboard_graph_index import build_dashboard_index # noqa: E402
|
| 37 |
+
|
| 38 |
+
GRAPH_EXPORT_NAMES = {
|
| 39 |
+
"graphify-out/graph.json",
|
| 40 |
+
"graphify-out/graph-delta.json",
|
| 41 |
+
"graphify-out/communities.json",
|
| 42 |
+
"graphify-out/graph-report.md",
|
| 43 |
+
"graphify-out/graph-export-manifest.json",
|
| 44 |
+
}
|
| 45 |
+
CATALOG_MEMBER = "external-catalogs/skills-sh/catalog.json"
|
| 46 |
+
AUDIT_MEMBER = "security/skillspector-audit.jsonl.gz"
|
| 47 |
+
PREVIEW_HTML_FILES = (
|
| 48 |
+
"sample-top60.html",
|
| 49 |
+
"viz-ai-agents.html",
|
| 50 |
+
"viz-overview.html",
|
| 51 |
+
"viz-python.html",
|
| 52 |
+
"viz-security.html",
|
| 53 |
+
)
|
| 54 |
+
GZIP_COMPRESSLEVEL = 3
|
| 55 |
+
_EXPORT_META_RE = re.compile(
|
| 56 |
+
r'(<meta\s+name=["\']ctx-graph-export-id["\']\s+content=["\'])([^"\']*)(["\'])',
|
| 57 |
+
re.IGNORECASE,
|
| 58 |
+
)
|
| 59 |
+
_METADATA_RE = re.compile(r"const CTX_GRAPH_METADATA = (\{.*?\});", re.DOTALL)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@dataclass(frozen=True)
|
| 63 |
+
class PruneStats:
|
| 64 |
+
remove_slugs: int
|
| 65 |
+
graph_nodes_before: int
|
| 66 |
+
graph_nodes_after: int
|
| 67 |
+
graph_edges_before: int
|
| 68 |
+
graph_edges_after: int
|
| 69 |
+
skill_pages_removed: int
|
| 70 |
+
converted_members_removed: int
|
| 71 |
+
catalog_entries_removed: int
|
| 72 |
+
audit_records_removed: int
|
| 73 |
+
export_id: str
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def build_pruned_artifacts(
|
| 77 |
+
*,
|
| 78 |
+
audit_path: Path,
|
| 79 |
+
full_tarball: Path,
|
| 80 |
+
runtime_tarball: Path,
|
| 81 |
+
root_catalog: Path,
|
| 82 |
+
root_communities: Path,
|
| 83 |
+
graph_dir: Path,
|
| 84 |
+
apply: bool,
|
| 85 |
+
now: datetime | None = None,
|
| 86 |
+
) -> PruneStats:
|
| 87 |
+
"""Prune remove candidates from full/runtime graph artifacts."""
|
| 88 |
+
records = load_audit_records(audit_path)
|
| 89 |
+
plan = build_remediation_plan(records, audit_path=audit_path)
|
| 90 |
+
remove_slugs = set(str(slug) for slug in plan["remove_slugs"])
|
| 91 |
+
remove_node_ids = {f"skill:{slug}" for slug in remove_slugs}
|
| 92 |
+
timestamp = _timestamp(now)
|
| 93 |
+
|
| 94 |
+
graph, communities = _read_tar_graph_artifacts(full_tarball)
|
| 95 |
+
graph_before = _graph_counts(graph)
|
| 96 |
+
graph = _prune_graph(graph, remove_node_ids)
|
| 97 |
+
graph_after = _graph_counts(graph)
|
| 98 |
+
export_id = f"ctx-skillspector-prune-{timestamp}-{graph_after[0]}-{graph_after[1]}"
|
| 99 |
+
graph.setdefault("graph", {})["export_id"] = export_id
|
| 100 |
+
graph["graph"]["generated"] = timestamp
|
| 101 |
+
graph["graph"]["skillspector_removed_nodes"] = len(remove_node_ids)
|
| 102 |
+
communities = _prune_communities(
|
| 103 |
+
communities,
|
| 104 |
+
remove_node_ids=remove_node_ids,
|
| 105 |
+
export_id=export_id,
|
| 106 |
+
generated=timestamp,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
audit_records = {
|
| 110 |
+
slug: record for slug, record in records.items() if slug not in remove_slugs
|
| 111 |
+
}
|
| 112 |
+
pruned_catalog, catalog_removed = _prune_catalog_file(root_catalog, remove_slugs)
|
| 113 |
+
replacements = _build_replacements(
|
| 114 |
+
graph=graph,
|
| 115 |
+
communities=communities,
|
| 116 |
+
remove_node_ids=remove_node_ids,
|
| 117 |
+
audit_records=audit_records,
|
| 118 |
+
pruned_catalog=pruned_catalog,
|
| 119 |
+
export_id=export_id,
|
| 120 |
+
generated=timestamp,
|
| 121 |
+
) if apply else {}
|
| 122 |
+
|
| 123 |
+
full_stats = _rewrite_tarball(
|
| 124 |
+
full_tarball,
|
| 125 |
+
replacements=replacements,
|
| 126 |
+
remove_slugs=remove_slugs,
|
| 127 |
+
apply=apply,
|
| 128 |
+
)
|
| 129 |
+
if apply:
|
| 130 |
+
runtime_replacements = {
|
| 131 |
+
key: value
|
| 132 |
+
for key, value in replacements.items()
|
| 133 |
+
if key not in {AUDIT_MEMBER, CATALOG_MEMBER}
|
| 134 |
+
}
|
| 135 |
+
runtime_replacements[CATALOG_MEMBER] = _json_bytes(pruned_catalog, compact=False)
|
| 136 |
+
_rewrite_tarball(
|
| 137 |
+
runtime_tarball,
|
| 138 |
+
replacements=runtime_replacements,
|
| 139 |
+
remove_slugs=remove_slugs,
|
| 140 |
+
apply=True,
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
if apply:
|
| 144 |
+
atomic_write_text(root_communities, json.dumps(communities, indent=2) + "\n")
|
| 145 |
+
atomic_write_bytes(root_catalog, _gzip_json_bytes(pruned_catalog))
|
| 146 |
+
atomic_write_bytes(audit_path, _audit_bytes(audit_records.values()))
|
| 147 |
+
_refresh_preview_metadata(
|
| 148 |
+
graph_dir,
|
| 149 |
+
export_id=export_id,
|
| 150 |
+
nodes=graph_after[0],
|
| 151 |
+
edges=graph_after[1],
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
return PruneStats(
|
| 155 |
+
remove_slugs=len(remove_slugs),
|
| 156 |
+
graph_nodes_before=graph_before[0],
|
| 157 |
+
graph_nodes_after=graph_after[0],
|
| 158 |
+
graph_edges_before=graph_before[1],
|
| 159 |
+
graph_edges_after=graph_after[1],
|
| 160 |
+
skill_pages_removed=full_stats["skill_pages_removed"],
|
| 161 |
+
converted_members_removed=full_stats["converted_members_removed"],
|
| 162 |
+
catalog_entries_removed=catalog_removed,
|
| 163 |
+
audit_records_removed=len(records) - len(audit_records),
|
| 164 |
+
export_id=export_id,
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _build_replacements(
|
| 169 |
+
*,
|
| 170 |
+
graph: dict[str, Any],
|
| 171 |
+
communities: dict[str, Any],
|
| 172 |
+
remove_node_ids: set[str],
|
| 173 |
+
audit_records: dict[str, SkillSpectorAuditRecord],
|
| 174 |
+
pruned_catalog: dict[str, Any],
|
| 175 |
+
export_id: str,
|
| 176 |
+
generated: str,
|
| 177 |
+
) -> dict[str, bytes]:
|
| 178 |
+
return {
|
| 179 |
+
"graphify-out/graph.json": _json_bytes(graph, compact=True),
|
| 180 |
+
"graphify-out/dashboard-neighborhoods.sqlite3": _dashboard_index_bytes(graph),
|
| 181 |
+
"graphify-out/graph-delta.json": _json_bytes(
|
| 182 |
+
_render_delta(remove_node_ids, export_id=export_id, generated=generated),
|
| 183 |
+
compact=False,
|
| 184 |
+
),
|
| 185 |
+
"graphify-out/communities.json": _json_bytes(communities, compact=False),
|
| 186 |
+
"graphify-out/graph-report.md": _render_report(
|
| 187 |
+
graph,
|
| 188 |
+
communities,
|
| 189 |
+
export_id=export_id,
|
| 190 |
+
generated=generated,
|
| 191 |
+
removed=len(remove_node_ids),
|
| 192 |
+
).encode("utf-8"),
|
| 193 |
+
"graphify-out/graph-export-manifest.json": _json_bytes(
|
| 194 |
+
_render_manifest(graph, communities, export_id=export_id, generated=generated),
|
| 195 |
+
compact=False,
|
| 196 |
+
),
|
| 197 |
+
AUDIT_MEMBER: _audit_bytes(audit_records.values()),
|
| 198 |
+
CATALOG_MEMBER: _json_bytes(pruned_catalog, compact=False),
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _safe_tar_name(name: str) -> str | None:
|
| 203 |
+
normalized = name.replace("\\", "/")
|
| 204 |
+
while normalized.startswith("./"):
|
| 205 |
+
normalized = normalized[2:]
|
| 206 |
+
normalized = normalized.rstrip("/")
|
| 207 |
+
if not normalized:
|
| 208 |
+
return None
|
| 209 |
+
parts = normalized.split("/")
|
| 210 |
+
first = parts[0]
|
| 211 |
+
if (
|
| 212 |
+
normalized.startswith("/")
|
| 213 |
+
or (len(first) == 2 and first[1] == ":")
|
| 214 |
+
or any(part in {"", ".", ".."} for part in parts)
|
| 215 |
+
):
|
| 216 |
+
return None
|
| 217 |
+
return normalized
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _read_tar_graph_artifacts(tarball: Path) -> tuple[dict[str, Any], dict[str, Any]]:
|
| 221 |
+
graph: dict[str, Any] | None = None
|
| 222 |
+
communities: dict[str, Any] | None = None
|
| 223 |
+
with tarfile.open(tarball, "r:gz") as tf:
|
| 224 |
+
for member in tf:
|
| 225 |
+
safe_name = _safe_tar_name(member.name)
|
| 226 |
+
if safe_name not in {"graphify-out/graph.json", "graphify-out/communities.json"}:
|
| 227 |
+
continue
|
| 228 |
+
f = tf.extractfile(member)
|
| 229 |
+
if f is None:
|
| 230 |
+
continue
|
| 231 |
+
data = json.loads(f.read().decode("utf-8"))
|
| 232 |
+
if safe_name.endswith("graph.json"):
|
| 233 |
+
graph = data
|
| 234 |
+
else:
|
| 235 |
+
communities = data
|
| 236 |
+
if graph is None or communities is None:
|
| 237 |
+
raise ValueError(f"{tarball} is missing graph.json or communities.json")
|
| 238 |
+
return graph, communities
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def _graph_edges(graph: dict[str, Any]) -> list[dict[str, Any]]:
|
| 242 |
+
raw = graph.get("edges", graph.get("links", []))
|
| 243 |
+
return [edge for edge in raw if isinstance(edge, dict)]
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def _graph_counts(graph: dict[str, Any]) -> tuple[int, int]:
|
| 247 |
+
nodes = [node for node in graph.get("nodes", []) if isinstance(node, dict)]
|
| 248 |
+
return len(nodes), len(_graph_edges(graph))
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def _prune_graph(graph: dict[str, Any], remove_node_ids: set[str]) -> dict[str, Any]:
|
| 252 |
+
nodes = [
|
| 253 |
+
node
|
| 254 |
+
for node in graph.get("nodes", [])
|
| 255 |
+
if isinstance(node, dict) and node.get("id") not in remove_node_ids
|
| 256 |
+
]
|
| 257 |
+
edges = [
|
| 258 |
+
edge
|
| 259 |
+
for edge in _graph_edges(graph)
|
| 260 |
+
if edge.get("source") not in remove_node_ids and edge.get("target") not in remove_node_ids
|
| 261 |
+
]
|
| 262 |
+
graph_meta = graph.get("graph")
|
| 263 |
+
pruned: dict[str, Any] = {"graph": graph_meta if isinstance(graph_meta, dict) else {}}
|
| 264 |
+
for key, value in graph.items():
|
| 265 |
+
if key not in {"graph", "nodes", "edges", "links"}:
|
| 266 |
+
pruned[key] = value
|
| 267 |
+
pruned["nodes"] = nodes
|
| 268 |
+
pruned["edges"] = edges
|
| 269 |
+
return pruned
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def _prune_communities(
|
| 273 |
+
communities: dict[str, Any],
|
| 274 |
+
*,
|
| 275 |
+
remove_node_ids: set[str],
|
| 276 |
+
export_id: str,
|
| 277 |
+
generated: str,
|
| 278 |
+
) -> dict[str, Any]:
|
| 279 |
+
raw = communities.get("communities", {})
|
| 280 |
+
kept: dict[str, Any] = {}
|
| 281 |
+
if isinstance(raw, dict):
|
| 282 |
+
for key, value in raw.items():
|
| 283 |
+
if not isinstance(value, dict):
|
| 284 |
+
continue
|
| 285 |
+
members = [
|
| 286 |
+
member
|
| 287 |
+
for member in value.get("members", [])
|
| 288 |
+
if isinstance(member, str) and member not in remove_node_ids
|
| 289 |
+
]
|
| 290 |
+
if members:
|
| 291 |
+
kept[str(key)] = {**value, "members": members}
|
| 292 |
+
return {
|
| 293 |
+
**communities,
|
| 294 |
+
"export_id": export_id,
|
| 295 |
+
"generated": generated,
|
| 296 |
+
"communities": kept,
|
| 297 |
+
"total_communities": len(kept),
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def _prune_catalog_file(path: Path, remove_slugs: set[str]) -> tuple[dict[str, Any], int]:
|
| 302 |
+
with gzip.open(path, "rt", encoding="utf-8") as f:
|
| 303 |
+
catalog = json.load(f)
|
| 304 |
+
if not isinstance(catalog, dict):
|
| 305 |
+
raise ValueError(f"{path} does not contain a JSON object")
|
| 306 |
+
return _prune_catalog(catalog, remove_slugs)
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def _prune_catalog(catalog: dict[str, Any], remove_slugs: set[str]) -> tuple[dict[str, Any], int]:
|
| 310 |
+
skills = [item for item in catalog.get("skills", []) if isinstance(item, dict)]
|
| 311 |
+
kept = [item for item in skills if str(item.get("ctx_slug") or "") not in remove_slugs]
|
| 312 |
+
pruned = dict(catalog)
|
| 313 |
+
pruned["skills"] = kept
|
| 314 |
+
pruned["observed_unique_skills"] = len(kept)
|
| 315 |
+
pruned["body_available_count"] = sum(1 for item in kept if item.get("body_available"))
|
| 316 |
+
pruned["body_packaged_count"] = sum(1 for item in kept if item.get("converted_path"))
|
| 317 |
+
pruned["body_hydrated_total_count"] = pruned["body_available_count"]
|
| 318 |
+
pruned["skillspector_removed_count"] = len(skills) - len(kept)
|
| 319 |
+
pruned["skillspector_removed_at"] = datetime.now(UTC).isoformat()
|
| 320 |
+
return pruned, len(skills) - len(kept)
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def _rewrite_tarball(
|
| 324 |
+
tarball: Path,
|
| 325 |
+
*,
|
| 326 |
+
replacements: dict[str, bytes],
|
| 327 |
+
remove_slugs: set[str],
|
| 328 |
+
apply: bool,
|
| 329 |
+
) -> dict[str, int]:
|
| 330 |
+
stats = {"skill_pages_removed": 0, "converted_members_removed": 0}
|
| 331 |
+
reject_symlink_path(tarball)
|
| 332 |
+
if not apply:
|
| 333 |
+
with tarfile.open(tarball, "r:gz") as src:
|
| 334 |
+
for member in src:
|
| 335 |
+
safe_name = _safe_tar_name(member.name)
|
| 336 |
+
if safe_name is None:
|
| 337 |
+
continue
|
| 338 |
+
if _is_removed_skill_page(safe_name, remove_slugs):
|
| 339 |
+
stats["skill_pages_removed"] += 1
|
| 340 |
+
elif _is_removed_converted_member(safe_name, remove_slugs):
|
| 341 |
+
stats["converted_members_removed"] += 1
|
| 342 |
+
return stats
|
| 343 |
+
|
| 344 |
+
staged = tarball.with_name(f"{tarball.name}.staged")
|
| 345 |
+
reject_symlink_path(staged)
|
| 346 |
+
skip_names = set(replacements)
|
| 347 |
+
with tarfile.open(tarball, "r:gz") as src, tarfile.open(
|
| 348 |
+
staged,
|
| 349 |
+
"w:gz",
|
| 350 |
+
compresslevel=GZIP_COMPRESSLEVEL,
|
| 351 |
+
) as dst:
|
| 352 |
+
for member in src:
|
| 353 |
+
safe_name = _safe_tar_name(member.name)
|
| 354 |
+
if safe_name is None:
|
| 355 |
+
continue
|
| 356 |
+
if safe_name in GRAPH_EXPORT_NAMES or safe_name in skip_names:
|
| 357 |
+
continue
|
| 358 |
+
if safe_name.endswith(".original") or safe_name.endswith(".lock"):
|
| 359 |
+
continue
|
| 360 |
+
if safe_name == ".ctx" or safe_name.startswith(".ctx/"):
|
| 361 |
+
continue
|
| 362 |
+
if _is_removed_skill_page(safe_name, remove_slugs):
|
| 363 |
+
stats["skill_pages_removed"] += 1
|
| 364 |
+
continue
|
| 365 |
+
if _is_removed_converted_member(safe_name, remove_slugs):
|
| 366 |
+
stats["converted_members_removed"] += 1
|
| 367 |
+
continue
|
| 368 |
+
if member.isfile():
|
| 369 |
+
source = src.extractfile(member)
|
| 370 |
+
if source is not None:
|
| 371 |
+
dst.addfile(member, source)
|
| 372 |
+
elif member.isdir():
|
| 373 |
+
dst.addfile(member)
|
| 374 |
+
for name, payload in sorted(replacements.items()):
|
| 375 |
+
_add_bytes(dst, name=f"./{name}", payload=payload)
|
| 376 |
+
promote_staged_artifact(staged, tarball, validate=_validate_tarball)
|
| 377 |
+
return stats
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def _is_removed_skill_page(name: str, remove_slugs: set[str]) -> bool:
|
| 381 |
+
if not name.startswith("entities/skills/") or not name.endswith(".md"):
|
| 382 |
+
return False
|
| 383 |
+
slug = name.removeprefix("entities/skills/").removesuffix(".md")
|
| 384 |
+
return slug in remove_slugs
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def _is_removed_converted_member(name: str, remove_slugs: set[str]) -> bool:
|
| 388 |
+
if not name.startswith("converted/"):
|
| 389 |
+
return False
|
| 390 |
+
parts = name.split("/", 2)
|
| 391 |
+
return len(parts) >= 2 and parts[1] in remove_slugs
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def _add_bytes(tf: tarfile.TarFile, *, name: str, payload: bytes) -> None:
|
| 395 |
+
info = tarfile.TarInfo(name)
|
| 396 |
+
info.size = len(payload)
|
| 397 |
+
info.mode = 0o644
|
| 398 |
+
info.mtime = 0
|
| 399 |
+
tf.addfile(info, BytesIO(payload))
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def _validate_tarball(candidate: Path) -> None:
|
| 403 |
+
seen: set[str] = set()
|
| 404 |
+
with tarfile.open(candidate, "r:gz") as tf:
|
| 405 |
+
for member in tf:
|
| 406 |
+
safe_name = _safe_tar_name(member.name)
|
| 407 |
+
if safe_name is None:
|
| 408 |
+
raise ValueError(f"unsafe tar member: {member.name}")
|
| 409 |
+
if safe_name.endswith(".original") or safe_name.endswith(".lock"):
|
| 410 |
+
raise ValueError(f"transient member leaked: {safe_name}")
|
| 411 |
+
if safe_name == ".ctx" or safe_name.startswith(".ctx/"):
|
| 412 |
+
raise ValueError(f"queue state leaked: {safe_name}")
|
| 413 |
+
seen.add(safe_name)
|
| 414 |
+
missing = sorted((GRAPH_EXPORT_NAMES | {"graphify-out/dashboard-neighborhoods.sqlite3"}) - seen)
|
| 415 |
+
if missing:
|
| 416 |
+
raise ValueError(f"candidate tarball missing graph exports: {missing}")
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def _json_bytes(data: Any, *, compact: bool) -> bytes:
|
| 420 |
+
if compact:
|
| 421 |
+
return json.dumps(data, separators=(",", ":")).encode("utf-8")
|
| 422 |
+
return (json.dumps(data, indent=2, sort_keys=True) + "\n").encode("utf-8")
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def _gzip_json_bytes(data: Any) -> bytes:
|
| 426 |
+
return gzip.compress(_json_bytes(data, compact=False), compresslevel=GZIP_COMPRESSLEVEL)
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def _audit_bytes(records: Iterable[SkillSpectorAuditRecord]) -> bytes:
|
| 430 |
+
lines = [
|
| 431 |
+
json.dumps(record.to_json(), sort_keys=True, separators=(",", ":"))
|
| 432 |
+
for record in sorted(records, key=lambda item: item.slug)
|
| 433 |
+
]
|
| 434 |
+
return gzip.compress(("\n".join(lines) + "\n").encode("utf-8"), compresslevel=GZIP_COMPRESSLEVEL)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def _dashboard_index_bytes(graph: dict[str, Any]) -> bytes:
|
| 438 |
+
with tempfile.TemporaryDirectory(prefix="ctx-skillspector-prune-index-") as tmp:
|
| 439 |
+
tmp_path = Path(tmp)
|
| 440 |
+
graph_path = tmp_path / "graph.json"
|
| 441 |
+
index_path = tmp_path / "dashboard-neighborhoods.sqlite3"
|
| 442 |
+
graph_path.write_bytes(_json_bytes(graph, compact=True))
|
| 443 |
+
build_dashboard_index(graph_path, index_path)
|
| 444 |
+
return index_path.read_bytes()
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def _render_delta(
|
| 448 |
+
removed_node_ids: set[str],
|
| 449 |
+
*,
|
| 450 |
+
export_id: str,
|
| 451 |
+
generated: str,
|
| 452 |
+
) -> dict[str, Any]:
|
| 453 |
+
return {
|
| 454 |
+
"version": 1,
|
| 455 |
+
"full_rebuild": False,
|
| 456 |
+
"export_id": export_id,
|
| 457 |
+
"generated": generated,
|
| 458 |
+
"removed_nodes": sorted(removed_node_ids),
|
| 459 |
+
"nodes": [],
|
| 460 |
+
"edges": [],
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def _render_report(
|
| 465 |
+
graph: dict[str, Any],
|
| 466 |
+
communities: dict[str, Any],
|
| 467 |
+
*,
|
| 468 |
+
export_id: str,
|
| 469 |
+
generated: str,
|
| 470 |
+
removed: int,
|
| 471 |
+
) -> str:
|
| 472 |
+
nodes, edges = _graph_counts(graph)
|
| 473 |
+
total_communities = int(communities.get("total_communities") or 0)
|
| 474 |
+
return "\n".join([
|
| 475 |
+
"# Graph Report",
|
| 476 |
+
"",
|
| 477 |
+
f"> Generated: {generated}",
|
| 478 |
+
f"> Export ID: {export_id}",
|
| 479 |
+
f"> Nodes: {nodes} | Edges: {edges} | Communities: {total_communities}",
|
| 480 |
+
"",
|
| 481 |
+
"## SkillSpector Prune",
|
| 482 |
+
"",
|
| 483 |
+
f"- Removed skill nodes: {removed}",
|
| 484 |
+
"",
|
| 485 |
+
])
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def _render_manifest(
|
| 489 |
+
graph: dict[str, Any],
|
| 490 |
+
communities: dict[str, Any],
|
| 491 |
+
*,
|
| 492 |
+
export_id: str,
|
| 493 |
+
generated: str,
|
| 494 |
+
) -> dict[str, Any]:
|
| 495 |
+
nodes, edges = _graph_counts(graph)
|
| 496 |
+
return {
|
| 497 |
+
"version": 1,
|
| 498 |
+
"export_id": export_id,
|
| 499 |
+
"generated": generated,
|
| 500 |
+
"artifacts": {
|
| 501 |
+
"graph": "graph.json",
|
| 502 |
+
"delta": "graph-delta.json",
|
| 503 |
+
"communities": "communities.json",
|
| 504 |
+
"report": "graph-report.md",
|
| 505 |
+
},
|
| 506 |
+
"counts": {
|
| 507 |
+
"nodes": nodes,
|
| 508 |
+
"edges": edges,
|
| 509 |
+
"communities": int(communities.get("total_communities") or 0),
|
| 510 |
+
},
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def _refresh_preview_metadata(
|
| 515 |
+
graph_dir: Path,
|
| 516 |
+
*,
|
| 517 |
+
export_id: str,
|
| 518 |
+
nodes: int,
|
| 519 |
+
edges: int,
|
| 520 |
+
) -> None:
|
| 521 |
+
for filename in PREVIEW_HTML_FILES:
|
| 522 |
+
path = graph_dir / filename
|
| 523 |
+
if not path.is_file():
|
| 524 |
+
continue
|
| 525 |
+
text = path.read_text(encoding="utf-8", errors="replace")
|
| 526 |
+
text = _EXPORT_META_RE.sub(rf"\g<1>{export_id}\3", text)
|
| 527 |
+
|
| 528 |
+
def replace_metadata(match: re.Match[str]) -> str:
|
| 529 |
+
try:
|
| 530 |
+
metadata = json.loads(match.group(1))
|
| 531 |
+
except json.JSONDecodeError:
|
| 532 |
+
metadata = {}
|
| 533 |
+
metadata["export_id"] = export_id
|
| 534 |
+
metadata["source_graph_nodes"] = nodes
|
| 535 |
+
metadata["source_graph_edges"] = edges
|
| 536 |
+
return "const CTX_GRAPH_METADATA = " + json.dumps(metadata, sort_keys=True) + ";"
|
| 537 |
+
|
| 538 |
+
text = _METADATA_RE.sub(replace_metadata, text)
|
| 539 |
+
atomic_write_text(path, text, encoding="utf-8")
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def _timestamp(now: datetime | None = None) -> str:
|
| 543 |
+
return (now or datetime.now(UTC)).strftime("%Y%m%dT%H%M%SZ")
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def _print_stats(stats: PruneStats, *, applied: bool) -> None:
|
| 547 |
+
mode = "applied" if applied else "dry-run"
|
| 548 |
+
print(f"SkillSpector prune {mode}:")
|
| 549 |
+
print(f" remove slugs: {stats.remove_slugs:,}")
|
| 550 |
+
print(f" graph nodes: {stats.graph_nodes_before:,} -> {stats.graph_nodes_after:,}")
|
| 551 |
+
print(f" graph edges: {stats.graph_edges_before:,} -> {stats.graph_edges_after:,}")
|
| 552 |
+
print(f" skill pages removed: {stats.skill_pages_removed:,}")
|
| 553 |
+
print(f" converted members removed: {stats.converted_members_removed:,}")
|
| 554 |
+
print(f" catalog entries removed: {stats.catalog_entries_removed:,}")
|
| 555 |
+
print(f" audit records removed: {stats.audit_records_removed:,}")
|
| 556 |
+
print(f" export id: {stats.export_id}")
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
def main(argv: list[str] | None = None) -> int:
|
| 560 |
+
parser = argparse.ArgumentParser(
|
| 561 |
+
description="Prune SkillSpector removal candidates from graph/wiki artifacts.",
|
| 562 |
+
)
|
| 563 |
+
parser.add_argument("--audit", type=Path, default=REPO_ROOT / "graph/skillspector-audit.jsonl.gz")
|
| 564 |
+
parser.add_argument("--full-tarball", type=Path, default=REPO_ROOT / "graph/wiki-graph.tar.gz")
|
| 565 |
+
parser.add_argument(
|
| 566 |
+
"--runtime-tarball",
|
| 567 |
+
type=Path,
|
| 568 |
+
default=REPO_ROOT / "graph/wiki-graph-runtime.tar.gz",
|
| 569 |
+
)
|
| 570 |
+
parser.add_argument("--catalog", type=Path, default=REPO_ROOT / "graph/skills-sh-catalog.json.gz")
|
| 571 |
+
parser.add_argument("--communities", type=Path, default=REPO_ROOT / "graph/communities.json")
|
| 572 |
+
parser.add_argument("--graph-dir", type=Path, default=REPO_ROOT / "graph")
|
| 573 |
+
parser.add_argument("--apply", action="store_true", help="Rewrite artifacts in place")
|
| 574 |
+
args = parser.parse_args(argv)
|
| 575 |
+
|
| 576 |
+
stats = build_pruned_artifacts(
|
| 577 |
+
audit_path=args.audit,
|
| 578 |
+
full_tarball=args.full_tarball,
|
| 579 |
+
runtime_tarball=args.runtime_tarball,
|
| 580 |
+
root_catalog=args.catalog,
|
| 581 |
+
root_communities=args.communities,
|
| 582 |
+
graph_dir=args.graph_dir,
|
| 583 |
+
apply=args.apply,
|
| 584 |
+
)
|
| 585 |
+
_print_stats(stats, applied=args.apply)
|
| 586 |
+
return 0
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
if __name__ == "__main__":
|
| 590 |
+
raise SystemExit(main())
|
scripts/sync_huggingface.py
CHANGED
|
@@ -273,28 +273,6 @@ def _patch_export_readme(export_dir: Path) -> None:
|
|
| 273 |
)
|
| 274 |
|
| 275 |
|
| 276 |
-
def _iter_export_file_names(export_dir: Path) -> set[str]:
|
| 277 |
-
names: set[str] = set()
|
| 278 |
-
for path in export_dir.rglob("*"):
|
| 279 |
-
if not path.is_file():
|
| 280 |
-
continue
|
| 281 |
-
rel = path.relative_to(export_dir).as_posix()
|
| 282 |
-
if rel == ".cache" or rel.startswith(".cache/"):
|
| 283 |
-
continue
|
| 284 |
-
names.add(rel)
|
| 285 |
-
return names
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
def _repo_url(*, repo_id: str, repo_type: str) -> str:
|
| 289 |
-
prefix = {"dataset": "datasets", "space": "spaces"}.get(repo_type)
|
| 290 |
-
repo_path = f"{prefix}/{repo_id}" if prefix else repo_id
|
| 291 |
-
return f"https://huggingface.co/{repo_path}"
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
def _repo_commit_url(*, repo_id: str, repo_type: str, sha: str) -> str:
|
| 295 |
-
return f"{_repo_url(repo_id=repo_id, repo_type=repo_type)}/commit/{sha}"
|
| 296 |
-
|
| 297 |
-
|
| 298 |
def _hf_status_code(exc: BaseException) -> int | None:
|
| 299 |
response = getattr(exc, "response", None)
|
| 300 |
status = getattr(response, "status_code", None)
|
|
@@ -323,20 +301,6 @@ def _ensure_hf_repo_exists(*, api: Any, repo_id: str, repo_type: str) -> None:
|
|
| 323 |
raise
|
| 324 |
|
| 325 |
|
| 326 |
-
def _remote_has_no_stale_paths(
|
| 327 |
-
*,
|
| 328 |
-
api: Any,
|
| 329 |
-
export_dir: Path,
|
| 330 |
-
repo_id: str,
|
| 331 |
-
repo_type: str,
|
| 332 |
-
) -> bool:
|
| 333 |
-
try:
|
| 334 |
-
remote_files = set(api.list_repo_files(repo_id=repo_id, repo_type=repo_type))
|
| 335 |
-
except Exception:
|
| 336 |
-
return False
|
| 337 |
-
return remote_files <= _iter_export_file_names(export_dir)
|
| 338 |
-
|
| 339 |
-
|
| 340 |
def _upload_export(
|
| 341 |
*,
|
| 342 |
api: Any,
|
|
@@ -344,30 +308,7 @@ def _upload_export(
|
|
| 344 |
repo_id: str,
|
| 345 |
repo_type: str,
|
| 346 |
head: str,
|
| 347 |
-
prefer_large_upload: bool,
|
| 348 |
) -> str:
|
| 349 |
-
if (
|
| 350 |
-
prefer_large_upload
|
| 351 |
-
and hasattr(api, "upload_large_folder")
|
| 352 |
-
and _remote_has_no_stale_paths(
|
| 353 |
-
api=api,
|
| 354 |
-
export_dir=export_dir,
|
| 355 |
-
repo_id=repo_id,
|
| 356 |
-
repo_type=repo_type,
|
| 357 |
-
)
|
| 358 |
-
):
|
| 359 |
-
api.upload_large_folder(
|
| 360 |
-
repo_id=repo_id,
|
| 361 |
-
repo_type=repo_type,
|
| 362 |
-
folder_path=str(export_dir),
|
| 363 |
-
print_report=True,
|
| 364 |
-
)
|
| 365 |
-
info = api.repo_info(repo_id=repo_id, repo_type=repo_type)
|
| 366 |
-
sha = getattr(info, "sha", None)
|
| 367 |
-
if sha:
|
| 368 |
-
return _repo_commit_url(repo_id=repo_id, repo_type=repo_type, sha=str(sha))
|
| 369 |
-
return _repo_url(repo_id=repo_id, repo_type=repo_type)
|
| 370 |
-
|
| 371 |
info = api.upload_folder(
|
| 372 |
repo_id=repo_id,
|
| 373 |
repo_type=repo_type,
|
|
@@ -379,6 +320,33 @@ def _upload_export(
|
|
| 379 |
return str(getattr(info, "commit_url", info))
|
| 380 |
|
| 381 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 382 |
def sync_to_huggingface(
|
| 383 |
*,
|
| 384 |
repo: Path,
|
|
@@ -404,12 +372,33 @@ def sync_to_huggingface(
|
|
| 404 |
repo_type=repo_type,
|
| 405 |
export_dir=export_dir,
|
| 406 |
head=head,
|
| 407 |
-
prefer_large_upload=True,
|
| 408 |
)
|
| 409 |
finally:
|
| 410 |
shutil.rmtree(workspace, ignore_errors=True)
|
| 411 |
|
| 412 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 413 |
def main() -> None:
|
| 414 |
parser = argparse.ArgumentParser(
|
| 415 |
description="Upload this git checkout to Hugging Face with repo-card metadata"
|
|
@@ -425,12 +414,18 @@ def main() -> None:
|
|
| 425 |
default=os.environ.get("HF_REPO_TYPE", DEFAULT_REPO_TYPE),
|
| 426 |
help="Hugging Face repo type",
|
| 427 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 428 |
args = parser.parse_args()
|
| 429 |
token = os.environ.get("HF_TOKEN")
|
| 430 |
if not token:
|
| 431 |
raise SystemExit("HF_TOKEN is required")
|
|
|
|
| 432 |
print(
|
| 433 |
-
|
| 434 |
repo=Path(args.repo).resolve(),
|
| 435 |
repo_id=args.repo_id,
|
| 436 |
repo_type=args.repo_type,
|
|
|
|
| 273 |
)
|
| 274 |
|
| 275 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
def _hf_status_code(exc: BaseException) -> int | None:
|
| 277 |
response = getattr(exc, "response", None)
|
| 278 |
status = getattr(response, "status_code", None)
|
|
|
|
| 301 |
raise
|
| 302 |
|
| 303 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
def _upload_export(
|
| 305 |
*,
|
| 306 |
api: Any,
|
|
|
|
| 308 |
repo_id: str,
|
| 309 |
repo_type: str,
|
| 310 |
head: str,
|
|
|
|
| 311 |
) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
info = api.upload_folder(
|
| 313 |
repo_id=repo_id,
|
| 314 |
repo_type=repo_type,
|
|
|
|
| 320 |
return str(getattr(info, "commit_url", info))
|
| 321 |
|
| 322 |
|
| 323 |
+
def _upload_readme_card(
|
| 324 |
+
*,
|
| 325 |
+
api: Any,
|
| 326 |
+
repo: Path,
|
| 327 |
+
repo_id: str,
|
| 328 |
+
repo_type: str,
|
| 329 |
+
head: str,
|
| 330 |
+
) -> str:
|
| 331 |
+
readme = repo / "README.md"
|
| 332 |
+
rendered = with_hf_repo_card_metadata(readme.read_text(encoding="utf-8"))
|
| 333 |
+
workspace = Path(tempfile.mkdtemp(prefix="ctx-hf-card-"))
|
| 334 |
+
try:
|
| 335 |
+
card = workspace / "README.md"
|
| 336 |
+
card.write_text(rendered, encoding="utf-8", newline="\n")
|
| 337 |
+
info = api.upload_file(
|
| 338 |
+
repo_id=repo_id,
|
| 339 |
+
repo_type=repo_type,
|
| 340 |
+
path_or_fileobj=str(card),
|
| 341 |
+
path_in_repo="README.md",
|
| 342 |
+
commit_message=f"Sync ctx card {head[:7]}",
|
| 343 |
+
commit_description=f"GitHub commit: {head}",
|
| 344 |
+
)
|
| 345 |
+
return str(getattr(info, "commit_url", info))
|
| 346 |
+
finally:
|
| 347 |
+
shutil.rmtree(workspace, ignore_errors=True)
|
| 348 |
+
|
| 349 |
+
|
| 350 |
def sync_to_huggingface(
|
| 351 |
*,
|
| 352 |
repo: Path,
|
|
|
|
| 372 |
repo_type=repo_type,
|
| 373 |
export_dir=export_dir,
|
| 374 |
head=head,
|
|
|
|
| 375 |
)
|
| 376 |
finally:
|
| 377 |
shutil.rmtree(workspace, ignore_errors=True)
|
| 378 |
|
| 379 |
|
| 380 |
+
def sync_card_to_huggingface(
|
| 381 |
+
*,
|
| 382 |
+
repo: Path,
|
| 383 |
+
repo_id: str,
|
| 384 |
+
repo_type: str,
|
| 385 |
+
token: str,
|
| 386 |
+
) -> str:
|
| 387 |
+
"""Upload only the Hugging Face repo card README."""
|
| 388 |
+
from huggingface_hub import HfApi
|
| 389 |
+
|
| 390 |
+
head = _git(repo, "rev-parse", "HEAD")
|
| 391 |
+
api = HfApi(token=token)
|
| 392 |
+
_ensure_hf_repo_exists(api=api, repo_id=repo_id, repo_type=repo_type)
|
| 393 |
+
return _upload_readme_card(
|
| 394 |
+
api=api,
|
| 395 |
+
repo=repo,
|
| 396 |
+
repo_id=repo_id,
|
| 397 |
+
repo_type=repo_type,
|
| 398 |
+
head=head,
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
def main() -> None:
|
| 403 |
parser = argparse.ArgumentParser(
|
| 404 |
description="Upload this git checkout to Hugging Face with repo-card metadata"
|
|
|
|
| 414 |
default=os.environ.get("HF_REPO_TYPE", DEFAULT_REPO_TYPE),
|
| 415 |
help="Hugging Face repo type",
|
| 416 |
)
|
| 417 |
+
parser.add_argument(
|
| 418 |
+
"--card-only",
|
| 419 |
+
action="store_true",
|
| 420 |
+
help="Only refresh README.md repo-card metadata without uploading artifacts",
|
| 421 |
+
)
|
| 422 |
args = parser.parse_args()
|
| 423 |
token = os.environ.get("HF_TOKEN")
|
| 424 |
if not token:
|
| 425 |
raise SystemExit("HF_TOKEN is required")
|
| 426 |
+
sync = sync_card_to_huggingface if args.card_only else sync_to_huggingface
|
| 427 |
print(
|
| 428 |
+
sync(
|
| 429 |
repo=Path(args.repo).resolve(),
|
| 430 |
repo_id=args.repo_id,
|
| 431 |
repo_type=args.repo_type,
|
skills/repo-stats-autoupdate/SKILL.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
---
|
| 2 |
name: repo-stats-autoupdate
|
| 3 |
-
description: Keeps README badge + inline counts in sync with the real number of skills, agents, graph nodes/edges, communities, converted pipelines, and
|
| 4 |
type: maintenance
|
| 5 |
priority: 30
|
| 6 |
always_load: false
|
|
@@ -20,7 +20,7 @@ Reads the **authoritative sources** for the ctx repo's key numbers and patches `
|
|
| 20 |
| Graph edges | `len(graph["edges"])`, formatted as `642K` / `1.2M` |
|
| 21 |
| Communities | `graph/communities.json` → `total_communities` |
|
| 22 |
| Converted pipelines | `~/.claude/skill-wiki/converted/` subdir count |
|
| 23 |
-
| Tests | `pytest --collect-only -q`
|
| 24 |
|
| 25 |
Fields that can't be resolved (e.g. wiki not deployed) are left untouched — the updater never blocks a commit.
|
| 26 |
|
|
@@ -37,6 +37,7 @@ After that, every `git commit` runs `.githooks/pre-commit` which calls the updat
|
|
| 37 |
```bash
|
| 38 |
python src/update_repo_stats.py # patch README
|
| 39 |
python src/update_repo_stats.py --check # exit 1 if stale (for CI)
|
|
|
|
| 40 |
```
|
| 41 |
|
| 42 |
## When NOT to use it
|
|
|
|
| 1 |
---
|
| 2 |
name: repo-stats-autoupdate
|
| 3 |
+
description: Keeps README badge + inline counts in sync with the real number of skills, agents, graph nodes/edges, communities, converted pipelines, and test inventory. Runs automatically on every commit via a git pre-commit hook. Use when the README drifts from reality or before publishing a release.
|
| 4 |
type: maintenance
|
| 5 |
priority: 30
|
| 6 |
always_load: false
|
|
|
|
| 20 |
| Graph edges | `len(graph["edges"])`, formatted as `642K` / `1.2M` |
|
| 21 |
| Communities | `graph/communities.json` → `total_communities` |
|
| 22 |
| Converted pipelines | `~/.claude/skill-wiki/converted/` subdir count |
|
| 23 |
+
| Tests | checked-in README/docs inventory by default; set `CTX_UPDATE_REPO_STATS_LIVE_TESTS=1` to refresh from `pytest --collect-only -q` |
|
| 24 |
|
| 25 |
Fields that can't be resolved (e.g. wiki not deployed) are left untouched — the updater never blocks a commit.
|
| 26 |
|
|
|
|
| 37 |
```bash
|
| 38 |
python src/update_repo_stats.py # patch README
|
| 39 |
python src/update_repo_stats.py --check # exit 1 if stale (for CI)
|
| 40 |
+
CTX_UPDATE_REPO_STATS_LIVE_TESTS=1 python src/update_repo_stats.py # refresh test inventory
|
| 41 |
```
|
| 42 |
|
| 43 |
## When NOT to use it
|
src/__init__.py
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
"""ctx — skill and agent recommendation for Claude Code."""
|
| 2 |
|
| 3 |
-
__version__ = "1.0.
|
|
|
|
| 1 |
"""ctx — skill and agent recommendation for Claude Code."""
|
| 2 |
|
| 3 |
+
__version__ = "1.0.20"
|
src/agent_add.py
CHANGED
|
@@ -32,6 +32,10 @@ from ctx.adapters.claude_code.install.install_utils import safe_copy_file
|
|
| 32 |
from intake_pipeline import IntakeRejected, check_intake, record_embedding
|
| 33 |
from wiki_batch_entities import generate_agent_page
|
| 34 |
from ctx.core.wiki.wiki_queue import enqueue_entity_upsert
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
from ctx.core.wiki.wiki_sync import append_log, ensure_wiki, update_index
|
| 36 |
from ctx.core.wiki.wiki_utils import validate_skill_name
|
| 37 |
from ctx.utils._fs_utils import reject_symlink_path, safe_atomic_write_text
|
|
@@ -63,16 +67,39 @@ def mirror_agent_body(installed_path: Path, wiki_path: Path, name: str) -> Path:
|
|
| 63 |
|
| 64 |
def write_entity_page(wiki_path: Path, name: str, content: str) -> bool:
|
| 65 |
"""Write agent entity page. Returns True if newly created."""
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
return is_new
|
| 71 |
|
| 72 |
|
| 73 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
if entity_page.exists():
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
if installed_path.exists():
|
| 77 |
installed = installed_path.read_text(encoding="utf-8", errors="replace")
|
| 78 |
existing += f"\n\n## Installed agent definition\n\n{installed}"
|
|
@@ -113,23 +140,20 @@ def add_agent(
|
|
| 113 |
f"{_MAX_AGENT_BYTES:,}. Trim before ingestion."
|
| 114 |
)
|
| 115 |
|
| 116 |
-
content = source_path.read_text(encoding="utf-8", errors="replace")
|
| 117 |
line_count = len(content.splitlines())
|
| 118 |
|
| 119 |
installed_path = agents_dir / f"{name}.md"
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
if installed_path.exists()
|
| 124 |
-
else entity_page if entity_page.exists() else None
|
| 125 |
)
|
| 126 |
-
has_existing = existing_path is not None
|
| 127 |
|
| 128 |
if review_existing and has_existing and not update_existing:
|
| 129 |
review = build_update_review(
|
| 130 |
entity_type="agent",
|
| 131 |
slug=name,
|
| 132 |
-
existing_text=_existing_agent_review_text(
|
| 133 |
proposed_text=_proposed_agent_review_text(
|
| 134 |
name=name,
|
| 135 |
source_path=source_path,
|
|
@@ -319,6 +343,8 @@ def main() -> None:
|
|
| 319 |
f"\nDone: {added} added, {updated} updated, {skipped} skipped, "
|
| 320 |
f"{rejected} rejected, {errors} errors"
|
| 321 |
)
|
|
|
|
|
|
|
| 322 |
|
| 323 |
|
| 324 |
if __name__ == "__main__":
|
|
|
|
| 32 |
from intake_pipeline import IntakeRejected, check_intake, record_embedding
|
| 33 |
from wiki_batch_entities import generate_agent_page
|
| 34 |
from ctx.core.wiki.wiki_queue import enqueue_entity_upsert
|
| 35 |
+
from ctx.core.wiki.wiki_packs import (
|
| 36 |
+
load_merged_wiki_pages,
|
| 37 |
+
write_active_wiki_overlay_pack,
|
| 38 |
+
)
|
| 39 |
from ctx.core.wiki.wiki_sync import append_log, ensure_wiki, update_index
|
| 40 |
from ctx.core.wiki.wiki_utils import validate_skill_name
|
| 41 |
from ctx.utils._fs_utils import reject_symlink_path, safe_atomic_write_text
|
|
|
|
| 67 |
|
| 68 |
def write_entity_page(wiki_path: Path, name: str, content: str) -> bool:
|
| 69 |
"""Write agent entity page. Returns True if newly created."""
|
| 70 |
+
relpath = f"entities/agents/{name}.md"
|
| 71 |
+
page = wiki_path / relpath
|
| 72 |
+
packs_dir = wiki_path / "wiki-packs"
|
| 73 |
+
is_new = _read_entity_page_text(wiki_path, name) is None
|
| 74 |
+
if page.exists() or not packs_dir.is_dir():
|
| 75 |
+
reject_symlink_path(page)
|
| 76 |
+
safe_atomic_write_text(page, content, encoding="utf-8")
|
| 77 |
+
if packs_dir.is_dir():
|
| 78 |
+
write_active_wiki_overlay_pack(
|
| 79 |
+
packs_dir=packs_dir,
|
| 80 |
+
pages={relpath: content},
|
| 81 |
+
tombstones=[],
|
| 82 |
+
)
|
| 83 |
return is_new
|
| 84 |
|
| 85 |
|
| 86 |
+
def _read_entity_page_text(wiki_path: Path, name: str) -> str | None:
|
| 87 |
+
relpath = f"entities/agents/{name}.md"
|
| 88 |
+
packs_dir = wiki_path / "wiki-packs"
|
| 89 |
+
if packs_dir.is_dir():
|
| 90 |
+
pages = load_merged_wiki_pages(packs_dir)
|
| 91 |
+
if relpath in pages:
|
| 92 |
+
return pages[relpath]
|
| 93 |
+
entity_page = wiki_path / relpath
|
| 94 |
if entity_page.exists():
|
| 95 |
+
return entity_page.read_text(encoding="utf-8", errors="replace")
|
| 96 |
+
return None
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _existing_agent_review_text(wiki_path: Path, name: str, installed_path: Path) -> str:
|
| 100 |
+
existing_page = _read_entity_page_text(wiki_path, name)
|
| 101 |
+
if existing_page is not None:
|
| 102 |
+
existing = existing_page
|
| 103 |
if installed_path.exists():
|
| 104 |
installed = installed_path.read_text(encoding="utf-8", errors="replace")
|
| 105 |
existing += f"\n\n## Installed agent definition\n\n{installed}"
|
|
|
|
| 140 |
f"{_MAX_AGENT_BYTES:,}. Trim before ingestion."
|
| 141 |
)
|
| 142 |
|
| 143 |
+
content = source_path.read_text(encoding="utf-8-sig", errors="replace")
|
| 144 |
line_count = len(content.splitlines())
|
| 145 |
|
| 146 |
installed_path = agents_dir / f"{name}.md"
|
| 147 |
+
has_existing = (
|
| 148 |
+
installed_path.exists()
|
| 149 |
+
or _read_entity_page_text(wiki_path, name) is not None
|
|
|
|
|
|
|
| 150 |
)
|
|
|
|
| 151 |
|
| 152 |
if review_existing and has_existing and not update_existing:
|
| 153 |
review = build_update_review(
|
| 154 |
entity_type="agent",
|
| 155 |
slug=name,
|
| 156 |
+
existing_text=_existing_agent_review_text(wiki_path, name, installed_path),
|
| 157 |
proposed_text=_proposed_agent_review_text(
|
| 158 |
name=name,
|
| 159 |
source_path=source_path,
|
|
|
|
| 343 |
f"\nDone: {added} added, {updated} updated, {skipped} skipped, "
|
| 344 |
f"{rejected} rejected, {errors} errors"
|
| 345 |
)
|
| 346 |
+
if rejected or errors:
|
| 347 |
+
sys.exit(1)
|
| 348 |
|
| 349 |
|
| 350 |
if __name__ == "__main__":
|
src/backup_mirror.py
CHANGED
|
@@ -212,12 +212,6 @@ def _iter_memory_files() -> Iterable[tuple[str, Path]]:
|
|
| 212 |
# ── Hashing + atomic copy ───────────────────────────────────────────────────
|
| 213 |
|
| 214 |
|
| 215 |
-
def _sha256_bytes(data: bytes) -> str:
|
| 216 |
-
h = hashlib.sha256()
|
| 217 |
-
h.update(data)
|
| 218 |
-
return h.hexdigest()
|
| 219 |
-
|
| 220 |
-
|
| 221 |
def _sha256_file(path: Path) -> str:
|
| 222 |
# Reject symlinks before reading so verify never hashes a file the
|
| 223 |
# attacker has pointed out of the snapshot.
|
|
|
|
| 212 |
# ── Hashing + atomic copy ───────────────────────────────────────────────────
|
| 213 |
|
| 214 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
def _sha256_file(path: Path) -> str:
|
| 216 |
# Reject symlinks before reading so verify never hashes a file the
|
| 217 |
# attacker has pointed out of the snapshot.
|
src/catalog_builder.py
CHANGED
|
@@ -22,11 +22,43 @@ import sys
|
|
| 22 |
from datetime import datetime, timezone
|
| 23 |
from pathlib import Path
|
| 24 |
|
|
|
|
| 25 |
from ctx_config import cfg
|
| 26 |
|
| 27 |
TODAY = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
| 28 |
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
def scan_skills_dir(skills_dir: Path) -> list[dict]:
|
| 31 |
"""Scan a directory for skills (subdirs with SKILL.md)."""
|
| 32 |
results: list[dict[str, object]] = []
|
|
@@ -133,7 +165,7 @@ def build_catalog(
|
|
| 133 |
)
|
| 134 |
|
| 135 |
catalog_path = wiki_dir / "catalog.md"
|
| 136 |
-
|
| 137 |
|
| 138 |
return {
|
| 139 |
"total": total,
|
|
@@ -146,11 +178,9 @@ def build_catalog(
|
|
| 146 |
|
| 147 |
def update_wiki_index(wiki_dir: Path, stats: dict) -> None:
|
| 148 |
"""Update index.md with catalog reference."""
|
| 149 |
-
|
| 150 |
-
if
|
| 151 |
return
|
| 152 |
-
|
| 153 |
-
content = index_path.read_text(encoding="utf-8")
|
| 154 |
catalog_ref = "- [[catalog]] - Full skill catalog (all installed items)"
|
| 155 |
|
| 156 |
if "[[catalog]]" not in content:
|
|
@@ -175,13 +205,13 @@ def update_wiki_index(wiki_dir: Path, stats: dict) -> None:
|
|
| 175 |
f"Last updated: {TODAY}",
|
| 176 |
content,
|
| 177 |
)
|
| 178 |
-
|
| 179 |
|
| 180 |
|
| 181 |
def append_log(wiki_dir: Path, stats: dict) -> None:
|
| 182 |
"""Append catalog build entry to log.md."""
|
| 183 |
-
|
| 184 |
-
if
|
| 185 |
return
|
| 186 |
|
| 187 |
entry = (
|
|
@@ -191,8 +221,7 @@ def append_log(wiki_dir: Path, stats: dict) -> None:
|
|
| 191 |
f"- Over 180 lines (micro-skill candidates): {stats['over_180']}\n"
|
| 192 |
f"- Catalog written to: {stats['catalog_path']}\n"
|
| 193 |
)
|
| 194 |
-
|
| 195 |
-
f.write(entry)
|
| 196 |
|
| 197 |
|
| 198 |
def main() -> None:
|
|
|
|
| 22 |
from datetime import datetime, timezone
|
| 23 |
from pathlib import Path
|
| 24 |
|
| 25 |
+
from ctx.core.wiki.wiki_packs import load_merged_wiki_pages, write_active_wiki_overlay_pack
|
| 26 |
from ctx_config import cfg
|
| 27 |
|
| 28 |
TODAY = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
| 29 |
|
| 30 |
|
| 31 |
+
def _read_wiki_page(wiki_dir: Path, relpath: str) -> str | None:
|
| 32 |
+
"""Read a wiki page from active packs when installed, else from disk."""
|
| 33 |
+
packs_dir = wiki_dir / "wiki-packs"
|
| 34 |
+
path = wiki_dir / relpath
|
| 35 |
+
if packs_dir.is_dir():
|
| 36 |
+
pages = load_merged_wiki_pages(packs_dir)
|
| 37 |
+
if relpath in pages:
|
| 38 |
+
return pages[relpath]
|
| 39 |
+
if path.exists():
|
| 40 |
+
return path.read_text(encoding="utf-8", errors="replace")
|
| 41 |
+
return None
|
| 42 |
+
if not path.exists():
|
| 43 |
+
return None
|
| 44 |
+
return path.read_text(encoding="utf-8", errors="replace")
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _write_wiki_page(wiki_dir: Path, relpath: str, content: str) -> None:
|
| 48 |
+
"""Write a wiki page, mirroring into overlay packs when installed."""
|
| 49 |
+
packs_dir = wiki_dir / "wiki-packs"
|
| 50 |
+
path = wiki_dir / relpath
|
| 51 |
+
if path.exists() or not packs_dir.is_dir():
|
| 52 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 53 |
+
path.write_text(content, encoding="utf-8")
|
| 54 |
+
if packs_dir.is_dir():
|
| 55 |
+
write_active_wiki_overlay_pack(
|
| 56 |
+
packs_dir=packs_dir,
|
| 57 |
+
pages={relpath: content},
|
| 58 |
+
tombstones=[],
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
def scan_skills_dir(skills_dir: Path) -> list[dict]:
|
| 63 |
"""Scan a directory for skills (subdirs with SKILL.md)."""
|
| 64 |
results: list[dict[str, object]] = []
|
|
|
|
| 165 |
)
|
| 166 |
|
| 167 |
catalog_path = wiki_dir / "catalog.md"
|
| 168 |
+
_write_wiki_page(wiki_dir, "catalog.md", "\n".join(lines) + "\n")
|
| 169 |
|
| 170 |
return {
|
| 171 |
"total": total,
|
|
|
|
| 178 |
|
| 179 |
def update_wiki_index(wiki_dir: Path, stats: dict) -> None:
|
| 180 |
"""Update index.md with catalog reference."""
|
| 181 |
+
content = _read_wiki_page(wiki_dir, "index.md")
|
| 182 |
+
if content is None:
|
| 183 |
return
|
|
|
|
|
|
|
| 184 |
catalog_ref = "- [[catalog]] - Full skill catalog (all installed items)"
|
| 185 |
|
| 186 |
if "[[catalog]]" not in content:
|
|
|
|
| 205 |
f"Last updated: {TODAY}",
|
| 206 |
content,
|
| 207 |
)
|
| 208 |
+
_write_wiki_page(wiki_dir, "index.md", content)
|
| 209 |
|
| 210 |
|
| 211 |
def append_log(wiki_dir: Path, stats: dict) -> None:
|
| 212 |
"""Append catalog build entry to log.md."""
|
| 213 |
+
content = _read_wiki_page(wiki_dir, "log.md")
|
| 214 |
+
if content is None:
|
| 215 |
return
|
| 216 |
|
| 217 |
entry = (
|
|
|
|
| 221 |
f"- Over 180 lines (micro-skill candidates): {stats['over_180']}\n"
|
| 222 |
f"- Catalog written to: {stats['catalog_path']}\n"
|
| 223 |
)
|
| 224 |
+
_write_wiki_page(wiki_dir, "log.md", content + entry)
|
|
|
|
| 225 |
|
| 226 |
|
| 227 |
def main() -> None:
|
src/config.json
CHANGED
|
@@ -41,6 +41,72 @@
|
|
| 41 |
"keep_log_days": 5
|
| 42 |
},
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
"harness": {
|
| 45 |
"_comment": "Harness catalog recommendation tuning for custom/API/local model users. Harnesses are separate from the execution bundle and are only recommended when their absolute fit score is at or above recommendation_min_fit_score. The normalized floor is kept for older user configs and display compatibility.",
|
| 46 |
"recommendation_min_normalized_score": 0.85,
|
|
@@ -106,6 +172,10 @@
|
|
| 106 |
"_comment": "Source-overlap edge construction. Pages with the same repo/source/homepage/detail/package URL can connect even when their tags differ. Buckets above dense_source_threshold are skipped so broad catalog URLs cannot create noise edges.",
|
| 107 |
"dense_source_threshold": 50
|
| 108 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
"edge_boosts": {
|
| 110 |
"_comment": "Additive edge boosts. These never create edges alone; they only strengthen pairs already justified by semantic, tags, slug tokens, source overlap, or direct wikilinks. Set a value to 0 to disable that signal.",
|
| 111 |
"direct_link": 0.10,
|
|
|
|
| 41 |
"keep_log_days": 5
|
| 42 |
},
|
| 43 |
|
| 44 |
+
"telemetry": {
|
| 45 |
+
"_comment": "Enterprise telemetry spine. Writes a redacted ctx.telemetry.v1 JSONL spool by default. Exporters are ready to use but disabled until explicitly enabled.",
|
| 46 |
+
"enabled": true,
|
| 47 |
+
"mode": "local_redacted",
|
| 48 |
+
"path": "~/.ctx/telemetry/events.jsonl",
|
| 49 |
+
"export": {
|
| 50 |
+
"enabled": false,
|
| 51 |
+
"sink": "otlp_http",
|
| 52 |
+
"path": "~/.ctx/telemetry/exported-events.jsonl",
|
| 53 |
+
"otlp": {
|
| 54 |
+
"endpoint": "http://localhost:4318/v1/logs",
|
| 55 |
+
"allowed_hosts": [],
|
| 56 |
+
"headers": {},
|
| 57 |
+
"timeout_seconds": 5.0,
|
| 58 |
+
"service_name": "ctx",
|
| 59 |
+
"service_namespace": "ctx",
|
| 60 |
+
"deployment_environment": "local"
|
| 61 |
+
}
|
| 62 |
+
},
|
| 63 |
+
"metrics": {
|
| 64 |
+
"_comment": "OpenTelemetry-style counters and histograms. Writes a separate redacted metric spool by default; metric exporters use independent checkpoint/status files.",
|
| 65 |
+
"enabled": true,
|
| 66 |
+
"path": "~/.ctx/telemetry/metrics.jsonl",
|
| 67 |
+
"histogram_bounds": [1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000],
|
| 68 |
+
"export": {
|
| 69 |
+
"enabled": false,
|
| 70 |
+
"sink": "otlp_http",
|
| 71 |
+
"path": "~/.ctx/telemetry/exported-metrics.jsonl",
|
| 72 |
+
"otlp": {
|
| 73 |
+
"endpoint": "http://localhost:4318/v1/metrics",
|
| 74 |
+
"allowed_hosts": [],
|
| 75 |
+
"headers": {},
|
| 76 |
+
"timeout_seconds": 5.0,
|
| 77 |
+
"service_name": "ctx",
|
| 78 |
+
"service_namespace": "ctx",
|
| 79 |
+
"deployment_environment": "local"
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
},
|
| 83 |
+
"privacy": {
|
| 84 |
+
"store_raw_inputs": false,
|
| 85 |
+
"hash_identifiers": true,
|
| 86 |
+
"hash_salt_env": "CTX_TELEMETRY_HASH_SALT",
|
| 87 |
+
"hash_salt_path": "~/.ctx/telemetry/hash-salt"
|
| 88 |
+
},
|
| 89 |
+
"retention": {
|
| 90 |
+
"_comment": "Retention is applied only by explicit operator command/API calls. Dry-runs do not write, malformed records are preserved by default, and min_keep_records prevents accidental full deletion.",
|
| 91 |
+
"enabled": true,
|
| 92 |
+
"status_path": "~/.ctx/telemetry/retention-status.json",
|
| 93 |
+
"min_keep_records": 1000,
|
| 94 |
+
"drop_malformed": false,
|
| 95 |
+
"events": {
|
| 96 |
+
"max_age_days": 90,
|
| 97 |
+
"max_records": 100000
|
| 98 |
+
},
|
| 99 |
+
"metrics": {
|
| 100 |
+
"max_age_days": 30,
|
| 101 |
+
"max_records": 200000
|
| 102 |
+
}
|
| 103 |
+
},
|
| 104 |
+
"limits": {
|
| 105 |
+
"max_payload_keys": 40,
|
| 106 |
+
"max_payload_value_chars": 1024
|
| 107 |
+
}
|
| 108 |
+
},
|
| 109 |
+
|
| 110 |
"harness": {
|
| 111 |
"_comment": "Harness catalog recommendation tuning for custom/API/local model users. Harnesses are separate from the execution bundle and are only recommended when their absolute fit score is at or above recommendation_min_fit_score. The normalized floor is kept for older user configs and display compatibility.",
|
| 112 |
"recommendation_min_normalized_score": 0.85,
|
|
|
|
| 172 |
"_comment": "Source-overlap edge construction. Pages with the same repo/source/homepage/detail/package URL can connect even when their tags differ. Buckets above dense_source_threshold are skipped so broad catalog URLs cannot create noise edges.",
|
| 173 |
"dense_source_threshold": 50
|
| 174 |
},
|
| 175 |
+
"pack_compaction": {
|
| 176 |
+
"_comment": "Operational threshold for modular graph/wiki maintenance. ctx writes small overlay packs for local entity updates; when either graph or wiki overlays reach this count, status reports that periodic compaction is due. Compaction still requires an explicit ctx.core.wiki.pack_compaction compact/promote command.",
|
| 177 |
+
"overlay_threshold": 25
|
| 178 |
+
},
|
| 179 |
"edge_boosts": {
|
| 180 |
"_comment": "Additive edge boosts. These never create edges alone; they only strengthen pairs already justified by semantic, tags, slug tokens, source overlap, or direct wikilinks. Set a value to 0 to disable that signal.",
|
| 181 |
"direct_link": 0.10,
|
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__ = "1.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.20"
|
| 34 |
|
| 35 |
|
| 36 |
# Public library surface — anything listed here is safe for third-
|
src/ctx/adapters/claude_code/hooks/context_monitor.py
CHANGED
|
@@ -235,7 +235,7 @@ def graph_suggest(
|
|
| 235 |
top_k = 1
|
| 236 |
top_k = min(top_k, configured_top_k, 5)
|
| 237 |
graph_path = CLAUDE_DIR / "skill-wiki" / "graphify-out" / "graph.json"
|
| 238 |
-
if not
|
| 239 |
return []
|
| 240 |
try:
|
| 241 |
from ctx.core.graph.resolve_graph import load_graph # noqa: PLC0415
|
|
@@ -257,6 +257,11 @@ def graph_suggest(
|
|
| 257 |
return []
|
| 258 |
|
| 259 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
def write_pending_skills(unmatched: list[str]) -> None:
|
| 261 |
"""Write pending bundle suggestions enriched with graph-based discovery.
|
| 262 |
|
|
|
|
| 235 |
top_k = 1
|
| 236 |
top_k = min(top_k, configured_top_k, 5)
|
| 237 |
graph_path = CLAUDE_DIR / "skill-wiki" / "graphify-out" / "graph.json"
|
| 238 |
+
if not _graph_source_available(graph_path):
|
| 239 |
return []
|
| 240 |
try:
|
| 241 |
from ctx.core.graph.resolve_graph import load_graph # noqa: PLC0415
|
|
|
|
| 257 |
return []
|
| 258 |
|
| 259 |
|
| 260 |
+
def _graph_source_available(graph_path: Path) -> bool:
|
| 261 |
+
"""Return whether the graph resolver has a legacy file or active packs."""
|
| 262 |
+
return graph_path.is_file() or (graph_path.parent / "packs").is_dir()
|
| 263 |
+
|
| 264 |
+
|
| 265 |
def write_pending_skills(unmatched: list[str]) -> None:
|
| 266 |
"""Write pending bundle suggestions enriched with graph-based discovery.
|
| 267 |
|
src/ctx/adapters/claude_code/install/mcp_install.py
CHANGED
|
@@ -223,6 +223,26 @@ def _json_config_card_summary(parsed_config: object) -> str:
|
|
| 223 |
return "; ".join(parts) if parts else "empty object"
|
| 224 |
|
| 225 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
@dataclass(frozen=True)
|
| 227 |
class InstallResult:
|
| 228 |
slug: str
|
|
@@ -415,8 +435,8 @@ def install_mcp(
|
|
| 415 |
|
| 416 |
if existing_status == "installed" and not force:
|
| 417 |
skipped_extra: dict[str, str] = {}
|
| 418 |
-
install_cmd = fm.get("install_cmd")
|
| 419 |
-
if
|
| 420 |
skipped_extra["command"] = install_cmd
|
| 421 |
record_install(
|
| 422 |
slug,
|
|
|
|
| 223 |
return "; ".join(parts) if parts else "empty object"
|
| 224 |
|
| 225 |
|
| 226 |
+
def _safe_manifest_command(command: object) -> str | None:
|
| 227 |
+
"""Return command text safe enough to persist in advisory manifests."""
|
| 228 |
+
if not isinstance(command, str) or not command.strip():
|
| 229 |
+
return None
|
| 230 |
+
try:
|
| 231 |
+
tokens = _split_install_command(command)
|
| 232 |
+
except ValueError:
|
| 233 |
+
return None
|
| 234 |
+
if not tokens:
|
| 235 |
+
return None
|
| 236 |
+
if _find_inline_secret_arg(tokens) is not None:
|
| 237 |
+
return None
|
| 238 |
+
executable = _normalized_executable(tokens[0])
|
| 239 |
+
if executable not in _ALLOWED_CMD_EXECS:
|
| 240 |
+
return None
|
| 241 |
+
if _rejects_banned_args(tokens) is not None:
|
| 242 |
+
return None
|
| 243 |
+
return _redact_output(command)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
@dataclass(frozen=True)
|
| 247 |
class InstallResult:
|
| 248 |
slug: str
|
|
|
|
| 435 |
|
| 436 |
if existing_status == "installed" and not force:
|
| 437 |
skipped_extra: dict[str, str] = {}
|
| 438 |
+
install_cmd = _safe_manifest_command(fm.get("install_cmd"))
|
| 439 |
+
if install_cmd:
|
| 440 |
skipped_extra["command"] = install_cmd
|
| 441 |
record_install(
|
| 442 |
slug,
|
src/ctx/adapters/claude_code/install/skill_unload.py
CHANGED
|
@@ -17,8 +17,23 @@ import json
|
|
| 17 |
import os
|
| 18 |
import re
|
| 19 |
import sys
|
|
|
|
|
|
|
|
|
|
| 20 |
from pathlib import Path
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
from ctx.core.wiki.wiki_utils import validate_skill_name
|
| 23 |
from ctx.utils._file_lock import file_lock
|
| 24 |
from ctx.utils._fs_utils import atomic_write_text as _atomic_write_text
|
|
@@ -32,23 +47,59 @@ SKILL_ENTITIES = WIKI_DIR / "entities" / "skills"
|
|
| 32 |
AGENT_ENTITIES = WIKI_DIR / "entities" / "agents"
|
| 33 |
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
return None
|
| 45 |
|
| 46 |
|
| 47 |
-
def
|
| 48 |
-
"""Best-effort mirror of never_load into graph
|
| 49 |
-
node_id =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
if node_id is None:
|
| 51 |
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
graph_json = WIKI_DIR / "graphify-out" / "graph.json"
|
| 53 |
if not graph_json.is_file():
|
| 54 |
return False
|
|
@@ -73,12 +124,127 @@ def _sync_graph_never_load(name: str, page: Path, value: bool) -> bool:
|
|
| 73 |
return True
|
| 74 |
|
| 75 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
def _sanitize_yaml_value(value: str) -> str:
|
| 78 |
"""Strip newlines/CRs so a value can't inject extra YAML keys."""
|
| 79 |
return value.replace("\r", " ").replace("\n", " ").strip()
|
| 80 |
|
| 81 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
def load_manifest() -> dict:
|
| 83 |
if MANIFEST_PATH.exists():
|
| 84 |
try:
|
|
@@ -92,6 +258,18 @@ def save_manifest(manifest: dict) -> None:
|
|
| 92 |
_atomic_write_text(MANIFEST_PATH, json.dumps(manifest, indent=2))
|
| 93 |
|
| 94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
def set_frontmatter_field(filepath: Path, field: str, value: str) -> bool:
|
| 96 |
"""Set a YAML frontmatter field in a wiki entity page. Returns True if changed.
|
| 97 |
|
|
@@ -101,22 +279,32 @@ def set_frontmatter_field(filepath: Path, field: str, value: str) -> bool:
|
|
| 101 |
"""
|
| 102 |
if not filepath.exists():
|
| 103 |
return False
|
| 104 |
-
safe_value = _sanitize_yaml_value(value)
|
| 105 |
-
escaped_field = re.escape(field)
|
| 106 |
content = filepath.read_text(encoding="utf-8", errors="replace")
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
new_content, count = re.subn(pattern, replacement, content, count=1, flags=re.MULTILINE)
|
| 110 |
-
if count == 0:
|
| 111 |
-
# Field doesn't exist — add it after the opening frontmatter delimiter.
|
| 112 |
-
new_content = re.sub(r"(---\n)", rf"\1{field}: {safe_value}\n", content, count=1)
|
| 113 |
-
if new_content != content:
|
| 114 |
_atomic_write_text(filepath, new_content)
|
| 115 |
return True
|
| 116 |
return False
|
| 117 |
|
| 118 |
|
| 119 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
"""Find entity page for a skill or agent by name.
|
| 121 |
|
| 122 |
Hardened against path traversal (CWE-22): name is validated against
|
|
@@ -126,12 +314,10 @@ def find_entity_page(name: str) -> Path | None:
|
|
| 126 |
validate_skill_name(name)
|
| 127 |
except ValueError:
|
| 128 |
return None
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
if agent_page.exists():
|
| 134 |
-
return agent_page
|
| 135 |
return None
|
| 136 |
|
| 137 |
|
|
@@ -162,12 +348,12 @@ def unload_from_session(
|
|
| 162 |
truth log level. Fix both at the single choke point.
|
| 163 |
"""
|
| 164 |
import uuid
|
| 165 |
-
from datetime import datetime, timezone
|
| 166 |
|
| 167 |
names_set = set(names)
|
| 168 |
with file_lock(MANIFEST_PATH):
|
| 169 |
manifest = load_manifest()
|
| 170 |
removed: list[str] = []
|
|
|
|
| 171 |
remaining = []
|
| 172 |
for entry in manifest.get("load", []):
|
| 173 |
entry_type = entry.get("entity_type", "skill")
|
|
@@ -176,6 +362,7 @@ def unload_from_session(
|
|
| 176 |
and (entity_type is None or entry_type == entity_type)
|
| 177 |
):
|
| 178 |
removed.append(entry["skill"])
|
|
|
|
| 179 |
manifest.setdefault("unload", []).append(entry)
|
| 180 |
else:
|
| 181 |
remaining.append(entry)
|
|
@@ -187,26 +374,28 @@ def unload_from_session(
|
|
| 187 |
if removed:
|
| 188 |
events_path = CLAUDE_DIR / "skill-events.jsonl"
|
| 189 |
session_id = os.environ.get("CTX_SESSION_ID") or f"unload-{uuid.uuid4().hex[:8]}"
|
| 190 |
-
now_iso = datetime.now(timezone.utc).isoformat()
|
| 191 |
try:
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
|
|
|
| 204 |
print(f"Warning: failed to log unload events: {exc}", file=sys.stderr)
|
| 205 |
try:
|
| 206 |
from ctx_audit_log import log_skill_event
|
| 207 |
-
for
|
|
|
|
|
|
|
| 208 |
log_skill_event(
|
| 209 |
-
"
|
| 210 |
actor="cli", session_id=session_id,
|
| 211 |
meta={"via": "skill_unload"},
|
| 212 |
)
|
|
@@ -216,14 +405,14 @@ def unload_from_session(
|
|
| 216 |
return removed
|
| 217 |
|
| 218 |
|
| 219 |
-
def set_never_load(names: list[str]) -> list[str]:
|
| 220 |
"""Set never_load: true in wiki entity pages."""
|
| 221 |
updated: list[str] = []
|
| 222 |
for name in names:
|
| 223 |
-
page =
|
| 224 |
if page:
|
| 225 |
-
changed =
|
| 226 |
-
graph_changed =
|
| 227 |
else:
|
| 228 |
changed = graph_changed = False
|
| 229 |
if page and (changed or graph_changed):
|
|
@@ -236,14 +425,14 @@ def set_never_load(names: list[str]) -> list[str]:
|
|
| 236 |
return updated
|
| 237 |
|
| 238 |
|
| 239 |
-
def restore_load(names: list[str]) -> list[str]:
|
| 240 |
"""Remove never_load flag from wiki entity pages."""
|
| 241 |
restored: list[str] = []
|
| 242 |
for name in names:
|
| 243 |
-
page =
|
| 244 |
if page:
|
| 245 |
-
changed =
|
| 246 |
-
graph_changed =
|
| 247 |
else:
|
| 248 |
changed = graph_changed = False
|
| 249 |
if page and (changed or graph_changed):
|
|
@@ -256,23 +445,22 @@ def restore_load(names: list[str]) -> list[str]:
|
|
| 256 |
return restored
|
| 257 |
|
| 258 |
|
| 259 |
-
def get_stale_skills() -> list[str]:
|
| 260 |
"""Find all skills with status: stale in their entity pages."""
|
| 261 |
stale: list[str] = []
|
| 262 |
-
for
|
| 263 |
-
if
|
| 264 |
-
|
| 265 |
-
for page in entity_dir.glob("*.md"):
|
| 266 |
-
content = page.read_text(encoding="utf-8", errors="replace")
|
| 267 |
-
if re.search(r"^status:\s*stale", content, re.MULTILINE):
|
| 268 |
-
stale.append(page.stem)
|
| 269 |
return stale
|
| 270 |
|
| 271 |
|
| 272 |
-
def list_loaded() -> None:
|
| 273 |
"""Show currently loaded skills/agents."""
|
| 274 |
manifest = load_manifest()
|
| 275 |
-
loaded =
|
|
|
|
|
|
|
|
|
|
| 276 |
if not loaded:
|
| 277 |
print("No skills/agents currently loaded in this session.")
|
| 278 |
return
|
|
@@ -282,16 +470,12 @@ def list_loaded() -> None:
|
|
| 282 |
print(f" - {entry['skill']} (source: {source})")
|
| 283 |
|
| 284 |
|
| 285 |
-
def list_never_load() -> None:
|
| 286 |
"""Show permanently suppressed skills/agents."""
|
| 287 |
suppressed: list[str] = []
|
| 288 |
-
for
|
| 289 |
-
if
|
| 290 |
-
|
| 291 |
-
for page in entity_dir.glob("*.md"):
|
| 292 |
-
content = page.read_text(encoding="utf-8", errors="replace")
|
| 293 |
-
if re.search(r"^never_load:\s*true", content, re.MULTILINE):
|
| 294 |
-
suppressed.append(page.stem)
|
| 295 |
if not suppressed:
|
| 296 |
print("No skills/agents are permanently suppressed.")
|
| 297 |
return
|
|
@@ -301,7 +485,7 @@ def list_never_load() -> None:
|
|
| 301 |
print("\nTo restore: python src/skill_unload.py --restore <name>")
|
| 302 |
|
| 303 |
|
| 304 |
-
def main() -> None:
|
| 305 |
parser = argparse.ArgumentParser(description="Unload skills/agents from session or suppress permanently")
|
| 306 |
# ``--slug`` is an alias for ``--name`` so docs/playbooks that say
|
| 307 |
# "slug" (the canonical vocabulary everywhere else in ctx) work
|
|
@@ -313,11 +497,18 @@ def main() -> None:
|
|
| 313 |
help="Override CTX_SESSION_ID env for the emitted "
|
| 314 |
"unload events (default: env var or synthetic id)")
|
| 315 |
parser.add_argument("--permanent", action="store_true", help="Set never_load: true (won't be recommended again)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
parser.add_argument("--stale", action="store_true", help="Unload all stale skills")
|
| 317 |
parser.add_argument("--restore", help="Remove never_load flag from a skill/agent")
|
| 318 |
parser.add_argument("--list-loaded", action="store_true", help="Show currently loaded skills")
|
| 319 |
parser.add_argument("--list-never", action="store_true", help="Show permanently suppressed skills")
|
| 320 |
-
args = parser.parse_args()
|
|
|
|
| 321 |
|
| 322 |
# Propagate --session-id into the env so unload_from_session() and
|
| 323 |
# its audit-log call both tag the emitted events with the caller's
|
|
@@ -326,11 +517,11 @@ def main() -> None:
|
|
| 326 |
os.environ["CTX_SESSION_ID"] = args.session_id
|
| 327 |
|
| 328 |
if args.list_loaded:
|
| 329 |
-
list_loaded()
|
| 330 |
return
|
| 331 |
|
| 332 |
if args.list_never:
|
| 333 |
-
list_never_load()
|
| 334 |
return
|
| 335 |
|
| 336 |
if args.restore:
|
|
@@ -342,7 +533,7 @@ def main() -> None:
|
|
| 342 |
except ValueError as exc:
|
| 343 |
print(f"Skipping invalid name {n!r}: {exc}", file=sys.stderr)
|
| 344 |
if valid:
|
| 345 |
-
restore_load(valid)
|
| 346 |
return
|
| 347 |
|
| 348 |
names: list[str] = []
|
|
@@ -351,7 +542,7 @@ def main() -> None:
|
|
| 351 |
if args.names:
|
| 352 |
names.extend(n.strip() for n in args.names.split(","))
|
| 353 |
if args.stale:
|
| 354 |
-
stale = get_stale_skills()
|
| 355 |
print(f"Found {len(stale)} stale skills")
|
| 356 |
names.extend(stale)
|
| 357 |
|
|
@@ -371,7 +562,7 @@ def main() -> None:
|
|
| 371 |
sys.exit(1)
|
| 372 |
|
| 373 |
# Unload from current session manifest
|
| 374 |
-
removed = unload_from_session(names)
|
| 375 |
if removed:
|
| 376 |
print(f"Unloaded from session: {', '.join(removed)}")
|
| 377 |
|
|
@@ -379,9 +570,9 @@ def main() -> None:
|
|
| 379 |
not_removed = [n for n in names if n not in removed]
|
| 380 |
if not_removed:
|
| 381 |
for name in not_removed:
|
| 382 |
-
page =
|
| 383 |
if page:
|
| 384 |
-
|
| 385 |
print(f" {name}: marked stale (lower priority next session)")
|
| 386 |
|
| 387 |
# Always clear from pending-unload
|
|
@@ -390,7 +581,15 @@ def main() -> None:
|
|
| 390 |
# Permanently suppress if requested
|
| 391 |
if args.permanent:
|
| 392 |
print("Setting never_load: true (will not be recommended again):")
|
| 393 |
-
set_never_load(names)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 394 |
|
| 395 |
|
| 396 |
if __name__ == "__main__":
|
|
|
|
| 17 |
import os
|
| 18 |
import re
|
| 19 |
import sys
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from datetime import datetime, timezone
|
| 22 |
+
from hashlib import sha256
|
| 23 |
from pathlib import Path
|
| 24 |
|
| 25 |
+
from ctx.core.graph.graph_packs import (
|
| 26 |
+
GraphPackManifestError,
|
| 27 |
+
discover_pack_manifests,
|
| 28 |
+
load_merged_pack_graph,
|
| 29 |
+
write_overlay_pack,
|
| 30 |
+
)
|
| 31 |
+
from ctx.core.wiki import wiki_queue
|
| 32 |
+
from ctx.core.wiki.wiki_packs import (
|
| 33 |
+
WikiPackManifestError,
|
| 34 |
+
load_merged_wiki_pages,
|
| 35 |
+
write_active_wiki_overlay_pack,
|
| 36 |
+
)
|
| 37 |
from ctx.core.wiki.wiki_utils import validate_skill_name
|
| 38 |
from ctx.utils._file_lock import file_lock
|
| 39 |
from ctx.utils._fs_utils import atomic_write_text as _atomic_write_text
|
|
|
|
| 47 |
AGENT_ENTITIES = WIKI_DIR / "entities" / "agents"
|
| 48 |
|
| 49 |
|
| 50 |
+
@dataclass(frozen=True)
|
| 51 |
+
class EntityPageRef:
|
| 52 |
+
name: str
|
| 53 |
+
subject_type: str
|
| 54 |
+
path: Path
|
| 55 |
+
relpath: str
|
| 56 |
+
content: str
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _graph_node_id_for_subject_type(name: str, subject_type: str) -> str | None:
|
| 60 |
+
if subject_type == "skills":
|
| 61 |
+
return f"skill:{name}"
|
| 62 |
+
if subject_type == "agents":
|
| 63 |
+
return f"agent:{name}"
|
| 64 |
return None
|
| 65 |
|
| 66 |
|
| 67 |
+
def _sync_graph_never_load_for_entity(ref: EntityPageRef, value: bool) -> bool:
|
| 68 |
+
"""Best-effort mirror of never_load into graph artifacts for merged wiki entities."""
|
| 69 |
+
node_id = _graph_node_id_for_subject_type(ref.name, ref.subject_type)
|
| 70 |
+
return _sync_graph_never_load_for_node(node_id, value)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _sync_graph_never_load_for_node(node_id: str | None, value: bool) -> bool:
|
| 74 |
+
"""Best-effort mirror of never_load into graph artifacts for immediate filtering."""
|
| 75 |
if node_id is None:
|
| 76 |
return False
|
| 77 |
+
legacy_changed = _sync_graph_json_never_load(node_id, value)
|
| 78 |
+
pack_changed = _sync_graph_pack_never_load(node_id, value)
|
| 79 |
+
changed = legacy_changed or pack_changed
|
| 80 |
+
if changed:
|
| 81 |
+
_queue_graph_store_refresh(node_id, value)
|
| 82 |
+
return changed
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _queue_graph_store_refresh(node_id: str, value: bool) -> None:
|
| 86 |
+
"""Queue a hot graph-store rebuild after graph metadata changes."""
|
| 87 |
+
try:
|
| 88 |
+
wiki_queue.enqueue_maintenance_job(
|
| 89 |
+
WIKI_DIR,
|
| 90 |
+
kind=wiki_queue.GRAPH_STORE_REFRESH_JOB,
|
| 91 |
+
payload={
|
| 92 |
+
"reason": "never_load",
|
| 93 |
+
"node_id": node_id,
|
| 94 |
+
"never_load": value,
|
| 95 |
+
},
|
| 96 |
+
source="skill_unload",
|
| 97 |
+
)
|
| 98 |
+
except Exception as exc: # noqa: BLE001 - refresh is best-effort for CLI UX.
|
| 99 |
+
print(f"Warning: failed to queue graph store refresh: {exc}", file=sys.stderr)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _sync_graph_json_never_load(node_id: str, value: bool) -> bool:
|
| 103 |
graph_json = WIKI_DIR / "graphify-out" / "graph.json"
|
| 104 |
if not graph_json.is_file():
|
| 105 |
return False
|
|
|
|
| 124 |
return True
|
| 125 |
|
| 126 |
|
| 127 |
+
def _sync_graph_pack_never_load(node_id: str, value: bool) -> bool:
|
| 128 |
+
packs_dir = WIKI_DIR / "graphify-out" / "packs"
|
| 129 |
+
try:
|
| 130 |
+
entries = discover_pack_manifests(packs_dir)
|
| 131 |
+
if not entries:
|
| 132 |
+
return False
|
| 133 |
+
graph = load_merged_pack_graph(packs_dir)
|
| 134 |
+
if node_id not in graph or bool(graph.nodes[node_id].get("never_load")) == value:
|
| 135 |
+
return False
|
| 136 |
+
base = entries[0].manifest
|
| 137 |
+
timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
|
| 138 |
+
digest = sha256(f"{node_id}:{value}".encode("utf-8")).hexdigest()[:12]
|
| 139 |
+
stem = node_id.replace(":", "-")
|
| 140 |
+
pack_id = f"overlay-{timestamp}-{stem}-never-load-{digest}"
|
| 141 |
+
for suffix in ["", *[f"-{index}" for index in range(1, 1000)]]:
|
| 142 |
+
candidate = f"{pack_id}{suffix}"
|
| 143 |
+
pack_dir = packs_dir / candidate
|
| 144 |
+
if pack_dir.exists():
|
| 145 |
+
continue
|
| 146 |
+
write_overlay_pack(
|
| 147 |
+
pack_dir=pack_dir,
|
| 148 |
+
pack_id=candidate,
|
| 149 |
+
base_export_id=base.base_export_id,
|
| 150 |
+
parent_export_id=base.base_export_id,
|
| 151 |
+
config_hash=base.config_hash,
|
| 152 |
+
model_id=base.model_id,
|
| 153 |
+
nodes=[{"id": node_id, "never_load": value}],
|
| 154 |
+
edges=[],
|
| 155 |
+
tombstones=[],
|
| 156 |
+
)
|
| 157 |
+
return True
|
| 158 |
+
except (GraphPackManifestError, OSError):
|
| 159 |
+
return False
|
| 160 |
+
return False
|
| 161 |
+
|
| 162 |
+
|
| 163 |
|
| 164 |
def _sanitize_yaml_value(value: str) -> str:
|
| 165 |
"""Strip newlines/CRs so a value can't inject extra YAML keys."""
|
| 166 |
return value.replace("\r", " ").replace("\n", " ").strip()
|
| 167 |
|
| 168 |
|
| 169 |
+
def _entity_subjects(entity_type: str | None = None) -> list[str]:
|
| 170 |
+
if entity_type == "skill":
|
| 171 |
+
return ["skills"]
|
| 172 |
+
if entity_type == "agent":
|
| 173 |
+
return ["agents"]
|
| 174 |
+
return ["skills", "agents"]
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _entity_dir(subject_type: str) -> Path:
|
| 178 |
+
if subject_type == "skills":
|
| 179 |
+
return SKILL_ENTITIES
|
| 180 |
+
if subject_type == "agents":
|
| 181 |
+
return AGENT_ENTITIES
|
| 182 |
+
raise ValueError(f"unknown subject_type: {subject_type}")
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _entity_relpath(subject_type: str, name: str) -> str:
|
| 186 |
+
return f"entities/{subject_type}/{name}.md"
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _iter_entity_page_refs(*, entity_type: str | None = None) -> list[EntityPageRef]:
|
| 190 |
+
packs_dir = WIKI_DIR / "wiki-packs"
|
| 191 |
+
subjects = set(_entity_subjects(entity_type))
|
| 192 |
+
if packs_dir.is_dir():
|
| 193 |
+
refs: list[EntityPageRef] = []
|
| 194 |
+
try:
|
| 195 |
+
pages = load_merged_wiki_pages(packs_dir)
|
| 196 |
+
except (WikiPackManifestError, OSError) as exc:
|
| 197 |
+
print(f"Warning: failed to read wiki packs: {exc}", file=sys.stderr)
|
| 198 |
+
pages = {}
|
| 199 |
+
for relpath, content in sorted(pages.items()):
|
| 200 |
+
path = Path(relpath)
|
| 201 |
+
if (
|
| 202 |
+
len(path.parts) == 3
|
| 203 |
+
and path.parts[0] == "entities"
|
| 204 |
+
and path.parts[1] in subjects
|
| 205 |
+
and path.suffix == ".md"
|
| 206 |
+
):
|
| 207 |
+
refs.append(EntityPageRef(
|
| 208 |
+
name=path.stem,
|
| 209 |
+
subject_type=path.parts[1],
|
| 210 |
+
path=WIKI_DIR / relpath,
|
| 211 |
+
relpath=relpath,
|
| 212 |
+
content=content,
|
| 213 |
+
))
|
| 214 |
+
return refs
|
| 215 |
+
|
| 216 |
+
legacy_refs: list[EntityPageRef] = []
|
| 217 |
+
for subject_type in _entity_subjects(entity_type):
|
| 218 |
+
entity_dir = _entity_dir(subject_type)
|
| 219 |
+
if not entity_dir.exists():
|
| 220 |
+
continue
|
| 221 |
+
for page in sorted(entity_dir.glob("*.md")):
|
| 222 |
+
try:
|
| 223 |
+
content = page.read_text(encoding="utf-8", errors="replace")
|
| 224 |
+
except OSError as exc:
|
| 225 |
+
print(f"Warning: entity page read error for {page.stem}: {exc}", file=sys.stderr)
|
| 226 |
+
continue
|
| 227 |
+
legacy_refs.append(EntityPageRef(
|
| 228 |
+
name=page.stem,
|
| 229 |
+
subject_type=subject_type,
|
| 230 |
+
path=page,
|
| 231 |
+
relpath=_entity_relpath(subject_type, page.stem),
|
| 232 |
+
content=content,
|
| 233 |
+
))
|
| 234 |
+
return legacy_refs
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def _find_entity_page_ref(name: str, *, entity_type: str | None = None) -> EntityPageRef | None:
|
| 238 |
+
try:
|
| 239 |
+
validate_skill_name(name)
|
| 240 |
+
except ValueError:
|
| 241 |
+
return None
|
| 242 |
+
for ref in _iter_entity_page_refs(entity_type=entity_type):
|
| 243 |
+
if ref.name == name:
|
| 244 |
+
return ref
|
| 245 |
+
return None
|
| 246 |
+
|
| 247 |
+
|
| 248 |
def load_manifest() -> dict:
|
| 249 |
if MANIFEST_PATH.exists():
|
| 250 |
try:
|
|
|
|
| 258 |
_atomic_write_text(MANIFEST_PATH, json.dumps(manifest, indent=2))
|
| 259 |
|
| 260 |
|
| 261 |
+
def _set_frontmatter_field_text(content: str, field: str, value: str) -> tuple[str, bool]:
|
| 262 |
+
safe_value = _sanitize_yaml_value(value)
|
| 263 |
+
escaped_field = re.escape(field)
|
| 264 |
+
pattern = rf"^{escaped_field}:\s*.+$"
|
| 265 |
+
replacement = f"{field}: {safe_value}"
|
| 266 |
+
new_content, count = re.subn(pattern, replacement, content, count=1, flags=re.MULTILINE)
|
| 267 |
+
if count == 0:
|
| 268 |
+
# Field doesn't exist; add it after the opening frontmatter delimiter.
|
| 269 |
+
new_content = re.sub(r"(---\n)", rf"\1{field}: {safe_value}\n", content, count=1)
|
| 270 |
+
return new_content, new_content != content
|
| 271 |
+
|
| 272 |
+
|
| 273 |
def set_frontmatter_field(filepath: Path, field: str, value: str) -> bool:
|
| 274 |
"""Set a YAML frontmatter field in a wiki entity page. Returns True if changed.
|
| 275 |
|
|
|
|
| 279 |
"""
|
| 280 |
if not filepath.exists():
|
| 281 |
return False
|
|
|
|
|
|
|
| 282 |
content = filepath.read_text(encoding="utf-8", errors="replace")
|
| 283 |
+
new_content, changed = _set_frontmatter_field_text(content, field, value)
|
| 284 |
+
if changed:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
_atomic_write_text(filepath, new_content)
|
| 286 |
return True
|
| 287 |
return False
|
| 288 |
|
| 289 |
|
| 290 |
+
def _set_entity_frontmatter_field(ref: EntityPageRef, field: str, value: str) -> bool:
|
| 291 |
+
new_content, changed = _set_frontmatter_field_text(ref.content, field, value)
|
| 292 |
+
if not changed:
|
| 293 |
+
return False
|
| 294 |
+
if ref.path.exists():
|
| 295 |
+
_atomic_write_text(ref.path, new_content)
|
| 296 |
+
try:
|
| 297 |
+
write_active_wiki_overlay_pack(
|
| 298 |
+
packs_dir=WIKI_DIR / "wiki-packs",
|
| 299 |
+
pages={ref.relpath: new_content},
|
| 300 |
+
tombstones=[],
|
| 301 |
+
)
|
| 302 |
+
except (WikiPackManifestError, OSError) as exc:
|
| 303 |
+
print(f"Warning: failed to mirror entity update into wiki pack: {exc}", file=sys.stderr)
|
| 304 |
+
return True
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def find_entity_page(name: str, entity_type: str | None = None) -> Path | None:
|
| 308 |
"""Find entity page for a skill or agent by name.
|
| 309 |
|
| 310 |
Hardened against path traversal (CWE-22): name is validated against
|
|
|
|
| 314 |
validate_skill_name(name)
|
| 315 |
except ValueError:
|
| 316 |
return None
|
| 317 |
+
for subject_type in _entity_subjects(entity_type):
|
| 318 |
+
page = _entity_dir(subject_type) / f"{name}.md"
|
| 319 |
+
if page.exists():
|
| 320 |
+
return page
|
|
|
|
|
|
|
| 321 |
return None
|
| 322 |
|
| 323 |
|
|
|
|
| 348 |
truth log level. Fix both at the single choke point.
|
| 349 |
"""
|
| 350 |
import uuid
|
|
|
|
| 351 |
|
| 352 |
names_set = set(names)
|
| 353 |
with file_lock(MANIFEST_PATH):
|
| 354 |
manifest = load_manifest()
|
| 355 |
removed: list[str] = []
|
| 356 |
+
removed_entries: list[dict] = []
|
| 357 |
remaining = []
|
| 358 |
for entry in manifest.get("load", []):
|
| 359 |
entry_type = entry.get("entity_type", "skill")
|
|
|
|
| 362 |
and (entity_type is None or entry_type == entity_type)
|
| 363 |
):
|
| 364 |
removed.append(entry["skill"])
|
| 365 |
+
removed_entries.append(dict(entry))
|
| 366 |
manifest.setdefault("unload", []).append(entry)
|
| 367 |
else:
|
| 368 |
remaining.append(entry)
|
|
|
|
| 374 |
if removed:
|
| 375 |
events_path = CLAUDE_DIR / "skill-events.jsonl"
|
| 376 |
session_id = os.environ.get("CTX_SESSION_ID") or f"unload-{uuid.uuid4().hex[:8]}"
|
|
|
|
| 377 |
try:
|
| 378 |
+
import skill_telemetry
|
| 379 |
+
for entry in removed_entries:
|
| 380 |
+
slug = str(entry.get("skill") or "")
|
| 381 |
+
skill_telemetry.log_event(
|
| 382 |
+
"unload",
|
| 383 |
+
slug,
|
| 384 |
+
session_id,
|
| 385 |
+
meta={"source": "skill_unload"},
|
| 386 |
+
entity_type=str(entry.get("entity_type") or "skill"),
|
| 387 |
+
path=events_path,
|
| 388 |
+
trusted_root=CLAUDE_DIR,
|
| 389 |
+
)
|
| 390 |
+
except Exception as exc: # noqa: BLE001 - event log is best-effort.
|
| 391 |
print(f"Warning: failed to log unload events: {exc}", file=sys.stderr)
|
| 392 |
try:
|
| 393 |
from ctx_audit_log import log_skill_event
|
| 394 |
+
for entry in removed_entries:
|
| 395 |
+
slug = str(entry.get("skill") or "")
|
| 396 |
+
entry_type = str(entry.get("entity_type") or "skill")
|
| 397 |
log_skill_event(
|
| 398 |
+
f"{entry_type}.unloaded", slug,
|
| 399 |
actor="cli", session_id=session_id,
|
| 400 |
meta={"via": "skill_unload"},
|
| 401 |
)
|
|
|
|
| 405 |
return removed
|
| 406 |
|
| 407 |
|
| 408 |
+
def set_never_load(names: list[str], *, entity_type: str | None = None) -> list[str]:
|
| 409 |
"""Set never_load: true in wiki entity pages."""
|
| 410 |
updated: list[str] = []
|
| 411 |
for name in names:
|
| 412 |
+
page = _find_entity_page_ref(name, entity_type=entity_type)
|
| 413 |
if page:
|
| 414 |
+
changed = _set_entity_frontmatter_field(page, "never_load", "true")
|
| 415 |
+
graph_changed = _sync_graph_never_load_for_entity(page, True)
|
| 416 |
else:
|
| 417 |
changed = graph_changed = False
|
| 418 |
if page and (changed or graph_changed):
|
|
|
|
| 425 |
return updated
|
| 426 |
|
| 427 |
|
| 428 |
+
def restore_load(names: list[str], *, entity_type: str | None = None) -> list[str]:
|
| 429 |
"""Remove never_load flag from wiki entity pages."""
|
| 430 |
restored: list[str] = []
|
| 431 |
for name in names:
|
| 432 |
+
page = _find_entity_page_ref(name, entity_type=entity_type)
|
| 433 |
if page:
|
| 434 |
+
changed = _set_entity_frontmatter_field(page, "never_load", "false")
|
| 435 |
+
graph_changed = _sync_graph_never_load_for_entity(page, False)
|
| 436 |
else:
|
| 437 |
changed = graph_changed = False
|
| 438 |
if page and (changed or graph_changed):
|
|
|
|
| 445 |
return restored
|
| 446 |
|
| 447 |
|
| 448 |
+
def get_stale_skills(*, entity_type: str | None = None) -> list[str]:
|
| 449 |
"""Find all skills with status: stale in their entity pages."""
|
| 450 |
stale: list[str] = []
|
| 451 |
+
for page in _iter_entity_page_refs(entity_type=entity_type):
|
| 452 |
+
if re.search(r"^status:\s*stale", page.content, re.MULTILINE):
|
| 453 |
+
stale.append(page.name)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 454 |
return stale
|
| 455 |
|
| 456 |
|
| 457 |
+
def list_loaded(*, entity_type: str | None = None) -> None:
|
| 458 |
"""Show currently loaded skills/agents."""
|
| 459 |
manifest = load_manifest()
|
| 460 |
+
loaded = [
|
| 461 |
+
entry for entry in manifest.get("load", [])
|
| 462 |
+
if entity_type is None or entry.get("entity_type", "skill") == entity_type
|
| 463 |
+
]
|
| 464 |
if not loaded:
|
| 465 |
print("No skills/agents currently loaded in this session.")
|
| 466 |
return
|
|
|
|
| 470 |
print(f" - {entry['skill']} (source: {source})")
|
| 471 |
|
| 472 |
|
| 473 |
+
def list_never_load(*, entity_type: str | None = None) -> None:
|
| 474 |
"""Show permanently suppressed skills/agents."""
|
| 475 |
suppressed: list[str] = []
|
| 476 |
+
for page in _iter_entity_page_refs(entity_type=entity_type):
|
| 477 |
+
if re.search(r"^never_load:\s*true", page.content, re.MULTILINE):
|
| 478 |
+
suppressed.append(page.name)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 479 |
if not suppressed:
|
| 480 |
print("No skills/agents are permanently suppressed.")
|
| 481 |
return
|
|
|
|
| 485 |
print("\nTo restore: python src/skill_unload.py --restore <name>")
|
| 486 |
|
| 487 |
|
| 488 |
+
def main(argv: list[str] | None = None, *, default_entity_type: str | None = None) -> None:
|
| 489 |
parser = argparse.ArgumentParser(description="Unload skills/agents from session or suppress permanently")
|
| 490 |
# ``--slug`` is an alias for ``--name`` so docs/playbooks that say
|
| 491 |
# "slug" (the canonical vocabulary everywhere else in ctx) work
|
|
|
|
| 497 |
help="Override CTX_SESSION_ID env for the emitted "
|
| 498 |
"unload events (default: env var or synthetic id)")
|
| 499 |
parser.add_argument("--permanent", action="store_true", help="Set never_load: true (won't be recommended again)")
|
| 500 |
+
parser.add_argument(
|
| 501 |
+
"--entity-type",
|
| 502 |
+
choices=("skill", "agent"),
|
| 503 |
+
default=default_entity_type,
|
| 504 |
+
help="Limit the operation to one entity type",
|
| 505 |
+
)
|
| 506 |
parser.add_argument("--stale", action="store_true", help="Unload all stale skills")
|
| 507 |
parser.add_argument("--restore", help="Remove never_load flag from a skill/agent")
|
| 508 |
parser.add_argument("--list-loaded", action="store_true", help="Show currently loaded skills")
|
| 509 |
parser.add_argument("--list-never", action="store_true", help="Show permanently suppressed skills")
|
| 510 |
+
args = parser.parse_args(argv)
|
| 511 |
+
entity_type = args.entity_type
|
| 512 |
|
| 513 |
# Propagate --session-id into the env so unload_from_session() and
|
| 514 |
# its audit-log call both tag the emitted events with the caller's
|
|
|
|
| 517 |
os.environ["CTX_SESSION_ID"] = args.session_id
|
| 518 |
|
| 519 |
if args.list_loaded:
|
| 520 |
+
list_loaded(entity_type=entity_type)
|
| 521 |
return
|
| 522 |
|
| 523 |
if args.list_never:
|
| 524 |
+
list_never_load(entity_type=entity_type)
|
| 525 |
return
|
| 526 |
|
| 527 |
if args.restore:
|
|
|
|
| 533 |
except ValueError as exc:
|
| 534 |
print(f"Skipping invalid name {n!r}: {exc}", file=sys.stderr)
|
| 535 |
if valid:
|
| 536 |
+
restore_load(valid, entity_type=entity_type)
|
| 537 |
return
|
| 538 |
|
| 539 |
names: list[str] = []
|
|
|
|
| 542 |
if args.names:
|
| 543 |
names.extend(n.strip() for n in args.names.split(","))
|
| 544 |
if args.stale:
|
| 545 |
+
stale = get_stale_skills(entity_type=entity_type)
|
| 546 |
print(f"Found {len(stale)} stale skills")
|
| 547 |
names.extend(stale)
|
| 548 |
|
|
|
|
| 562 |
sys.exit(1)
|
| 563 |
|
| 564 |
# Unload from current session manifest
|
| 565 |
+
removed = unload_from_session(names, entity_type=entity_type)
|
| 566 |
if removed:
|
| 567 |
print(f"Unloaded from session: {', '.join(removed)}")
|
| 568 |
|
|
|
|
| 570 |
not_removed = [n for n in names if n not in removed]
|
| 571 |
if not_removed:
|
| 572 |
for name in not_removed:
|
| 573 |
+
page = _find_entity_page_ref(name, entity_type=entity_type)
|
| 574 |
if page:
|
| 575 |
+
_set_entity_frontmatter_field(page, "status", "stale")
|
| 576 |
print(f" {name}: marked stale (lower priority next session)")
|
| 577 |
|
| 578 |
# Always clear from pending-unload
|
|
|
|
| 581 |
# Permanently suppress if requested
|
| 582 |
if args.permanent:
|
| 583 |
print("Setting never_load: true (will not be recommended again):")
|
| 584 |
+
set_never_load(names, entity_type=entity_type)
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
def skill_main() -> None:
|
| 588 |
+
main(default_entity_type="skill")
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
def agent_main() -> None:
|
| 592 |
+
main(default_entity_type="agent")
|
| 593 |
|
| 594 |
|
| 595 |
if __name__ == "__main__":
|
src/ctx/adapters/claude_code/install/skillspector_scan.py
CHANGED
|
@@ -1,184 +1,15 @@
|
|
| 1 |
-
"""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
-
import
|
| 6 |
-
import
|
| 7 |
-
import
|
| 8 |
-
import
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
"""Result from a best-effort SkillSpector scan."""
|
| 17 |
-
|
| 18 |
-
status: str # passed | findings | missing | error | skipped
|
| 19 |
-
command: list[str]
|
| 20 |
-
exit_code: int | None
|
| 21 |
-
output: str
|
| 22 |
-
|
| 23 |
-
def to_json(self) -> dict[str, object]:
|
| 24 |
-
return asdict(self)
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
_SAFE_ENV_KEYS = {
|
| 28 |
-
"APPDATA",
|
| 29 |
-
"COMSPEC",
|
| 30 |
-
"HOME",
|
| 31 |
-
"LANG",
|
| 32 |
-
"LC_ALL",
|
| 33 |
-
"PATH",
|
| 34 |
-
"PATHEXT",
|
| 35 |
-
"REQUESTS_CA_BUNDLE",
|
| 36 |
-
"SSL_CERT_FILE",
|
| 37 |
-
"SYSTEMROOT",
|
| 38 |
-
"TEMP",
|
| 39 |
-
"TMP",
|
| 40 |
-
"TMPDIR",
|
| 41 |
-
"USERPROFILE",
|
| 42 |
-
"VIRTUAL_ENV",
|
| 43 |
-
"WINDIR",
|
| 44 |
-
}
|
| 45 |
-
_ANSI_CSI_RE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
|
| 46 |
-
_ANSI_OSC_RE = re.compile(r"\x1b\][^\x07]*(?:\x07|\x1b\\)")
|
| 47 |
-
_SECRET_ASSIGNMENT_RE = re.compile(
|
| 48 |
-
r"(?i)\b((?:[A-Z0-9_]*"
|
| 49 |
-
r"(?:API[_-]?KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)"
|
| 50 |
-
r"[A-Z0-9_]*|HF_TOKEN|GITHUB_TOKEN|OPENAI_API_KEY)"
|
| 51 |
-
r"\s*[:=]\s*)([^\s]+)"
|
| 52 |
-
)
|
| 53 |
-
_KNOWN_TOKEN_RE = re.compile(
|
| 54 |
-
r"\b(?:gh[pousr]_[A-Za-z0-9_]{20,}|hf_[A-Za-z0-9]{20,}|"
|
| 55 |
-
r"sk-[A-Za-z0-9_-]{20,})\b"
|
| 56 |
-
)
|
| 57 |
-
_MAX_OUTPUT_CHARS = 20_000
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
def _resolve_command(
|
| 61 |
-
command: Sequence[str] | None = None,
|
| 62 |
-
binary: str | None = None,
|
| 63 |
-
) -> list[str] | None:
|
| 64 |
-
if command:
|
| 65 |
-
return [str(part) for part in command]
|
| 66 |
-
configured = binary or os.environ.get("CTX_SKILLSPECTOR_BIN") or "skillspector"
|
| 67 |
-
if os.sep in configured or (os.altsep and os.altsep in configured):
|
| 68 |
-
return [configured] if Path(configured).exists() else None
|
| 69 |
-
found = shutil.which(configured)
|
| 70 |
-
return [found] if found else None
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
def _scanner_env(*, use_llm: bool) -> dict[str, str] | None:
|
| 74 |
-
if use_llm:
|
| 75 |
-
return None
|
| 76 |
-
safe: dict[str, str] = {}
|
| 77 |
-
for key, value in os.environ.items():
|
| 78 |
-
if key.upper() in _SAFE_ENV_KEYS:
|
| 79 |
-
safe[key] = value
|
| 80 |
-
return safe
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
def _stringify_output(value: str | bytes | None) -> str:
|
| 84 |
-
if value is None:
|
| 85 |
-
return ""
|
| 86 |
-
if isinstance(value, bytes):
|
| 87 |
-
return value.decode("utf-8", errors="replace")
|
| 88 |
-
return value
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
def _sanitize_output(output: str) -> str:
|
| 92 |
-
clean = _ANSI_OSC_RE.sub("", output)
|
| 93 |
-
clean = _ANSI_CSI_RE.sub("", clean)
|
| 94 |
-
clean = _SECRET_ASSIGNMENT_RE.sub(r"\1[REDACTED]", clean)
|
| 95 |
-
clean = _KNOWN_TOKEN_RE.sub("[REDACTED]", clean)
|
| 96 |
-
if len(clean) > _MAX_OUTPUT_CHARS:
|
| 97 |
-
clean = clean[:_MAX_OUTPUT_CHARS] + "\n[truncated SkillSpector output]"
|
| 98 |
-
return clean
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
def run_skillspector_scan(
|
| 102 |
-
target: Path,
|
| 103 |
-
*,
|
| 104 |
-
command: Sequence[str] | None = None,
|
| 105 |
-
binary: str | None = None,
|
| 106 |
-
use_llm: bool = False,
|
| 107 |
-
timeout_seconds: int = 120,
|
| 108 |
-
) -> SkillSpectorResult:
|
| 109 |
-
"""Run SkillSpector against ``target`` and return captured output.
|
| 110 |
-
|
| 111 |
-
SkillSpector is intentionally an external tool here. ctx supports Python
|
| 112 |
-
3.11 while SkillSpector currently requires Python 3.12+, so depending on
|
| 113 |
-
the package directly would make ordinary ctx installs heavier and less
|
| 114 |
-
portable. The adapter runs static-only scans by default and preserves the
|
| 115 |
-
tool's stdout/stderr so the user sees SkillSpector's own report.
|
| 116 |
-
"""
|
| 117 |
-
resolved = _resolve_command(command=command, binary=binary)
|
| 118 |
-
if resolved is None:
|
| 119 |
-
return SkillSpectorResult(
|
| 120 |
-
status="missing",
|
| 121 |
-
command=[binary or os.environ.get("CTX_SKILLSPECTOR_BIN") or "skillspector"],
|
| 122 |
-
exit_code=None,
|
| 123 |
-
output=(
|
| 124 |
-
"SkillSpector is not installed or not on PATH. Install it, or set "
|
| 125 |
-
"CTX_SKILLSPECTOR_BIN to the scanner executable."
|
| 126 |
-
),
|
| 127 |
-
)
|
| 128 |
-
|
| 129 |
-
scan_command = [
|
| 130 |
-
*resolved,
|
| 131 |
-
"scan",
|
| 132 |
-
str(target),
|
| 133 |
-
"--format",
|
| 134 |
-
"terminal",
|
| 135 |
-
]
|
| 136 |
-
if not use_llm:
|
| 137 |
-
scan_command.append("--no-llm")
|
| 138 |
-
|
| 139 |
-
try:
|
| 140 |
-
completed = subprocess.run(
|
| 141 |
-
scan_command,
|
| 142 |
-
capture_output=True,
|
| 143 |
-
text=True,
|
| 144 |
-
env=_scanner_env(use_llm=use_llm),
|
| 145 |
-
timeout=max(timeout_seconds, 1),
|
| 146 |
-
check=False,
|
| 147 |
-
)
|
| 148 |
-
except subprocess.TimeoutExpired as exc:
|
| 149 |
-
output = _stringify_output(exc.stdout) + _stringify_output(exc.stderr)
|
| 150 |
-
return SkillSpectorResult(
|
| 151 |
-
status="error",
|
| 152 |
-
command=scan_command,
|
| 153 |
-
exit_code=None,
|
| 154 |
-
output=(
|
| 155 |
-
_sanitize_output(output.strip())
|
| 156 |
-
or f"SkillSpector timed out after {timeout_seconds}s."
|
| 157 |
-
),
|
| 158 |
-
)
|
| 159 |
-
except OSError as exc:
|
| 160 |
-
return SkillSpectorResult(
|
| 161 |
-
status="error",
|
| 162 |
-
command=scan_command,
|
| 163 |
-
exit_code=None,
|
| 164 |
-
output=f"SkillSpector failed to start: {exc}",
|
| 165 |
-
)
|
| 166 |
-
|
| 167 |
-
output = "\n".join(
|
| 168 |
-
part.strip()
|
| 169 |
-
for part in (completed.stdout, completed.stderr)
|
| 170 |
-
if part and part.strip()
|
| 171 |
-
)
|
| 172 |
-
output = _sanitize_output(output)
|
| 173 |
-
if completed.returncode == 0:
|
| 174 |
-
status = "passed"
|
| 175 |
-
elif completed.returncode == 1:
|
| 176 |
-
status = "findings"
|
| 177 |
-
else:
|
| 178 |
-
status = "error"
|
| 179 |
-
return SkillSpectorResult(
|
| 180 |
-
status=status,
|
| 181 |
-
command=scan_command,
|
| 182 |
-
exit_code=completed.returncode,
|
| 183 |
-
output=output,
|
| 184 |
-
)
|
|
|
|
| 1 |
+
"""Compatibility wrapper for the ctx-wide SkillSpector service."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
+
from ctx.core.quality.skillspector_service import SkillSpectorResult
|
| 6 |
+
from ctx.core.quality.skillspector_service import render_scan_report
|
| 7 |
+
from ctx.core.quality.skillspector_service import run_skillspector_scan
|
| 8 |
+
from ctx.core.quality.skillspector_service import skill_scan_target
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"SkillSpectorResult",
|
| 12 |
+
"render_scan_report",
|
| 13 |
+
"run_skillspector_scan",
|
| 14 |
+
"skill_scan_target",
|
| 15 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/ctx/adapters/generic/ctx_core_tools.py
CHANGED
|
@@ -40,18 +40,20 @@ from __future__ import annotations
|
|
| 40 |
import hashlib
|
| 41 |
import json
|
| 42 |
import logging
|
| 43 |
-
|
| 44 |
from pathlib import Path
|
| 45 |
-
from typing import Any, Callable
|
| 46 |
|
| 47 |
from ctx.adapters.generic.providers import ToolCall, ToolDefinition
|
| 48 |
from ctx.adapters.generic.runtime_lifecycle import RuntimeLifecycleStore
|
| 49 |
from ctx.adapters.generic.tools import TOOL_SEPARATOR
|
| 50 |
from ctx.core.entity_types import (
|
| 51 |
RECOMMENDABLE_ENTITY_TYPES,
|
|
|
|
| 52 |
entity_page_path,
|
| 53 |
entity_wikilink,
|
| 54 |
)
|
|
|
|
| 55 |
|
| 56 |
|
| 57 |
_logger = logging.getLogger(__name__)
|
|
@@ -63,27 +65,179 @@ _logger = logging.getLogger(__name__)
|
|
| 63 |
# anything else falls back to its normal tool_executor.
|
| 64 |
_NAMESPACE = f"ctx{TOOL_SEPARATOR}"
|
| 65 |
_FILE_SIGNATURE_SAMPLE_BYTES = 64 * 1024
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
FileSignature = tuple[int, int, str]
|
| 68 |
-
|
|
|
|
|
|
|
| 69 |
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
| 74 |
|
| 75 |
-
``score`` is the raw graph-walk weight; ``normalized_score`` is
|
| 76 |
-
that value divided by the top score in the same result set (so
|
| 77 |
-
the highest-ranked entry is always 1.0 — lets a caller apply a
|
| 78 |
-
0.0-1.0 cutoff without knowing the absolute graph scale).
|
| 79 |
-
"""
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
|
| 89 |
class CtxCoreToolbox:
|
|
@@ -114,7 +268,7 @@ class CtxCoreToolbox:
|
|
| 114 |
self._graph: Any | None = None # networkx.Graph
|
| 115 |
self._pages: list[Any] | None = None # list[SkillPage]
|
| 116 |
self._graph_signature: GraphSignature | None = None
|
| 117 |
-
self._pages_signature:
|
| 118 |
self._semantic_signature: tuple[FileSignature | None, ...] | None = None
|
| 119 |
|
| 120 |
# ── Public Protocol surface ─────────────────────────────────────────
|
|
@@ -166,6 +320,8 @@ class CtxCoreToolbox:
|
|
| 166 |
"Default false keeps recommendations latency-safe."
|
| 167 |
),
|
| 168 |
},
|
|
|
|
|
|
|
| 169 |
},
|
| 170 |
"required": ["query"],
|
| 171 |
},
|
|
@@ -204,6 +360,8 @@ class CtxCoreToolbox:
|
|
| 204 |
"minimum": 1,
|
| 205 |
"maximum": 50,
|
| 206 |
},
|
|
|
|
|
|
|
| 207 |
},
|
| 208 |
"required": ["seeds"],
|
| 209 |
},
|
|
@@ -226,6 +384,8 @@ class CtxCoreToolbox:
|
|
| 226 |
"minimum": 1,
|
| 227 |
"maximum": 100,
|
| 228 |
},
|
|
|
|
|
|
|
| 229 |
},
|
| 230 |
"required": ["query"],
|
| 231 |
},
|
|
@@ -250,6 +410,8 @@ class CtxCoreToolbox:
|
|
| 250 |
"Use it to disambiguate duplicate slugs."
|
| 251 |
),
|
| 252 |
},
|
|
|
|
|
|
|
| 253 |
},
|
| 254 |
"required": ["slug"],
|
| 255 |
},
|
|
@@ -272,33 +434,65 @@ class CtxCoreToolbox:
|
|
| 272 |
)
|
| 273 |
local_name = call.name[len(_NAMESPACE):]
|
| 274 |
args = call.arguments or {}
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
|
| 303 |
def owns(self, tool_name: str) -> bool:
|
| 304 |
"""True when this toolbox is the dispatcher for the given name."""
|
|
@@ -384,12 +578,12 @@ class CtxCoreToolbox:
|
|
| 384 |
if model_provider or model
|
| 385 |
else []
|
| 386 |
)
|
| 387 |
-
return
|
| 388 |
"query": query,
|
| 389 |
"tags": tags,
|
| 390 |
"results": results,
|
| 391 |
"companion_harnesses": companion_harnesses,
|
| 392 |
-
})
|
| 393 |
|
| 394 |
def _dispatch_graph_query(self, args: dict[str, Any]) -> str:
|
| 395 |
seeds_raw = args.get("seeds") or []
|
|
@@ -422,7 +616,10 @@ class CtxCoreToolbox:
|
|
| 422 |
}
|
| 423 |
for r in raw
|
| 424 |
]
|
| 425 |
-
return
|
|
|
|
|
|
|
|
|
|
| 426 |
|
| 427 |
def _dispatch_wiki_search(self, args: dict[str, Any]) -> str:
|
| 428 |
query = str(args.get("query", "")).strip()
|
|
@@ -454,7 +651,10 @@ class CtxCoreToolbox:
|
|
| 454 |
}
|
| 455 |
for p in hits
|
| 456 |
]
|
| 457 |
-
return
|
|
|
|
|
|
|
|
|
|
| 458 |
|
| 459 |
def _dispatch_wiki_get(self, args: dict[str, Any]) -> str:
|
| 460 |
slug = str(args.get("slug", "")).strip()
|
|
@@ -482,10 +682,31 @@ class CtxCoreToolbox:
|
|
| 482 |
return json.dumps({"error": "wiki_dir not configured"})
|
| 483 |
|
| 484 |
candidates = _wiki_get_candidates(wiki, slug, entity_type or None)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 485 |
|
| 486 |
for candidate_type, path, wikilink in candidates:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 487 |
if path.is_file():
|
| 488 |
-
return self._serialise_page(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 489 |
|
| 490 |
return json.dumps({
|
| 491 |
"error": f"no entity page found for slug {slug!r}",
|
|
@@ -580,22 +801,38 @@ class CtxCoreToolbox:
|
|
| 580 |
raise ValueError("session_id is required")
|
| 581 |
return supplied
|
| 582 |
|
| 583 |
-
def _serialise_page(
|
| 584 |
-
|
| 585 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 586 |
try:
|
| 587 |
text = path.read_text(encoding="utf-8", errors="replace")
|
| 588 |
except OSError as exc:
|
| 589 |
return json.dumps({"error": f"could not read {path}: {exc}"})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 590 |
fm, body = parse_frontmatter_and_body(text)
|
| 591 |
-
return
|
| 592 |
"slug": path.stem,
|
| 593 |
"entity_type": entity_type,
|
| 594 |
"wikilink": wikilink,
|
| 595 |
"path": str(path),
|
| 596 |
"frontmatter": fm,
|
| 597 |
"body": body,
|
| 598 |
-
})
|
| 599 |
|
| 600 |
# ── Lazy caches ─────────────────────────────────────────────────────
|
| 601 |
|
|
@@ -627,6 +864,13 @@ class CtxCoreToolbox:
|
|
| 627 |
|
| 628 |
def _graph_file_path(self) -> Path | None:
|
| 629 |
if self._graph_path is not None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 630 |
return self._graph_path
|
| 631 |
wiki = self._wiki_dir_resolved()
|
| 632 |
if wiki is not None:
|
|
@@ -665,6 +909,13 @@ def _wiki_entity_path(wiki: Path, slug: str, entity_type: str) -> Path:
|
|
| 665 |
return path
|
| 666 |
|
| 667 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 668 |
def _wiki_entity_link(slug: str, entity_type: str) -> str:
|
| 669 |
link = entity_wikilink(entity_type, slug)
|
| 670 |
if link is None:
|
|
@@ -684,6 +935,15 @@ def _wiki_get_candidates(
|
|
| 684 |
]
|
| 685 |
|
| 686 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 687 |
def _file_signature(path: Path) -> FileSignature | None:
|
| 688 |
try:
|
| 689 |
stat = path.stat()
|
|
@@ -700,9 +960,36 @@ def _graph_file_signature(path: Path) -> GraphSignature:
|
|
| 700 |
return (
|
| 701 |
_file_signature(path),
|
| 702 |
_file_signature(path.with_name("entity-overlays.jsonl")),
|
|
|
|
| 703 |
)
|
| 704 |
|
| 705 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 706 |
def _file_content_fingerprint(path: Path, size: int) -> str:
|
| 707 |
hasher = hashlib.blake2b(digest_size=8)
|
| 708 |
try:
|
|
@@ -718,22 +1005,21 @@ def _file_content_fingerprint(path: Path, size: int) -> str:
|
|
| 718 |
return hasher.hexdigest()
|
| 719 |
|
| 720 |
|
| 721 |
-
def _wiki_pages_signature(wiki: Path) ->
|
| 722 |
entity_root = wiki / "entities"
|
| 723 |
count = 0
|
| 724 |
newest = 0
|
| 725 |
total_size = 0
|
| 726 |
-
if
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
return count, newest, total_size
|
| 737 |
|
| 738 |
|
| 739 |
def _semantic_cache_signature(
|
|
|
|
| 40 |
import hashlib
|
| 41 |
import json
|
| 42 |
import logging
|
| 43 |
+
import time
|
| 44 |
from pathlib import Path
|
| 45 |
+
from typing import Any, Callable, Mapping
|
| 46 |
|
| 47 |
from ctx.adapters.generic.providers import ToolCall, ToolDefinition
|
| 48 |
from ctx.adapters.generic.runtime_lifecycle import RuntimeLifecycleStore
|
| 49 |
from ctx.adapters.generic.tools import TOOL_SEPARATOR
|
| 50 |
from ctx.core.entity_types import (
|
| 51 |
RECOMMENDABLE_ENTITY_TYPES,
|
| 52 |
+
entity_relpath,
|
| 53 |
entity_page_path,
|
| 54 |
entity_wikilink,
|
| 55 |
)
|
| 56 |
+
from ctx.telemetry import hash_identifier, record_event, record_exception, telemetry_span
|
| 57 |
|
| 58 |
|
| 59 |
_logger = logging.getLogger(__name__)
|
|
|
|
| 65 |
# anything else falls back to its normal tool_executor.
|
| 66 |
_NAMESPACE = f"ctx{TOOL_SEPARATOR}"
|
| 67 |
_FILE_SIGNATURE_SAMPLE_BYTES = 64 * 1024
|
| 68 |
+
SUPPORTED_RESPONSE_FORMATS = ("json", "gcf")
|
| 69 |
+
_RESPONSE_FORMAT_PROPERTY = {
|
| 70 |
+
"type": "string",
|
| 71 |
+
"enum": list(SUPPORTED_RESPONSE_FORMATS),
|
| 72 |
+
"description": (
|
| 73 |
+
"Optional response codec for large read-only responses. "
|
| 74 |
+
"Default json preserves the stable ctx contract; gcf requires "
|
| 75 |
+
"the optional claude-ctx[gcf] extra."
|
| 76 |
+
),
|
| 77 |
+
}
|
| 78 |
|
| 79 |
FileSignature = tuple[int, int, str]
|
| 80 |
+
PackSignature = tuple[tuple[str, FileSignature | None], ...]
|
| 81 |
+
GraphSignature = tuple[FileSignature | None, FileSignature | None, PackSignature]
|
| 82 |
+
PageSignature = tuple[int, int, int, PackSignature]
|
| 83 |
|
| 84 |
|
| 85 |
+
def _response_format_from_args(args: Mapping[str, Any]) -> str:
|
| 86 |
+
raw = args.get("_response_format", args.get("output_format", "json"))
|
| 87 |
+
requested = str(raw or "json").strip().lower()
|
| 88 |
+
return requested or "json"
|
| 89 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
def _encode_response(data: Mapping[str, Any], response_format: str) -> str:
|
| 92 |
+
requested = str(response_format or "json").strip().lower()
|
| 93 |
+
if requested == "json":
|
| 94 |
+
return json.dumps(data)
|
| 95 |
+
if requested != "gcf":
|
| 96 |
+
return json.dumps({
|
| 97 |
+
"error": (
|
| 98 |
+
"unsupported response format "
|
| 99 |
+
f"{response_format!r}; expected one of "
|
| 100 |
+
f"{', '.join(SUPPORTED_RESPONSE_FORMATS)}"
|
| 101 |
+
),
|
| 102 |
+
"response_format": "json",
|
| 103 |
+
})
|
| 104 |
+
|
| 105 |
+
try:
|
| 106 |
+
from gcf import encode_generic # type: ignore[import-not-found]
|
| 107 |
+
except Exception:
|
| 108 |
+
return json.dumps({
|
| 109 |
+
"error": (
|
| 110 |
+
"GCF response format requires optional dependency "
|
| 111 |
+
"gcf-python. Install with `pip install "
|
| 112 |
+
"\"claude-ctx[gcf]\"`."
|
| 113 |
+
),
|
| 114 |
+
"response_format": "json",
|
| 115 |
+
})
|
| 116 |
+
|
| 117 |
+
try:
|
| 118 |
+
return str(encode_generic(dict(data)))
|
| 119 |
+
except Exception as exc: # noqa: BLE001
|
| 120 |
+
return json.dumps({
|
| 121 |
+
"error": f"GCF response encoding failed: {exc}",
|
| 122 |
+
"response_format": "json",
|
| 123 |
+
})
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _duration_ms(started: float) -> float:
|
| 127 |
+
return (time.perf_counter() - started) * 1000.0
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _hash_json_value(value: object) -> str:
|
| 131 |
+
encoded = json.dumps(value, sort_keys=True, separators=(",", ":"), default=str)
|
| 132 |
+
return hash_identifier(encoded)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _safe_tool_payload(local_name: str, args: Mapping[str, Any]) -> dict[str, Any]:
|
| 136 |
+
payload: dict[str, Any] = {
|
| 137 |
+
"ctx.operation": local_name,
|
| 138 |
+
"ctx.tool.name": f"{_NAMESPACE}{local_name}",
|
| 139 |
+
"ctx.arguments.keys": sorted(str(key) for key in args),
|
| 140 |
+
}
|
| 141 |
+
for key in ("top_k", "top_n", "max_hops"):
|
| 142 |
+
value = args.get(key)
|
| 143 |
+
if isinstance(value, (int, float)):
|
| 144 |
+
payload[f"ctx.arguments.{key}"] = value
|
| 145 |
+
query = args.get("query")
|
| 146 |
+
if isinstance(query, str):
|
| 147 |
+
payload["ctx.query.hash"] = hash_identifier(query)
|
| 148 |
+
payload["ctx.query.length"] = len(query)
|
| 149 |
+
seeds = args.get("seeds")
|
| 150 |
+
if isinstance(seeds, (list, tuple)):
|
| 151 |
+
payload["ctx.seeds.count"] = len(seeds)
|
| 152 |
+
payload["ctx.seeds.hash"] = _hash_json_value(list(seeds))
|
| 153 |
+
slug = args.get("slug")
|
| 154 |
+
if isinstance(slug, str):
|
| 155 |
+
payload["ctx.slug.hash"] = hash_identifier(slug)
|
| 156 |
+
entity_type = args.get("entity_type")
|
| 157 |
+
if isinstance(entity_type, str):
|
| 158 |
+
payload["ctx.entity.type"] = entity_type
|
| 159 |
+
lifecycle_action = args.get("event_type") or args.get("trigger") or local_name
|
| 160 |
+
if local_name in _LIFECYCLE_LOCAL_NAMES:
|
| 161 |
+
payload["ctx.lifecycle.action"] = str(lifecycle_action)
|
| 162 |
+
return payload
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _result_payload(result_json: str) -> tuple[str, str | None, dict[str, Any]]:
|
| 166 |
+
try:
|
| 167 |
+
parsed = json.loads(result_json)
|
| 168 |
+
except json.JSONDecodeError:
|
| 169 |
+
return "error", "invalid_json", {"ctx.result.has_error_payload": True}
|
| 170 |
+
if not isinstance(parsed, dict):
|
| 171 |
+
return "ok", None, {}
|
| 172 |
+
payload: dict[str, Any] = {"ctx.result.has_error_payload": "error" in parsed}
|
| 173 |
+
results = parsed.get("results")
|
| 174 |
+
if isinstance(results, list):
|
| 175 |
+
payload["ctx.result.count"] = len(results)
|
| 176 |
+
companion_harnesses = parsed.get("companion_harnesses")
|
| 177 |
+
if isinstance(companion_harnesses, list):
|
| 178 |
+
payload["ctx.companion_harness.count"] = len(companion_harnesses)
|
| 179 |
+
if parsed.get("ok") is False or "error" in parsed:
|
| 180 |
+
return "error", "structured_error", payload
|
| 181 |
+
return "ok", None, payload
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _record_core_tool_event(
|
| 185 |
+
event_name: str,
|
| 186 |
+
*,
|
| 187 |
+
payload: dict[str, Any],
|
| 188 |
+
outcome: str,
|
| 189 |
+
duration_ms: float,
|
| 190 |
+
session_id: str | None = None,
|
| 191 |
+
error_kind: str | None = None,
|
| 192 |
+
exc: BaseException | None = None,
|
| 193 |
+
) -> None:
|
| 194 |
+
payload["otel.status_code"] = "ERROR" if outcome == "error" else "OK"
|
| 195 |
+
if error_kind:
|
| 196 |
+
payload["error.type"] = error_kind
|
| 197 |
+
try:
|
| 198 |
+
if exc is not None:
|
| 199 |
+
record_exception(
|
| 200 |
+
event_name,
|
| 201 |
+
source="ctx-core",
|
| 202 |
+
exc=exc,
|
| 203 |
+
transport="ctx-core-toolbox",
|
| 204 |
+
session_id=session_id,
|
| 205 |
+
outcome=outcome,
|
| 206 |
+
duration_ms=duration_ms,
|
| 207 |
+
error_kind=error_kind,
|
| 208 |
+
payload=payload,
|
| 209 |
+
)
|
| 210 |
+
else:
|
| 211 |
+
record_event(
|
| 212 |
+
event_name,
|
| 213 |
+
source="ctx-core",
|
| 214 |
+
transport="ctx-core-toolbox",
|
| 215 |
+
session_id=session_id,
|
| 216 |
+
outcome=outcome,
|
| 217 |
+
duration_ms=duration_ms,
|
| 218 |
+
error_kind=error_kind,
|
| 219 |
+
payload=payload,
|
| 220 |
+
)
|
| 221 |
+
except Exception: # noqa: BLE001 - telemetry must not break tool calls.
|
| 222 |
+
pass
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
_CORE_EVENT_NAMES = {
|
| 226 |
+
"recommend_bundle": "ctx.core.recommend_bundle",
|
| 227 |
+
"graph_query": "ctx.core.graph_query",
|
| 228 |
+
"wiki_search": "ctx.core.wiki_search",
|
| 229 |
+
"wiki_get": "ctx.core.wiki_get",
|
| 230 |
+
}
|
| 231 |
+
_LIFECYCLE_LOCAL_NAMES = frozenset({
|
| 232 |
+
"observe_dev_event",
|
| 233 |
+
"load_entity",
|
| 234 |
+
"mark_entity_used",
|
| 235 |
+
"record_validation",
|
| 236 |
+
"record_escalation",
|
| 237 |
+
"unload_entity",
|
| 238 |
+
"session_end",
|
| 239 |
+
"session_state",
|
| 240 |
+
})
|
| 241 |
|
| 242 |
|
| 243 |
class CtxCoreToolbox:
|
|
|
|
| 268 |
self._graph: Any | None = None # networkx.Graph
|
| 269 |
self._pages: list[Any] | None = None # list[SkillPage]
|
| 270 |
self._graph_signature: GraphSignature | None = None
|
| 271 |
+
self._pages_signature: PageSignature | None = None
|
| 272 |
self._semantic_signature: tuple[FileSignature | None, ...] | None = None
|
| 273 |
|
| 274 |
# ── Public Protocol surface ─────────────────────────────────────────
|
|
|
|
| 320 |
"Default false keeps recommendations latency-safe."
|
| 321 |
),
|
| 322 |
},
|
| 323 |
+
"output_format": dict(_RESPONSE_FORMAT_PROPERTY),
|
| 324 |
+
"_response_format": dict(_RESPONSE_FORMAT_PROPERTY),
|
| 325 |
},
|
| 326 |
"required": ["query"],
|
| 327 |
},
|
|
|
|
| 360 |
"minimum": 1,
|
| 361 |
"maximum": 50,
|
| 362 |
},
|
| 363 |
+
"output_format": dict(_RESPONSE_FORMAT_PROPERTY),
|
| 364 |
+
"_response_format": dict(_RESPONSE_FORMAT_PROPERTY),
|
| 365 |
},
|
| 366 |
"required": ["seeds"],
|
| 367 |
},
|
|
|
|
| 384 |
"minimum": 1,
|
| 385 |
"maximum": 100,
|
| 386 |
},
|
| 387 |
+
"output_format": dict(_RESPONSE_FORMAT_PROPERTY),
|
| 388 |
+
"_response_format": dict(_RESPONSE_FORMAT_PROPERTY),
|
| 389 |
},
|
| 390 |
"required": ["query"],
|
| 391 |
},
|
|
|
|
| 410 |
"Use it to disambiguate duplicate slugs."
|
| 411 |
),
|
| 412 |
},
|
| 413 |
+
"output_format": dict(_RESPONSE_FORMAT_PROPERTY),
|
| 414 |
+
"_response_format": dict(_RESPONSE_FORMAT_PROPERTY),
|
| 415 |
},
|
| 416 |
"required": ["slug"],
|
| 417 |
},
|
|
|
|
| 434 |
)
|
| 435 |
local_name = call.name[len(_NAMESPACE):]
|
| 436 |
args = call.arguments or {}
|
| 437 |
+
started = time.perf_counter()
|
| 438 |
+
event_name = _CORE_EVENT_NAMES.get(
|
| 439 |
+
local_name,
|
| 440 |
+
"ctx.core.lifecycle" if local_name in _LIFECYCLE_LOCAL_NAMES else "ctx.core.tool_call",
|
| 441 |
+
)
|
| 442 |
+
event_payload = _safe_tool_payload(local_name, args)
|
| 443 |
+
session_id = str(args.get("session_id") or "").strip() or self._bound_session_id
|
| 444 |
+
|
| 445 |
+
with telemetry_span():
|
| 446 |
+
try:
|
| 447 |
+
if local_name == "recommend_bundle":
|
| 448 |
+
result = self._dispatch_recommend(args)
|
| 449 |
+
elif local_name == "graph_query":
|
| 450 |
+
result = self._dispatch_graph_query(args)
|
| 451 |
+
elif local_name == "wiki_search":
|
| 452 |
+
result = self._dispatch_wiki_search(args)
|
| 453 |
+
elif local_name == "wiki_get":
|
| 454 |
+
result = self._dispatch_wiki_get(args)
|
| 455 |
+
elif local_name == "observe_dev_event":
|
| 456 |
+
result = self._dispatch_lifecycle(args, "observe_dev_event")
|
| 457 |
+
elif local_name == "load_entity":
|
| 458 |
+
result = self._dispatch_lifecycle(args, "load_entity")
|
| 459 |
+
elif local_name == "mark_entity_used":
|
| 460 |
+
result = self._dispatch_lifecycle(args, "mark_entity_used")
|
| 461 |
+
elif local_name == "record_validation":
|
| 462 |
+
result = self._dispatch_lifecycle(args, "record_validation")
|
| 463 |
+
elif local_name == "record_escalation":
|
| 464 |
+
result = self._dispatch_lifecycle(args, "record_escalation")
|
| 465 |
+
elif local_name == "unload_entity":
|
| 466 |
+
result = self._dispatch_lifecycle(args, "unload_entity")
|
| 467 |
+
elif local_name == "session_end":
|
| 468 |
+
result = self._dispatch_lifecycle(args, "session_end")
|
| 469 |
+
elif local_name == "session_state":
|
| 470 |
+
result = self._dispatch_lifecycle(args, "session_state")
|
| 471 |
+
else:
|
| 472 |
+
raise ValueError(f"unknown ctx-core tool {local_name!r}")
|
| 473 |
+
except Exception as exc: # noqa: BLE001 - preserve existing propagation.
|
| 474 |
+
_record_core_tool_event(
|
| 475 |
+
event_name,
|
| 476 |
+
payload=event_payload,
|
| 477 |
+
outcome="error",
|
| 478 |
+
duration_ms=_duration_ms(started),
|
| 479 |
+
session_id=session_id,
|
| 480 |
+
error_kind=type(exc).__name__,
|
| 481 |
+
exc=exc,
|
| 482 |
+
)
|
| 483 |
+
raise
|
| 484 |
+
|
| 485 |
+
outcome, error_kind, result_payload = _result_payload(result)
|
| 486 |
+
event_payload.update(result_payload)
|
| 487 |
+
_record_core_tool_event(
|
| 488 |
+
event_name,
|
| 489 |
+
payload=event_payload,
|
| 490 |
+
outcome=outcome,
|
| 491 |
+
duration_ms=_duration_ms(started),
|
| 492 |
+
session_id=session_id,
|
| 493 |
+
error_kind=error_kind,
|
| 494 |
+
)
|
| 495 |
+
return result
|
| 496 |
|
| 497 |
def owns(self, tool_name: str) -> bool:
|
| 498 |
"""True when this toolbox is the dispatcher for the given name."""
|
|
|
|
| 578 |
if model_provider or model
|
| 579 |
else []
|
| 580 |
)
|
| 581 |
+
return _encode_response({
|
| 582 |
"query": query,
|
| 583 |
"tags": tags,
|
| 584 |
"results": results,
|
| 585 |
"companion_harnesses": companion_harnesses,
|
| 586 |
+
}, _response_format_from_args(args))
|
| 587 |
|
| 588 |
def _dispatch_graph_query(self, args: dict[str, Any]) -> str:
|
| 589 |
seeds_raw = args.get("seeds") or []
|
|
|
|
| 616 |
}
|
| 617 |
for r in raw
|
| 618 |
]
|
| 619 |
+
return _encode_response(
|
| 620 |
+
{"seeds": seeds, "results": results},
|
| 621 |
+
_response_format_from_args(args),
|
| 622 |
+
)
|
| 623 |
|
| 624 |
def _dispatch_wiki_search(self, args: dict[str, Any]) -> str:
|
| 625 |
query = str(args.get("query", "")).strip()
|
|
|
|
| 651 |
}
|
| 652 |
for p in hits
|
| 653 |
]
|
| 654 |
+
return _encode_response(
|
| 655 |
+
{"query": query, "results": results},
|
| 656 |
+
_response_format_from_args(args),
|
| 657 |
+
)
|
| 658 |
|
| 659 |
def _dispatch_wiki_get(self, args: dict[str, Any]) -> str:
|
| 660 |
slug = str(args.get("slug", "")).strip()
|
|
|
|
| 682 |
return json.dumps({"error": "wiki_dir not configured"})
|
| 683 |
|
| 684 |
candidates = _wiki_get_candidates(wiki, slug, entity_type or None)
|
| 685 |
+
try:
|
| 686 |
+
pack_pages = _wiki_pack_pages(wiki)
|
| 687 |
+
except Exception as exc: # noqa: BLE001 - surface corrupt pack state to callers.
|
| 688 |
+
return json.dumps({"error": f"could not read wiki-packs: {exc}"})
|
| 689 |
|
| 690 |
for candidate_type, path, wikilink in candidates:
|
| 691 |
+
if pack_pages is not None:
|
| 692 |
+
relpath = _wiki_entity_relpath(candidate_type, slug)
|
| 693 |
+
text = pack_pages.get(relpath)
|
| 694 |
+
if text is not None:
|
| 695 |
+
return self._serialise_page_text(
|
| 696 |
+
path,
|
| 697 |
+
text,
|
| 698 |
+
candidate_type,
|
| 699 |
+
wikilink,
|
| 700 |
+
_response_format_from_args(args),
|
| 701 |
+
)
|
| 702 |
+
continue
|
| 703 |
if path.is_file():
|
| 704 |
+
return self._serialise_page(
|
| 705 |
+
path,
|
| 706 |
+
candidate_type,
|
| 707 |
+
wikilink,
|
| 708 |
+
_response_format_from_args(args),
|
| 709 |
+
)
|
| 710 |
|
| 711 |
return json.dumps({
|
| 712 |
"error": f"no entity page found for slug {slug!r}",
|
|
|
|
| 801 |
raise ValueError("session_id is required")
|
| 802 |
return supplied
|
| 803 |
|
| 804 |
+
def _serialise_page(
|
| 805 |
+
self,
|
| 806 |
+
path: Path,
|
| 807 |
+
entity_type: str,
|
| 808 |
+
wikilink: str,
|
| 809 |
+
response_format: str,
|
| 810 |
+
) -> str:
|
| 811 |
try:
|
| 812 |
text = path.read_text(encoding="utf-8", errors="replace")
|
| 813 |
except OSError as exc:
|
| 814 |
return json.dumps({"error": f"could not read {path}: {exc}"})
|
| 815 |
+
return self._serialise_page_text(path, text, entity_type, wikilink, response_format)
|
| 816 |
+
|
| 817 |
+
def _serialise_page_text(
|
| 818 |
+
self,
|
| 819 |
+
path: Path,
|
| 820 |
+
text: str,
|
| 821 |
+
entity_type: str,
|
| 822 |
+
wikilink: str,
|
| 823 |
+
response_format: str,
|
| 824 |
+
) -> str:
|
| 825 |
+
from ctx.core.wiki.wiki_utils import parse_frontmatter_and_body # noqa: PLC0415
|
| 826 |
+
|
| 827 |
fm, body = parse_frontmatter_and_body(text)
|
| 828 |
+
return _encode_response({
|
| 829 |
"slug": path.stem,
|
| 830 |
"entity_type": entity_type,
|
| 831 |
"wikilink": wikilink,
|
| 832 |
"path": str(path),
|
| 833 |
"frontmatter": fm,
|
| 834 |
"body": body,
|
| 835 |
+
}, response_format)
|
| 836 |
|
| 837 |
# ── Lazy caches ─────────────────────────────────────────────────────
|
| 838 |
|
|
|
|
| 864 |
|
| 865 |
def _graph_file_path(self) -> Path | None:
|
| 866 |
if self._graph_path is not None:
|
| 867 |
+
if _graph_source_available(self._graph_path):
|
| 868 |
+
return self._graph_path
|
| 869 |
+
wiki = self._wiki_dir_resolved()
|
| 870 |
+
if wiki is not None:
|
| 871 |
+
wiki_graph_path = wiki / "graphify-out" / "graph.json"
|
| 872 |
+
if _graph_source_available(wiki_graph_path):
|
| 873 |
+
return wiki_graph_path
|
| 874 |
return self._graph_path
|
| 875 |
wiki = self._wiki_dir_resolved()
|
| 876 |
if wiki is not None:
|
|
|
|
| 909 |
return path
|
| 910 |
|
| 911 |
|
| 912 |
+
def _wiki_entity_relpath(entity_type: str, slug: str) -> str:
|
| 913 |
+
relpath = entity_relpath(entity_type, slug)
|
| 914 |
+
if relpath is None:
|
| 915 |
+
raise ValueError(f"unknown entity type {entity_type!r}")
|
| 916 |
+
return relpath.as_posix()
|
| 917 |
+
|
| 918 |
+
|
| 919 |
def _wiki_entity_link(slug: str, entity_type: str) -> str:
|
| 920 |
link = entity_wikilink(entity_type, slug)
|
| 921 |
if link is None:
|
|
|
|
| 935 |
]
|
| 936 |
|
| 937 |
|
| 938 |
+
def _wiki_pack_pages(wiki: Path) -> dict[str, str] | None:
|
| 939 |
+
packs_dir = wiki / "wiki-packs"
|
| 940 |
+
if not packs_dir.is_dir():
|
| 941 |
+
return None
|
| 942 |
+
from ctx.core.wiki.wiki_packs import load_merged_wiki_pages # noqa: PLC0415
|
| 943 |
+
|
| 944 |
+
return load_merged_wiki_pages(packs_dir)
|
| 945 |
+
|
| 946 |
+
|
| 947 |
def _file_signature(path: Path) -> FileSignature | None:
|
| 948 |
try:
|
| 949 |
stat = path.stat()
|
|
|
|
| 960 |
return (
|
| 961 |
_file_signature(path),
|
| 962 |
_file_signature(path.with_name("entity-overlays.jsonl")),
|
| 963 |
+
_graph_pack_signature(path),
|
| 964 |
)
|
| 965 |
|
| 966 |
|
| 967 |
+
def _graph_source_available(path: Path) -> bool:
|
| 968 |
+
return path.is_file() or (path.parent / "packs").is_dir()
|
| 969 |
+
|
| 970 |
+
|
| 971 |
+
def _graph_pack_signature(graph_path: Path) -> PackSignature:
|
| 972 |
+
return _pack_dir_signature(graph_path.parent / "packs")
|
| 973 |
+
|
| 974 |
+
|
| 975 |
+
def _pack_dir_signature(packs_dir: Path) -> PackSignature:
|
| 976 |
+
if not packs_dir.is_dir():
|
| 977 |
+
return ()
|
| 978 |
+
|
| 979 |
+
rows: list[tuple[str, FileSignature | None]] = []
|
| 980 |
+
try:
|
| 981 |
+
paths = sorted(path for path in packs_dir.rglob("*") if path.is_file())
|
| 982 |
+
except OSError:
|
| 983 |
+
return (("<unreadable>", None),)
|
| 984 |
+
for path in paths:
|
| 985 |
+
try:
|
| 986 |
+
relpath = path.relative_to(packs_dir).as_posix()
|
| 987 |
+
except ValueError:
|
| 988 |
+
relpath = path.name
|
| 989 |
+
rows.append((relpath, _file_signature(path)))
|
| 990 |
+
return tuple(rows)
|
| 991 |
+
|
| 992 |
+
|
| 993 |
def _file_content_fingerprint(path: Path, size: int) -> str:
|
| 994 |
hasher = hashlib.blake2b(digest_size=8)
|
| 995 |
try:
|
|
|
|
| 1005 |
return hasher.hexdigest()
|
| 1006 |
|
| 1007 |
|
| 1008 |
+
def _wiki_pages_signature(wiki: Path) -> PageSignature:
|
| 1009 |
entity_root = wiki / "entities"
|
| 1010 |
count = 0
|
| 1011 |
newest = 0
|
| 1012 |
total_size = 0
|
| 1013 |
+
if entity_root.is_dir():
|
| 1014 |
+
for path in entity_root.rglob("*.md"):
|
| 1015 |
+
try:
|
| 1016 |
+
stat = path.stat()
|
| 1017 |
+
except OSError:
|
| 1018 |
+
continue
|
| 1019 |
+
count += 1
|
| 1020 |
+
newest = max(newest, stat.st_mtime_ns)
|
| 1021 |
+
total_size += stat.st_size
|
| 1022 |
+
return count, newest, total_size, _pack_dir_signature(wiki / "wiki-packs")
|
|
|
|
| 1023 |
|
| 1024 |
|
| 1025 |
def _semantic_cache_signature(
|
src/ctx/adapters/generic/runtime_lifecycle.py
CHANGED
|
@@ -12,6 +12,14 @@ from typing import Any
|
|
| 12 |
|
| 13 |
from ctx.core.entity_types import RECOMMENDABLE_ENTITY_TYPES
|
| 14 |
from ctx.core.wiki.wiki_utils import validate_skill_name
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
from ctx.utils._fs_utils import reject_symlink_path
|
| 16 |
|
| 17 |
|
|
@@ -266,12 +274,20 @@ class RuntimeLifecycleStore:
|
|
| 266 |
event["session_id"] = session_id
|
| 267 |
event["created_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
| 268 |
event["created_at_epoch"] = time.time()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
path = self.events_path
|
| 270 |
reject_symlink_path(path)
|
| 271 |
-
|
| 272 |
with path.open("a", encoding="utf-8") as fh:
|
| 273 |
fh.write(json.dumps(event, sort_keys=True) + "\n")
|
| 274 |
-
|
|
|
|
| 275 |
|
| 276 |
def _events_for_session(self, session_id: str) -> list[dict[str, Any]]:
|
| 277 |
path = self.events_path
|
|
@@ -298,6 +314,17 @@ class RuntimeLifecycleStore:
|
|
| 298 |
return root / "events.jsonl"
|
| 299 |
|
| 300 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
def _validate_session_id(raw: str) -> str:
|
| 302 |
value = raw.strip()
|
| 303 |
if not value or not _SESSION_RE.match(value):
|
|
@@ -305,6 +332,38 @@ def _validate_session_id(raw: str) -> str:
|
|
| 305 |
return value
|
| 306 |
|
| 307 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
def _validate_entity_type(raw: str) -> str:
|
| 309 |
value = raw.strip()
|
| 310 |
if value not in _ENTITY_TYPES:
|
|
|
|
| 12 |
|
| 13 |
from ctx.core.entity_types import RECOMMENDABLE_ENTITY_TYPES
|
| 14 |
from ctx.core.wiki.wiki_utils import validate_skill_name
|
| 15 |
+
from ctx.telemetry import (
|
| 16 |
+
ensure_private_event_file,
|
| 17 |
+
hash_identifier,
|
| 18 |
+
record_event,
|
| 19 |
+
sanitize_payload,
|
| 20 |
+
telemetry_span,
|
| 21 |
+
telemetry_enabled,
|
| 22 |
+
)
|
| 23 |
from ctx.utils._fs_utils import reject_symlink_path
|
| 24 |
|
| 25 |
|
|
|
|
| 274 |
event["session_id"] = session_id
|
| 275 |
event["created_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
| 276 |
event["created_at_epoch"] = time.time()
|
| 277 |
+
if not telemetry_enabled():
|
| 278 |
+
return {
|
| 279 |
+
"ok": True,
|
| 280 |
+
"events_path": str(self.events_path),
|
| 281 |
+
"recorded": False,
|
| 282 |
+
}
|
| 283 |
+
event = _sanitize_lifecycle_event(event)
|
| 284 |
path = self.events_path
|
| 285 |
reject_symlink_path(path)
|
| 286 |
+
ensure_private_event_file(path)
|
| 287 |
with path.open("a", encoding="utf-8") as fh:
|
| 288 |
fh.write(json.dumps(event, sort_keys=True) + "\n")
|
| 289 |
+
_record_runtime_lifecycle_telemetry(event)
|
| 290 |
+
return {"ok": True, "event": event, "events_path": str(path), "recorded": True}
|
| 291 |
|
| 292 |
def _events_for_session(self, session_id: str) -> list[dict[str, Any]]:
|
| 293 |
path = self.events_path
|
|
|
|
| 314 |
return root / "events.jsonl"
|
| 315 |
|
| 316 |
|
| 317 |
+
def _sanitize_lifecycle_event(event: dict[str, Any]) -> dict[str, Any]:
|
| 318 |
+
redacted = dict(event)
|
| 319 |
+
payload = redacted.get("payload")
|
| 320 |
+
if isinstance(payload, dict):
|
| 321 |
+
redacted["payload"] = sanitize_payload(payload)
|
| 322 |
+
cwd = redacted.pop("cwd", None)
|
| 323 |
+
if isinstance(cwd, str) and cwd:
|
| 324 |
+
redacted["cwd_hash"] = hash_identifier(cwd)
|
| 325 |
+
return redacted
|
| 326 |
+
|
| 327 |
+
|
| 328 |
def _validate_session_id(raw: str) -> str:
|
| 329 |
value = raw.strip()
|
| 330 |
if not value or not _SESSION_RE.match(value):
|
|
|
|
| 332 |
return value
|
| 333 |
|
| 334 |
|
| 335 |
+
def _record_runtime_lifecycle_telemetry(event: dict[str, Any]) -> None:
|
| 336 |
+
payload: dict[str, Any] = {
|
| 337 |
+
"ctx.lifecycle.action": str(event.get("action") or ""),
|
| 338 |
+
"ctx.payload.present": bool(event.get("payload")),
|
| 339 |
+
"otel.status_code": "OK",
|
| 340 |
+
}
|
| 341 |
+
entity_type = event.get("entity_type")
|
| 342 |
+
if isinstance(entity_type, str) and entity_type:
|
| 343 |
+
payload["ctx.entity.type"] = entity_type
|
| 344 |
+
slug = event.get("slug")
|
| 345 |
+
if isinstance(slug, str) and slug:
|
| 346 |
+
payload["ctx.slug.hash"] = hash_identifier(slug)
|
| 347 |
+
status = event.get("status")
|
| 348 |
+
if isinstance(status, str) and status:
|
| 349 |
+
payload["ctx.status"] = status
|
| 350 |
+
security_scan = event.get("security_scan")
|
| 351 |
+
if isinstance(security_scan, dict):
|
| 352 |
+
payload["ctx.security_scan.status"] = str(security_scan.get("status") or "")
|
| 353 |
+
try:
|
| 354 |
+
with telemetry_span():
|
| 355 |
+
record_event(
|
| 356 |
+
"ctx.runtime_lifecycle.record",
|
| 357 |
+
source="ctx-runtime-lifecycle",
|
| 358 |
+
transport="local-jsonl",
|
| 359 |
+
session_id=str(event.get("session_id") or "") or None,
|
| 360 |
+
outcome="ok",
|
| 361 |
+
payload=payload,
|
| 362 |
+
)
|
| 363 |
+
except Exception: # noqa: BLE001 - lifecycle writes must not depend on telemetry.
|
| 364 |
+
pass
|
| 365 |
+
|
| 366 |
+
|
| 367 |
def _validate_entity_type(raw: str) -> str:
|
| 368 |
value = raw.strip()
|
| 369 |
if value not in _ENTITY_TYPES:
|
src/ctx/api.py
CHANGED
|
@@ -50,15 +50,14 @@ Plan 001 Phase H9.
|
|
| 50 |
from __future__ import annotations
|
| 51 |
|
| 52 |
import json
|
|
|
|
| 53 |
from pathlib import Path
|
| 54 |
from typing import Any
|
| 55 |
|
| 56 |
from ctx.adapters.generic.ctx_core_tools import CtxCoreToolbox
|
| 57 |
from ctx.adapters.generic.providers import ToolCall
|
| 58 |
-
from ctx.core.entity_types import
|
| 59 |
-
|
| 60 |
-
SUBJECT_TYPE_FOR_ENTITY_TYPE,
|
| 61 |
-
)
|
| 62 |
|
| 63 |
|
| 64 |
__all__ = [
|
|
@@ -75,6 +74,12 @@ __all__ = [
|
|
| 75 |
# Module-level singleton toolbox — lazy, shared across calls. Saves
|
| 76 |
# loading the 13k-node graph on every function call.
|
| 77 |
_default_toolbox: CtxCoreToolbox | None = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
|
| 80 |
def _get_toolbox() -> CtxCoreToolbox:
|
|
@@ -84,13 +89,124 @@ def _get_toolbox() -> CtxCoreToolbox:
|
|
| 84 |
return _default_toolbox
|
| 85 |
|
| 86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
def _call(tool_name: str, arguments: dict[str, Any]) -> dict[str, Any]:
|
| 88 |
"""Invoke one CtxCoreToolbox tool, return the parsed JSON result."""
|
|
|
|
|
|
|
|
|
|
| 89 |
toolbox = _get_toolbox()
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
|
| 96 |
# ── Public API ─────────────────────────────────────────────────────────────
|
|
@@ -191,26 +307,53 @@ def list_all_entities(
|
|
| 191 |
``'skill'``, ``'agent'``, ``'mcp-server'``, ``'harness'``. Pass
|
| 192 |
None (default) to get every entity across all recommendable types.
|
| 193 |
"""
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
|
|
|
| 211 |
else:
|
| 212 |
-
|
| 213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
|
| 215 |
|
| 216 |
def default_wiki_dir() -> Path | None:
|
|
|
|
| 50 |
from __future__ import annotations
|
| 51 |
|
| 52 |
import json
|
| 53 |
+
import time
|
| 54 |
from pathlib import Path
|
| 55 |
from typing import Any
|
| 56 |
|
| 57 |
from ctx.adapters.generic.ctx_core_tools import CtxCoreToolbox
|
| 58 |
from ctx.adapters.generic.providers import ToolCall
|
| 59 |
+
from ctx.core.entity_types import RECOMMENDABLE_ENTITY_TYPES
|
| 60 |
+
from ctx.telemetry import hash_identifier, record_event, record_exception, telemetry_span
|
|
|
|
|
|
|
| 61 |
|
| 62 |
|
| 63 |
__all__ = [
|
|
|
|
| 74 |
# Module-level singleton toolbox — lazy, shared across calls. Saves
|
| 75 |
# loading the 13k-node graph on every function call.
|
| 76 |
_default_toolbox: CtxCoreToolbox | None = None
|
| 77 |
+
_TOOL_EVENT_NAMES = {
|
| 78 |
+
"ctx__recommend_bundle": "ctx.api.recommend_bundle",
|
| 79 |
+
"ctx__graph_query": "ctx.api.graph_query",
|
| 80 |
+
"ctx__wiki_search": "ctx.api.wiki_search",
|
| 81 |
+
"ctx__wiki_get": "ctx.api.wiki_get",
|
| 82 |
+
}
|
| 83 |
|
| 84 |
|
| 85 |
def _get_toolbox() -> CtxCoreToolbox:
|
|
|
|
| 89 |
return _default_toolbox
|
| 90 |
|
| 91 |
|
| 92 |
+
def _duration_ms(started: float) -> float:
|
| 93 |
+
return (time.perf_counter() - started) * 1000.0
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _hash_json_value(value: object) -> str:
|
| 97 |
+
encoded = json.dumps(value, sort_keys=True, separators=(",", ":"), default=str)
|
| 98 |
+
return hash_identifier(encoded)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _safe_argument_payload(tool_name: str, arguments: dict[str, Any]) -> dict[str, Any]:
|
| 102 |
+
payload: dict[str, Any] = {
|
| 103 |
+
"ctx.operation": tool_name.removeprefix("ctx__"),
|
| 104 |
+
"ctx.tool.name": tool_name,
|
| 105 |
+
"ctx.arguments.keys": sorted(arguments),
|
| 106 |
+
}
|
| 107 |
+
for key in ("top_k", "top_n", "max_hops"):
|
| 108 |
+
value = arguments.get(key)
|
| 109 |
+
if isinstance(value, (int, float)):
|
| 110 |
+
payload[f"ctx.arguments.{key}"] = value
|
| 111 |
+
query = arguments.get("query")
|
| 112 |
+
if isinstance(query, str):
|
| 113 |
+
payload["ctx.query.hash"] = hash_identifier(query)
|
| 114 |
+
payload["ctx.query.length"] = len(query)
|
| 115 |
+
seeds = arguments.get("seeds")
|
| 116 |
+
if isinstance(seeds, (list, tuple)):
|
| 117 |
+
payload["ctx.seeds.count"] = len(seeds)
|
| 118 |
+
payload["ctx.seeds.hash"] = _hash_json_value(list(seeds))
|
| 119 |
+
slug = arguments.get("slug")
|
| 120 |
+
if isinstance(slug, str):
|
| 121 |
+
payload["ctx.slug.hash"] = hash_identifier(slug)
|
| 122 |
+
entity_type = arguments.get("entity_type")
|
| 123 |
+
if isinstance(entity_type, str):
|
| 124 |
+
payload["ctx.entity.type"] = entity_type
|
| 125 |
+
return payload
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _result_payload(result: dict[str, Any]) -> dict[str, Any]:
|
| 129 |
+
payload: dict[str, Any] = {"ctx.result.has_error_payload": "error" in result}
|
| 130 |
+
results = result.get("results")
|
| 131 |
+
if isinstance(results, list):
|
| 132 |
+
payload["ctx.result.count"] = len(results)
|
| 133 |
+
elif "error" not in result and result:
|
| 134 |
+
payload["ctx.result.count"] = 1
|
| 135 |
+
return payload
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _record_api_event(
|
| 139 |
+
event_name: str,
|
| 140 |
+
*,
|
| 141 |
+
payload: dict[str, Any],
|
| 142 |
+
outcome: str,
|
| 143 |
+
duration_ms: float,
|
| 144 |
+
error_kind: str | None = None,
|
| 145 |
+
exc: BaseException | None = None,
|
| 146 |
+
) -> None:
|
| 147 |
+
payload["otel.status_code"] = "ERROR" if outcome == "error" else "OK"
|
| 148 |
+
if error_kind:
|
| 149 |
+
payload["error.type"] = error_kind
|
| 150 |
+
try:
|
| 151 |
+
if exc is not None:
|
| 152 |
+
record_exception(
|
| 153 |
+
event_name,
|
| 154 |
+
source="ctx-api",
|
| 155 |
+
exc=exc,
|
| 156 |
+
transport="python-api",
|
| 157 |
+
outcome=outcome,
|
| 158 |
+
duration_ms=duration_ms,
|
| 159 |
+
error_kind=error_kind,
|
| 160 |
+
payload=payload,
|
| 161 |
+
)
|
| 162 |
+
else:
|
| 163 |
+
record_event(
|
| 164 |
+
event_name,
|
| 165 |
+
source="ctx-api",
|
| 166 |
+
transport="python-api",
|
| 167 |
+
outcome=outcome,
|
| 168 |
+
duration_ms=duration_ms,
|
| 169 |
+
error_kind=error_kind,
|
| 170 |
+
payload=payload,
|
| 171 |
+
)
|
| 172 |
+
except Exception: # noqa: BLE001 - telemetry must never break the API.
|
| 173 |
+
pass
|
| 174 |
+
|
| 175 |
+
|
| 176 |
def _call(tool_name: str, arguments: dict[str, Any]) -> dict[str, Any]:
|
| 177 |
"""Invoke one CtxCoreToolbox tool, return the parsed JSON result."""
|
| 178 |
+
started = time.perf_counter()
|
| 179 |
+
event_name = _TOOL_EVENT_NAMES.get(tool_name, "ctx.api.tool_call")
|
| 180 |
+
event_payload = _safe_argument_payload(tool_name, arguments)
|
| 181 |
toolbox = _get_toolbox()
|
| 182 |
+
with telemetry_span():
|
| 183 |
+
try:
|
| 184 |
+
raw = toolbox.dispatch(
|
| 185 |
+
ToolCall(id="api", name=tool_name, arguments=arguments)
|
| 186 |
+
)
|
| 187 |
+
payload = json.loads(raw)
|
| 188 |
+
except Exception as exc: # noqa: BLE001 - preserve existing propagation.
|
| 189 |
+
_record_api_event(
|
| 190 |
+
event_name,
|
| 191 |
+
payload=event_payload,
|
| 192 |
+
outcome="error",
|
| 193 |
+
duration_ms=_duration_ms(started),
|
| 194 |
+
error_kind=type(exc).__name__,
|
| 195 |
+
exc=exc,
|
| 196 |
+
)
|
| 197 |
+
raise
|
| 198 |
+
|
| 199 |
+
outcome = "error" if isinstance(payload, dict) and "error" in payload else "ok"
|
| 200 |
+
if isinstance(payload, dict):
|
| 201 |
+
event_payload.update(_result_payload(payload))
|
| 202 |
+
_record_api_event(
|
| 203 |
+
event_name,
|
| 204 |
+
payload=event_payload,
|
| 205 |
+
outcome=outcome,
|
| 206 |
+
duration_ms=_duration_ms(started),
|
| 207 |
+
error_kind="structured_error" if outcome == "error" else None,
|
| 208 |
+
)
|
| 209 |
+
return payload
|
| 210 |
|
| 211 |
|
| 212 |
# ── Public API ─────────────────────────────────────────────────────────────
|
|
|
|
| 307 |
``'skill'``, ``'agent'``, ``'mcp-server'``, ``'harness'``. Pass
|
| 308 |
None (default) to get every entity across all recommendable types.
|
| 309 |
"""
|
| 310 |
+
started = time.perf_counter()
|
| 311 |
+
event_payload: dict[str, Any] = {
|
| 312 |
+
"ctx.operation": "list_all_entities",
|
| 313 |
+
"ctx.arguments.keys": ["entity_type"] if entity_type is not None else [],
|
| 314 |
+
}
|
| 315 |
+
if entity_type is not None:
|
| 316 |
+
event_payload["ctx.entity.type"] = entity_type
|
| 317 |
+
try:
|
| 318 |
+
wiki = default_wiki_dir()
|
| 319 |
+
event_payload["ctx.wiki.available"] = bool(wiki is not None and wiki.is_dir())
|
| 320 |
+
if wiki is None or not wiki.is_dir():
|
| 321 |
+
result: list[str] = []
|
| 322 |
+
outcome = "error"
|
| 323 |
+
error_kind = "wiki_unavailable"
|
| 324 |
+
elif entity_type is not None and entity_type not in RECOMMENDABLE_ENTITY_TYPES:
|
| 325 |
+
result = []
|
| 326 |
+
outcome = "error"
|
| 327 |
+
error_kind = "invalid_entity_type"
|
| 328 |
else:
|
| 329 |
+
from ctx.core.wiki.wiki_query import load_all_pages # noqa: PLC0415
|
| 330 |
+
|
| 331 |
+
result = sorted({
|
| 332 |
+
page.name
|
| 333 |
+
for page in load_all_pages(wiki)
|
| 334 |
+
if entity_type is None or page.entity_type == entity_type
|
| 335 |
+
})
|
| 336 |
+
outcome = "ok"
|
| 337 |
+
error_kind = None
|
| 338 |
+
except Exception as exc: # noqa: BLE001 - preserve existing propagation.
|
| 339 |
+
_record_api_event(
|
| 340 |
+
"ctx.api.list_all_entities",
|
| 341 |
+
payload=event_payload,
|
| 342 |
+
outcome="error",
|
| 343 |
+
duration_ms=_duration_ms(started),
|
| 344 |
+
error_kind=type(exc).__name__,
|
| 345 |
+
)
|
| 346 |
+
raise
|
| 347 |
+
|
| 348 |
+
event_payload["ctx.result.count"] = len(result)
|
| 349 |
+
_record_api_event(
|
| 350 |
+
"ctx.api.list_all_entities",
|
| 351 |
+
payload=event_payload,
|
| 352 |
+
outcome=outcome,
|
| 353 |
+
duration_ms=_duration_ms(started),
|
| 354 |
+
error_kind=error_kind,
|
| 355 |
+
)
|
| 356 |
+
return result
|
| 357 |
|
| 358 |
|
| 359 |
def default_wiki_dir() -> Path | None:
|
src/ctx/assets/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Packaged dashboard assets."""
|
src/ctx/assets/monitor-docs.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const docsSearch = document.getElementById('docs-search');
|
| 2 |
+
const docsSearchResults = document.getElementById('docs-search-results');
|
| 3 |
+
const docButtons = Array.from(document.querySelectorAll('.docs-tab-button'));
|
| 4 |
+
const docPanels = Array.from(document.querySelectorAll('.docs-tab-panel'));
|
| 5 |
+
const docLinks = Array.from(document.querySelectorAll('[data-doc-link]'));
|
| 6 |
+
function activeDocPanel() { return docPanels.find(panel => !panel.hidden); }
|
| 7 |
+
function jumpToDocTarget(tab, target) {
|
| 8 |
+
activateDocTab(tab);
|
| 9 |
+
if (target) history.replaceState(null, '', '#' + target);
|
| 10 |
+
window.requestAnimationFrame(() => {
|
| 11 |
+
const node = document.getElementById(target);
|
| 12 |
+
if (node) {
|
| 13 |
+
node.scrollIntoView({ block: 'start' });
|
| 14 |
+
}
|
| 15 |
+
});
|
| 16 |
+
}
|
| 17 |
+
function activateDocTab(key) {
|
| 18 |
+
docButtons.forEach(button => button.classList.toggle('active', button.dataset.docTab === key));
|
| 19 |
+
docPanels.forEach(panel => { panel.hidden = panel.dataset.docPanel !== key; });
|
| 20 |
+
applyDocsFilter();
|
| 21 |
+
}
|
| 22 |
+
function renderDocsSearchResults(q) {
|
| 23 |
+
if (!docsSearchResults) return;
|
| 24 |
+
docsSearchResults.replaceChildren();
|
| 25 |
+
docsSearchResults.hidden = !q;
|
| 26 |
+
if (!q) return;
|
| 27 |
+
function docSearchScore(link) {
|
| 28 |
+
const label = (link.dataset.docLabel || link.textContent || '').toLowerCase();
|
| 29 |
+
let score = 0;
|
| 30 |
+
if (label === q) score += 200;
|
| 31 |
+
if (label.includes(q)) score += 100;
|
| 32 |
+
if (link.classList.contains('docs-heading-link')) score += 25;
|
| 33 |
+
if ((link.dataset.docSearch || '').includes(q)) score += 1;
|
| 34 |
+
return score;
|
| 35 |
+
}
|
| 36 |
+
const matches = docLinks.filter(link => (link.dataset.docSearch || '').includes(q))
|
| 37 |
+
.sort((a, b) => docSearchScore(b) - docSearchScore(a))
|
| 38 |
+
.slice(0, 12);
|
| 39 |
+
if (!matches.length) {
|
| 40 |
+
const empty = document.createElement('div');
|
| 41 |
+
empty.className = 'docs-search-empty';
|
| 42 |
+
empty.textContent = 'No local docs matches.';
|
| 43 |
+
docsSearchResults.appendChild(empty);
|
| 44 |
+
return;
|
| 45 |
+
}
|
| 46 |
+
matches.forEach(link => {
|
| 47 |
+
const button = document.createElement('button');
|
| 48 |
+
button.type = 'button';
|
| 49 |
+
button.className = 'docs-search-result';
|
| 50 |
+
button.dataset.docTab = link.dataset.docTab || '';
|
| 51 |
+
button.dataset.docTarget = link.dataset.docTarget || '';
|
| 52 |
+
button.textContent = link.dataset.docLabel || link.textContent || '';
|
| 53 |
+
const meta = document.createElement('span');
|
| 54 |
+
meta.textContent = (link.dataset.docTab || 'docs') + ' section';
|
| 55 |
+
button.appendChild(meta);
|
| 56 |
+
docsSearchResults.appendChild(button);
|
| 57 |
+
});
|
| 58 |
+
}
|
| 59 |
+
function applyDocsFilter() {
|
| 60 |
+
const panel = activeDocPanel();
|
| 61 |
+
if (!panel) return;
|
| 62 |
+
const q = (docsSearch.value || '').trim().toLowerCase();
|
| 63 |
+
renderDocsSearchResults(q);
|
| 64 |
+
Array.from(panel.querySelectorAll('[data-doc-page]')).forEach(page => {
|
| 65 |
+
page.style.display = (!q || page.dataset.docPage.includes(q)) ? '' : 'none';
|
| 66 |
+
});
|
| 67 |
+
}
|
| 68 |
+
docButtons.forEach(button => button.addEventListener('click', () => activateDocTab(button.dataset.docTab)));
|
| 69 |
+
document.addEventListener('click', event => {
|
| 70 |
+
const link = event.target.closest('a[data-doc-target]');
|
| 71 |
+
if (!link) return;
|
| 72 |
+
event.preventDefault();
|
| 73 |
+
jumpToDocTarget(link.dataset.docTab, link.dataset.docTarget);
|
| 74 |
+
});
|
| 75 |
+
if (docsSearchResults) docsSearchResults.addEventListener('click', event => {
|
| 76 |
+
const button = event.target.closest('button[data-doc-target]');
|
| 77 |
+
if (!button) return;
|
| 78 |
+
jumpToDocTarget(button.dataset.docTab, button.dataset.docTarget);
|
| 79 |
+
});
|
| 80 |
+
if (docsSearch) docsSearch.addEventListener('input', applyDocsFilter);
|
| 81 |
+
if (docsSearch) docsSearch.addEventListener('keydown', event => {
|
| 82 |
+
if (event.key !== 'Enter') return;
|
| 83 |
+
const first = docsSearchResults ? docsSearchResults.querySelector('button[data-doc-target]') : null;
|
| 84 |
+
if (first) jumpToDocTarget(first.dataset.docTab, first.dataset.docTarget);
|
| 85 |
+
});
|
| 86 |
+
const initialDocTab = (location.hash || '').replace('#doc-tab-', '');
|
| 87 |
+
if (initialDocTab && docButtons.some(button => button.dataset.docTab === initialDocTab)) activateDocTab(initialDocTab);
|
| 88 |
+
const initialDocTarget = (location.hash || '').replace('#', '');
|
| 89 |
+
const initialDocLink = initialDocTarget ? docLinks.find(link => link.dataset.docTarget === initialDocTarget) : null;
|
| 90 |
+
if (initialDocLink) activateDocTab(initialDocLink.dataset.docTab);
|
| 91 |
+
applyDocsFilter();
|
src/ctx/assets/monitor-manage.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
(() => {
|
| 2 |
+
const config = window.CTX_MONITOR_MANAGE || {};
|
| 3 |
+
const MANAGE_MUTATIONS_ENABLED = Boolean(config.mutationsEnabled);
|
| 4 |
+
const MANAGE_TOKEN = config.token || "";
|
| 5 |
+
let manageResults = Array.isArray(config.initialResults) ? config.initialResults : [];
|
| 6 |
+
|
| 7 |
+
const resultsEl = document.getElementById("manage-results");
|
| 8 |
+
const statusEl = document.getElementById("manage-search-status");
|
| 9 |
+
const form = document.getElementById("entity-editor-form");
|
| 10 |
+
const editorStatus = document.getElementById("entity-editor-status");
|
| 11 |
+
let selected = null;
|
| 12 |
+
|
| 13 |
+
function escapeHtml(value) {
|
| 14 |
+
return String(value ?? "").replace(/[&<>"']/g, (ch) => (
|
| 15 |
+
{"&": "&", "<": "<", ">": ">", "\"": """, "'": "'"}[ch]
|
| 16 |
+
));
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
function displaySlug(slug) {
|
| 20 |
+
return String(slug || "").replace(/^skills-sh-/, "");
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
function entityLabel(row) {
|
| 24 |
+
return row.type + ":" + displaySlug(row.slug);
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
function setStatus(text) {
|
| 28 |
+
editorStatus.textContent = text || "";
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
function fillForm(detail) {
|
| 32 |
+
selected = {slug: detail.slug, type: detail.type};
|
| 33 |
+
const fm = detail.frontmatter || {};
|
| 34 |
+
form.slug.value = detail.slug || "";
|
| 35 |
+
form.entity_type.value = detail.type || "skill";
|
| 36 |
+
form.title.value = fm.title || fm.name || detail.slug || "";
|
| 37 |
+
form.description.value = fm.description || "";
|
| 38 |
+
form.tags.value = Array.isArray(fm.tags) ? fm.tags.join(", ") : (fm.tags || "");
|
| 39 |
+
form.source_url.value = fm.source_url || fm.repo_url || fm.github_url || fm.homepage_url || "";
|
| 40 |
+
form.body.value = detail.body || "";
|
| 41 |
+
setStatus("editing " + entityLabel(selected));
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
function renderResults(rows) {
|
| 45 |
+
statusEl.textContent = rows.length + " result" + (rows.length === 1 ? "" : "s");
|
| 46 |
+
if (!rows.length) {
|
| 47 |
+
resultsEl.innerHTML = '<p class="muted">No entities found.</p>';
|
| 48 |
+
return;
|
| 49 |
+
}
|
| 50 |
+
resultsEl.innerHTML = rows.map((row) => (
|
| 51 |
+
'<button type="button" class="manage-result" data-slug="' + escapeHtml(row.slug)
|
| 52 |
+
+ '" data-type="' + escapeHtml(row.type)
|
| 53 |
+
+ '"><strong>' + escapeHtml(row.display_slug || displaySlug(row.slug))
|
| 54 |
+
+ '</strong><span class="pill entity-type-' + escapeHtml(row.type) + '">'
|
| 55 |
+
+ escapeHtml(row.type) + '</span><span class="muted">'
|
| 56 |
+
+ escapeHtml(row.description || row.title || "") + "</span></button>"
|
| 57 |
+
)).join("");
|
| 58 |
+
document.querySelectorAll(".manage-result").forEach((btn) => btn.addEventListener("click", async () => {
|
| 59 |
+
const slug = btn.dataset.slug;
|
| 60 |
+
const type = btn.dataset.type;
|
| 61 |
+
const res = await fetch("/api/entity/" + encodeURIComponent(slug) + ".json?type=" + encodeURIComponent(type));
|
| 62 |
+
if (!res.ok) {
|
| 63 |
+
setStatus("load failed: " + res.statusText);
|
| 64 |
+
return;
|
| 65 |
+
}
|
| 66 |
+
fillForm(await res.json());
|
| 67 |
+
}));
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
let timer = null;
|
| 71 |
+
|
| 72 |
+
async function searchNow() {
|
| 73 |
+
const q = document.getElementById("manage-search").value.trim();
|
| 74 |
+
const type = document.getElementById("manage-type").value;
|
| 75 |
+
const url = "/api/entities/search.json?q=" + encodeURIComponent(q)
|
| 76 |
+
+ (type ? "&type=" + encodeURIComponent(type) : "");
|
| 77 |
+
statusEl.textContent = "Searching...";
|
| 78 |
+
const res = await fetch(url);
|
| 79 |
+
if (!res.ok) {
|
| 80 |
+
statusEl.textContent = "Search failed: " + res.statusText;
|
| 81 |
+
return;
|
| 82 |
+
}
|
| 83 |
+
manageResults = (await res.json()).results || [];
|
| 84 |
+
renderResults(manageResults);
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
function scheduleSearch() {
|
| 88 |
+
clearTimeout(timer);
|
| 89 |
+
timer = setTimeout(searchNow, 250);
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
async function post(url, payload) {
|
| 93 |
+
if (!MANAGE_MUTATIONS_ENABLED) {
|
| 94 |
+
return {ok: false, detail: "mutations disabled on non-loopback bind"};
|
| 95 |
+
}
|
| 96 |
+
const res = await fetch(url, {
|
| 97 |
+
method: "POST",
|
| 98 |
+
headers: {"Content-Type": "application/json", "X-CTX-Monitor-Token": MANAGE_TOKEN},
|
| 99 |
+
body: JSON.stringify(payload),
|
| 100 |
+
});
|
| 101 |
+
let data = {};
|
| 102 |
+
try {
|
| 103 |
+
data = await res.json();
|
| 104 |
+
} catch (_) {
|
| 105 |
+
// The API usually responds with JSON, but keep the UI resilient to empty errors.
|
| 106 |
+
}
|
| 107 |
+
data.ok = res.ok && data.ok !== false;
|
| 108 |
+
return data;
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
document.getElementById("manage-search").addEventListener("input", scheduleSearch);
|
| 112 |
+
document.getElementById("manage-type").addEventListener("change", searchNow);
|
| 113 |
+
document.getElementById("entity-new-button").addEventListener("click", () => {
|
| 114 |
+
selected = null;
|
| 115 |
+
form.reset();
|
| 116 |
+
setStatus("new entity");
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
form.addEventListener("submit", async (ev) => {
|
| 120 |
+
ev.preventDefault();
|
| 121 |
+
const payload = Object.fromEntries(new FormData(form).entries());
|
| 122 |
+
const isUpdate = selected && selected.slug === payload.slug && selected.type === payload.entity_type;
|
| 123 |
+
if (isUpdate) {
|
| 124 |
+
const ok = confirm(
|
| 125 |
+
"Update existing " + payload.entity_type + ":" + payload.slug + "?\n\n"
|
| 126 |
+
+ "Benefit: keeps the catalog current.\n"
|
| 127 |
+
+ "Risk: a lower-quality edit can degrade recommendations.",
|
| 128 |
+
);
|
| 129 |
+
if (!ok) {
|
| 130 |
+
setStatus("update cancelled");
|
| 131 |
+
return;
|
| 132 |
+
}
|
| 133 |
+
payload.confirm_update = "true";
|
| 134 |
+
}
|
| 135 |
+
setStatus("saving...");
|
| 136 |
+
const data = await post("/api/entity/upsert", payload);
|
| 137 |
+
setStatus(data.detail || (data.ok ? "saved" : "save failed"));
|
| 138 |
+
if (data.ok) searchNow();
|
| 139 |
+
});
|
| 140 |
+
|
| 141 |
+
document.getElementById("entity-delete-button").addEventListener("click", async () => {
|
| 142 |
+
const slug = form.slug.value.trim();
|
| 143 |
+
const type = form.entity_type.value;
|
| 144 |
+
if (!slug || !confirm("Delete " + type + ":" + slug + " from the wiki catalog?")) return;
|
| 145 |
+
setStatus("deleting...");
|
| 146 |
+
const data = await post("/api/entity/delete", {slug, entity_type: type});
|
| 147 |
+
setStatus(data.detail || (data.ok ? "deleted" : "delete failed"));
|
| 148 |
+
if (data.ok) {
|
| 149 |
+
selected = null;
|
| 150 |
+
form.reset();
|
| 151 |
+
searchNow();
|
| 152 |
+
}
|
| 153 |
+
});
|
| 154 |
+
|
| 155 |
+
renderResults(manageResults);
|
| 156 |
+
})();
|
src/ctx/assets/monitor-nav.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
(function () {
|
| 2 |
+
const nav = document.getElementById('dashboard-nav');
|
| 3 |
+
if (!nav) return;
|
| 4 |
+
const storageKey = nav.dataset.navStorageKey;
|
| 5 |
+
const defaultKeys = JSON.parse(nav.dataset.navDefaultKeys || '[]');
|
| 6 |
+
const reset = document.getElementById('nav-reset');
|
| 7 |
+
function links() { return Array.from(nav.querySelectorAll('a[data-nav-key]')); }
|
| 8 |
+
function linkFor(key) { return nav.querySelector('a[data-nav-key="' + CSS.escape(key) + '"]'); }
|
| 9 |
+
function applyOrder(order) {
|
| 10 |
+
const valid = Array.isArray(order) ? order.filter(key => defaultKeys.includes(key)) : [];
|
| 11 |
+
const merged = valid.concat(defaultKeys.filter(key => !valid.includes(key)));
|
| 12 |
+
merged.forEach(key => { const link = linkFor(key); if (link) nav.appendChild(link); });
|
| 13 |
+
if (reset) nav.appendChild(reset);
|
| 14 |
+
}
|
| 15 |
+
function saveOrder() {
|
| 16 |
+
try { localStorage.setItem(storageKey, JSON.stringify(links().map(a => a.dataset.navKey))); } catch (_) {}
|
| 17 |
+
}
|
| 18 |
+
function clearDragState() {
|
| 19 |
+
links().forEach(item => item.classList.remove('nav-drag-over', 'nav-dragging'));
|
| 20 |
+
}
|
| 21 |
+
function insertionTarget(clientX, clientY) {
|
| 22 |
+
const candidates = links().filter(link => link !== dragged);
|
| 23 |
+
if (!candidates.length) return reset;
|
| 24 |
+
const sameRow = candidates.filter(link => {
|
| 25 |
+
const rect = link.getBoundingClientRect();
|
| 26 |
+
return clientY >= rect.top - 8 && clientY <= rect.bottom + 8;
|
| 27 |
+
});
|
| 28 |
+
const pool = sameRow.length ? sameRow : candidates;
|
| 29 |
+
for (const link of pool) {
|
| 30 |
+
const rect = link.getBoundingClientRect();
|
| 31 |
+
if (clientX < rect.left + rect.width / 2) return link;
|
| 32 |
+
}
|
| 33 |
+
return reset;
|
| 34 |
+
}
|
| 35 |
+
function resetOrder() {
|
| 36 |
+
try { localStorage.removeItem(storageKey); } catch (_) {}
|
| 37 |
+
applyOrder(defaultKeys);
|
| 38 |
+
}
|
| 39 |
+
try { applyOrder(JSON.parse(localStorage.getItem(storageKey) || '[]')); } catch (_) { applyOrder(defaultKeys); }
|
| 40 |
+
let dragged = null;
|
| 41 |
+
links().forEach(link => {
|
| 42 |
+
link.addEventListener('dragstart', event => {
|
| 43 |
+
dragged = link;
|
| 44 |
+
link.classList.add('nav-dragging');
|
| 45 |
+
if (event.dataTransfer) {
|
| 46 |
+
event.dataTransfer.effectAllowed = 'move';
|
| 47 |
+
event.dataTransfer.setData('text/plain', link.dataset.navKey || '');
|
| 48 |
+
}
|
| 49 |
+
});
|
| 50 |
+
link.addEventListener('dragend', () => {
|
| 51 |
+
clearDragState();
|
| 52 |
+
if (reset) nav.appendChild(reset);
|
| 53 |
+
saveOrder();
|
| 54 |
+
dragged = null;
|
| 55 |
+
});
|
| 56 |
+
});
|
| 57 |
+
nav.addEventListener('dragover', event => {
|
| 58 |
+
if (!dragged) return;
|
| 59 |
+
event.preventDefault();
|
| 60 |
+
const target = insertionTarget(event.clientX, event.clientY);
|
| 61 |
+
links().forEach(item => item.classList.remove('nav-drag-over'));
|
| 62 |
+
if (target && target !== dragged) {
|
| 63 |
+
if (target.dataset && target.dataset.navKey) target.classList.add('nav-drag-over');
|
| 64 |
+
nav.insertBefore(dragged, target);
|
| 65 |
+
if (reset) nav.appendChild(reset);
|
| 66 |
+
}
|
| 67 |
+
});
|
| 68 |
+
nav.addEventListener('drop', event => {
|
| 69 |
+
if (!dragged) return;
|
| 70 |
+
event.preventDefault();
|
| 71 |
+
clearDragState();
|
| 72 |
+
if (reset) nav.appendChild(reset);
|
| 73 |
+
saveOrder();
|
| 74 |
+
});
|
| 75 |
+
if (reset) reset.addEventListener('click', resetOrder);
|
| 76 |
+
})();
|
src/ctx/assets/monitor.css
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
:root {
|
| 2 |
+
color-scheme: light dark;
|
| 3 |
+
--bg: #eef3f8;
|
| 4 |
+
--surface: #ffffff;
|
| 5 |
+
--surface-2: #f8fafc;
|
| 6 |
+
--surface-3: #eef2f7;
|
| 7 |
+
--text: #0f172a;
|
| 8 |
+
--muted-text: #64748b;
|
| 9 |
+
--border: #d8e1ee;
|
| 10 |
+
--accent: #2563eb;
|
| 11 |
+
--accent-strong: #1d4ed8;
|
| 12 |
+
--accent-soft: #dbeafe;
|
| 13 |
+
--accent-ring: rgba(37, 99, 235, 0.22);
|
| 14 |
+
--ok: #059669;
|
| 15 |
+
--warning: #d97706;
|
| 16 |
+
--danger: #dc2626;
|
| 17 |
+
--radius: 8px;
|
| 18 |
+
--shadow: 0 18px 48px rgba(15, 23, 42, 0.10);
|
| 19 |
+
--shadow-soft: 0 1px 2px rgba(15, 23, 42, 0.06);
|
| 20 |
+
}
|
| 21 |
+
* { box-sizing: border-box; }
|
| 22 |
+
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
| 23 |
+
margin: 0; padding: 0; line-height: 1.5; background: var(--bg); color: var(--text); }
|
| 24 |
+
body::before { content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;
|
| 25 |
+
background:
|
| 26 |
+
radial-gradient(circle at 18% -10%, rgba(37,99,235,0.16), transparent 30rem),
|
| 27 |
+
radial-gradient(circle at 88% 4%, rgba(20,184,166,0.12), transparent 28rem),
|
| 28 |
+
linear-gradient(180deg, #f8fbff 0%, var(--bg) 42%, #edf2f7 100%); }
|
| 29 |
+
.app-shell { width: min(1500px, calc(100vw - 32px)); margin: 0 auto; padding: 1rem 0 2.5rem; }
|
| 30 |
+
.app-header { display: flex; align-items: center; justify-content: space-between; gap: 1rem;
|
| 31 |
+
margin-bottom: 0.75rem; padding: 0.8rem 0.15rem; }
|
| 32 |
+
.app-brand { display: inline-flex; align-items: center; gap: 0.55rem; color: var(--text);
|
| 33 |
+
font-weight: 800; letter-spacing: 0; text-decoration: none; }
|
| 34 |
+
.app-brand:hover { text-decoration: none; }
|
| 35 |
+
.app-brand-mark { display: inline-grid; place-items: center; width: 2.15rem; height: 2.15rem;
|
| 36 |
+
border-radius: 8px; background: #0f172a; color: #fff; box-shadow: var(--shadow-soft); }
|
| 37 |
+
.app-header-meta { color: var(--muted-text); font-size: 0.86rem; text-align: right; }
|
| 38 |
+
.app-main { min-width: 0; }
|
| 39 |
+
h1 { margin-top: 0; letter-spacing: 0; }
|
| 40 |
+
h2, h3 { letter-spacing: 0; }
|
| 41 |
+
a { color: var(--accent); text-decoration: none; }
|
| 42 |
+
a:hover { text-decoration: underline; }
|
| 43 |
+
table { border-collapse: collapse; width: 100%; margin: 1rem 0; }
|
| 44 |
+
th, td { text-align: left; padding: 0.4rem 0.8rem; border-bottom: 1px solid var(--border);
|
| 45 |
+
font-size: 0.92rem; }
|
| 46 |
+
th { background: var(--surface-3); font-weight: 600; }
|
| 47 |
+
tr:hover { background: rgba(0,0,0,0.02); }
|
| 48 |
+
button, input, select, textarea {
|
| 49 |
+
font: inherit;
|
| 50 |
+
color: inherit;
|
| 51 |
+
border: 1px solid var(--border);
|
| 52 |
+
border-radius: 6px;
|
| 53 |
+
background: var(--surface);
|
| 54 |
+
}
|
| 55 |
+
button {
|
| 56 |
+
cursor: pointer;
|
| 57 |
+
padding: 0.38rem 0.7rem;
|
| 58 |
+
background: var(--accent);
|
| 59 |
+
border-color: var(--accent);
|
| 60 |
+
color: #fff;
|
| 61 |
+
font-weight: 650;
|
| 62 |
+
}
|
| 63 |
+
button:hover { background: var(--accent-strong); border-color: var(--accent-strong); }
|
| 64 |
+
button.secondary { background: var(--surface); color: var(--text); border-color: var(--border); }
|
| 65 |
+
button.secondary:hover { background: var(--surface-3); }
|
| 66 |
+
input, select, textarea { padding: 0.42rem 0.55rem; }
|
| 67 |
+
input:focus, select:focus, textarea:focus, button:focus {
|
| 68 |
+
outline: 2px solid var(--accent-soft);
|
| 69 |
+
outline-offset: 2px;
|
| 70 |
+
}
|
| 71 |
+
.pill { display: inline-block; padding: 0.15rem 0.55rem; border-radius: 999px;
|
| 72 |
+
font-size: 0.8rem; font-weight: 600; background: #e5e7eb; color: #111; }
|
| 73 |
+
.entity-type-skill { background: #e0e7ff; color: #312e81; }
|
| 74 |
+
.entity-type-agent { background: #fef3c7; color: #78350f; }
|
| 75 |
+
.entity-type-mcp-server { background: #fee2e2; color: #7f1d1d; }
|
| 76 |
+
.entity-type-harness { background: #dcfce7; color: #14532d; }
|
| 77 |
+
.grade-A { background: #d1fae5; color: #065f46; }
|
| 78 |
+
.grade-B { background: #dbeafe; color: #1e3a8a; }
|
| 79 |
+
.grade-C { background: #fef3c7; color: #78350f; }
|
| 80 |
+
.grade-D { background: #fed7aa; color: #7c2d12; }
|
| 81 |
+
.grade-F { background: #fee2e2; color: #7f1d1d; }
|
| 82 |
+
code, pre { background: rgba(15,23,42,0.06); padding: 0 0.3rem; border-radius: 3px;
|
| 83 |
+
font-family: "SF Mono", Monaco, Consolas, monospace; font-size: 0.85rem; }
|
| 84 |
+
pre { padding: 0.6rem 0.8rem; overflow-x: auto; }
|
| 85 |
+
.muted { color: var(--muted-text); font-size: 0.85rem; }
|
| 86 |
+
.error { color: #991b1b; background: #fee2e2; border: 1px solid #fecaca;
|
| 87 |
+
border-radius: 6px; padding: 0.5rem 0.65rem; }
|
| 88 |
+
.nav { display: flex; gap: 0.35rem; margin: 0 0 1.4rem; align-items: center; flex-wrap: wrap;
|
| 89 |
+
position: sticky; top: 0; z-index: 10; padding: 0.55rem 0.45rem;
|
| 90 |
+
border: 1px solid rgba(216,225,238,0.86); border-radius: 12px;
|
| 91 |
+
background: rgba(255,255,255,0.88); box-shadow: var(--shadow); backdrop-filter: blur(14px); }
|
| 92 |
+
.nav a[draggable="true"] { cursor: grab; border-radius: 6px; padding: 0.28rem 0.48rem;
|
| 93 |
+
font-weight: 620; color: #334155; }
|
| 94 |
+
.nav a[draggable="true"]:hover { background: rgba(37,99,235,0.09); color: var(--accent);
|
| 95 |
+
text-decoration: none; }
|
| 96 |
+
.nav a.nav-dragging { opacity: 0.45; cursor: grabbing; }
|
| 97 |
+
.nav a.nav-drag-over { outline: 2px solid #93c5fd; background: rgba(147,197,253,0.18); }
|
| 98 |
+
.nav-reset { border: 1px solid #d1d5db; border-radius: 4px; background: transparent;
|
| 99 |
+
color: #6b7280; cursor: pointer; padding: 0.1rem 0.35rem; font-size: 0.78rem; }
|
| 100 |
+
.card { border: 1px solid rgba(216,225,238,0.92); border-radius: 12px; padding: 1rem 1.25rem;
|
| 101 |
+
margin-bottom: 1rem; background: rgba(255,255,255,0.94); box-shadow: var(--shadow-soft); }
|
| 102 |
+
.card:hover { box-shadow: 0 10px 28px rgba(15,23,42,0.07); }
|
| 103 |
+
.stat-card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); }
|
| 104 |
+
.wiki-entity-grid { display: grid; grid-template-columns: minmax(0, 1fr) minmax(280px, 360px);
|
| 105 |
+
gap: 1rem; align-items: start; }
|
| 106 |
+
.wiki-body { overflow-wrap: anywhere; }
|
| 107 |
+
.wiki-body h1, .wiki-body h2, .wiki-body h3 { margin-top: 0.9rem; }
|
| 108 |
+
.wiki-body h1:first-child, .wiki-body h2:first-child, .wiki-body h3:first-child { margin-top: 0; }
|
| 109 |
+
.wiki-body ul, .wiki-body ol { padding-left: 1.35rem; }
|
| 110 |
+
.wiki-body li { margin: 0.2rem 0; }
|
| 111 |
+
.wiki-body pre { white-space: pre-wrap; }
|
| 112 |
+
.frontmatter-table { table-layout: fixed; font-size: 0.85rem; }
|
| 113 |
+
.frontmatter-table td:last-child code { white-space: normal; overflow-wrap: anywhere; }
|
| 114 |
+
.entity-tabs { display: flex; gap: 0.4rem; margin: 0.8rem 0 1rem; flex-wrap: wrap; }
|
| 115 |
+
.entity-tab-button { border: 1px solid #d1d5db; border-radius: 6px; background: #fff;
|
| 116 |
+
color: inherit; cursor: pointer; padding: 0.35rem 0.7rem; }
|
| 117 |
+
.entity-tab-button.active { background: #111827; color: #fff; border-color: #111827; }
|
| 118 |
+
.entity-tab-panel[hidden] { display: none; }
|
| 119 |
+
.graph-live-results { display: flex; flex-direction: column; gap: 0.35rem; margin-top: 0.45rem;
|
| 120 |
+
max-height: 18rem; overflow-y: auto; }
|
| 121 |
+
.graph-live-results[hidden] { display: none; }
|
| 122 |
+
.graph-live-result { display: flex; flex-direction: column; align-items: stretch; gap: 0.18rem;
|
| 123 |
+
text-align: left; background: var(--surface-2); color: var(--text);
|
| 124 |
+
border-color: var(--border); padding: 0.48rem 0.55rem; }
|
| 125 |
+
.graph-live-result:hover { background: var(--accent-soft); border-color: var(--accent); }
|
| 126 |
+
.graph-live-result small { color: var(--muted-text); font-weight: 500; line-height: 1.25; }
|
| 127 |
+
.graph-live-empty { color: var(--muted-text); font-size: 0.82rem; padding: 0.35rem 0.1rem; }
|
| 128 |
+
.graph-match-card { overflow: hidden; }
|
| 129 |
+
.graph-match-summary { display: flex; align-items: center; gap: 0.35rem; margin-top: 0.35rem; }
|
| 130 |
+
.graph-match-histogram { height: 2.2rem; display: flex; align-items: end; gap: 3px;
|
| 131 |
+
padding: 0.25rem 0.15rem 0.1rem; }
|
| 132 |
+
.graph-match-bar { flex: 1 1 0; min-width: 0; min-height: 0.22rem; border: 0;
|
| 133 |
+
border-radius: 4px 4px 0 0; background: #bfd0e4; opacity: 0.74;
|
| 134 |
+
cursor: pointer; padding: 0; transition: background 120ms ease,
|
| 135 |
+
opacity 120ms ease, transform 120ms ease; }
|
| 136 |
+
.graph-match-bar:hover,
|
| 137 |
+
.graph-match-bar:focus-visible { background: #1d4ed8; opacity: 1; outline: none;
|
| 138 |
+
transform: translateY(-1px); }
|
| 139 |
+
.graph-match-bar.active { background: #2563eb; opacity: 0.96; }
|
| 140 |
+
.graph-range-wrap { position: relative; height: 1.65rem; margin-top: 0.05rem; }
|
| 141 |
+
.graph-range-track,
|
| 142 |
+
.graph-range-fill { position: absolute; left: 0; right: 0; top: 50%; height: 0.3rem;
|
| 143 |
+
transform: translateY(-50%); border-radius: 999px; }
|
| 144 |
+
.graph-range-track { background: #dbe3ef; box-shadow: inset 0 1px 2px rgba(15,23,42,0.10); }
|
| 145 |
+
.graph-range-fill { right: auto; background: #2563eb; box-shadow: 0 0 0 1px rgba(37,99,235,0.10); }
|
| 146 |
+
.graph-range-wrap input[type="range"] { position: absolute; inset: 0; width: 100%; margin: 0;
|
| 147 |
+
appearance: none; -webkit-appearance: none;
|
| 148 |
+
background: transparent; border: 0; box-shadow: none;
|
| 149 |
+
color: transparent; padding: 0; pointer-events: none; }
|
| 150 |
+
.graph-range-wrap input[type="range"]:focus,
|
| 151 |
+
.graph-range-wrap input[type="range"]:focus-visible,
|
| 152 |
+
.graph-range-wrap input[type="range"]:active { outline: none !important; box-shadow: none !important; }
|
| 153 |
+
.graph-range-wrap input[type="range"]::-moz-focus-outer { border: 0; }
|
| 154 |
+
.graph-range-wrap input[type="range"]::-webkit-slider-runnable-track { height: 0.3rem; background: transparent;
|
| 155 |
+
border: 0; box-shadow: none; }
|
| 156 |
+
.graph-range-wrap input[type="range"]::-moz-range-track { height: 0.3rem; background: transparent;
|
| 157 |
+
border: 0; box-shadow: none; }
|
| 158 |
+
.graph-range-wrap input[type="range"]::-webkit-slider-thumb { appearance: none; -webkit-appearance: none;
|
| 159 |
+
width: 1rem; height: 1rem;
|
| 160 |
+
margin-top: calc((0.3rem - 1rem) / 2);
|
| 161 |
+
border: 0.25rem solid #2563eb;
|
| 162 |
+
border-radius: 999px; background: #fff;
|
| 163 |
+
outline: none;
|
| 164 |
+
box-shadow: 0 1px 4px rgba(15,23,42,0.24);
|
| 165 |
+
cursor: ew-resize; pointer-events: auto; }
|
| 166 |
+
.graph-range-wrap input[type="range"]::-moz-range-thumb { width: 0.5rem; height: 0.5rem;
|
| 167 |
+
border: 0.25rem solid #2563eb;
|
| 168 |
+
border-radius: 999px; background: #fff;
|
| 169 |
+
outline: none;
|
| 170 |
+
box-shadow: 0 1px 4px rgba(15,23,42,0.24);
|
| 171 |
+
cursor: ew-resize; pointer-events: auto; }
|
| 172 |
+
.graph-range-wrap input[type="range"]:focus-visible::-webkit-slider-thumb {
|
| 173 |
+
box-shadow: 0 0 0 0.24rem var(--accent-ring), 0 1px 4px rgba(15,23,42,0.24);
|
| 174 |
+
}
|
| 175 |
+
.graph-range-wrap input[type="range"]:focus-visible::-moz-range-thumb {
|
| 176 |
+
box-shadow: 0 0 0 0.24rem var(--accent-ring), 0 1px 4px rgba(15,23,42,0.24);
|
| 177 |
+
}
|
| 178 |
+
.graph-range-scale { display: flex; justify-content: space-between; color: var(--muted-text);
|
| 179 |
+
font-size: 0.72rem; line-height: 1; margin-top: 0.22rem; }
|
| 180 |
+
.graph-stage { width: 100%; height: calc(100vh - 2rem); height: calc(100dvh - 2rem);
|
| 181 |
+
min-height: 42rem; border: 1px solid var(--border); border-radius: 12px;
|
| 182 |
+
background: var(--surface); overflow: hidden; box-shadow: var(--shadow); }
|
| 183 |
+
.graph-renderer-shell { --graph-inspector-height: 14rem; height: 100%; display: grid; overflow: hidden; border-radius: 12px;
|
| 184 |
+
background: linear-gradient(180deg, rgba(248,251,255,0.94), rgba(239,246,255,0.88));
|
| 185 |
+
grid-template-rows: auto minmax(18rem, 1fr) 0.65rem minmax(10rem, var(--graph-inspector-height)); }
|
| 186 |
+
.graph-toolbar { display: flex; align-items: center; gap: 0.45rem; padding: 0.4rem 0.55rem;
|
| 187 |
+
border-bottom: 1px solid var(--border); background: rgba(255,255,255,0.86);
|
| 188 |
+
backdrop-filter: blur(10px); flex-wrap: wrap; }
|
| 189 |
+
.graph-toolbar button { padding: 0.22rem 0.48rem; line-height: 1.2; }
|
| 190 |
+
.graph-toolbar .muted { font-size: 0.78rem; line-height: 1.25; }
|
| 191 |
+
.graph-canvas-wrap { position: relative; min-height: 0; background: transparent; cursor: grab; }
|
| 192 |
+
.graph-canvas-wrap:active { cursor: grabbing; }
|
| 193 |
+
.graph-canvas-wrap [data-3d-node-id],
|
| 194 |
+
.graph-canvas-wrap [data-testid="graph-svg-node"] { cursor: pointer; }
|
| 195 |
+
.graph-canvas-wrap [data-edge-detail] { cursor: help; }
|
| 196 |
+
.graph-canvas-wrap svg { background:
|
| 197 |
+
radial-gradient(circle at 50% 42%, rgba(37,99,235,0.08), transparent 22rem),
|
| 198 |
+
linear-gradient(180deg, #f8fbff 0%, #eef4fb 100%) !important; }
|
| 199 |
+
.graph-canvas-wrap svg text { user-select: none; }
|
| 200 |
+
.graph-canvas-wrap [data-3d-node-id],
|
| 201 |
+
.graph-canvas-wrap [data-testid="graph-svg-node"] { outline: none; }
|
| 202 |
+
.graph-canvas-wrap [data-3d-node-id]:focus,
|
| 203 |
+
.graph-canvas-wrap [data-3d-node-id]:focus-visible,
|
| 204 |
+
.graph-canvas-wrap [data-testid="graph-svg-node"]:focus,
|
| 205 |
+
.graph-canvas-wrap [data-testid="graph-svg-node"]:focus-visible { outline: none; }
|
| 206 |
+
.graph-resize-handle { display: flex; align-items: center; justify-content: center;
|
| 207 |
+
border-top: 1px solid rgba(148,163,184,0.35);
|
| 208 |
+
border-bottom: 1px solid rgba(148,163,184,0.35);
|
| 209 |
+
background: linear-gradient(180deg, rgba(255,255,255,0.75), rgba(226,232,240,0.82));
|
| 210 |
+
cursor: ns-resize; touch-action: none; }
|
| 211 |
+
.graph-resize-handle::before { content: ""; width: 3.25rem; height: 0.22rem; border-radius: 999px;
|
| 212 |
+
background: rgba(100,116,139,0.72); box-shadow: 0 0.32rem 0 rgba(100,116,139,0.32); }
|
| 213 |
+
.graph-resize-handle:hover,
|
| 214 |
+
.graph-resize-handle:focus-visible { background: rgba(219,234,254,0.96); outline: none; }
|
| 215 |
+
.graph-resizing { user-select: none; }
|
| 216 |
+
.graph-tooltip { position: absolute; z-index: 3; max-width: 250px; pointer-events: none;
|
| 217 |
+
padding: 0.45rem 0.55rem; border: 1px solid var(--border);
|
| 218 |
+
border-radius: var(--radius); background: rgba(15,23,42,0.92);
|
| 219 |
+
color: #f8fafc; font-size: 0.78rem; line-height: 1.35;
|
| 220 |
+
box-shadow: var(--shadow); }
|
| 221 |
+
.graph-node-selected [data-testid="graph-svg-node"],
|
| 222 |
+
.graph-canvas-wrap [data-3d-node-id]:focus-visible [data-testid="graph-svg-node"] {
|
| 223 |
+
fill: #facc15 !important;
|
| 224 |
+
stroke: #0f172a !important;
|
| 225 |
+
stroke-width: 4 !important;
|
| 226 |
+
filter: drop-shadow(0 0 10px rgba(250,204,21,0.46));
|
| 227 |
+
}
|
| 228 |
+
.graph-edge-selected { stroke: #3b82f6 !important; stroke-opacity: 0.42 !important; }
|
| 229 |
+
.graph-inspector-grid { display: grid; grid-template-columns: minmax(0,1fr);
|
| 230 |
+
gap: 0.6rem; padding: 0.55rem 0.65rem; border-top: 1px solid var(--border);
|
| 231 |
+
background: rgba(255,255,255,0.9); min-height: 0; overflow: hidden; }
|
| 232 |
+
.graph-list-panel { overflow: auto; border-top: 1px solid var(--border);
|
| 233 |
+
background: rgba(255,255,255,0.82); }
|
| 234 |
+
.graph-fallback-label, .graph-neighbor-label, .graph-link-label { font-weight: 700; color: var(--text); }
|
| 235 |
+
.graph-fallback-node:hover .graph-fallback-label { color: var(--accent); }
|
| 236 |
+
.graph-node-detail-panel,
|
| 237 |
+
[data-testid="graph-edge-detail"] { min-height: 0; max-height: 100%; overflow: auto; }
|
| 238 |
+
.graph-node-detail-panel { width: 100%; }
|
| 239 |
+
.graph-edge-detail-inline { width: 100%; margin-bottom: 0.55rem; padding: 0.4rem 0.55rem;
|
| 240 |
+
border: 1px solid var(--border); border-radius: var(--radius);
|
| 241 |
+
background: rgba(248,250,252,0.92); }
|
| 242 |
+
.graph-selected-summary { display: grid; gap: 0.25rem; margin-bottom: 0.55rem; }
|
| 243 |
+
.graph-selected-summary p { margin: 0.15rem 0 0; }
|
| 244 |
+
.graph-neighbor-tree h3 { margin: 0.45rem 0 0.35rem; font-size: 1rem; }
|
| 245 |
+
.graph-neighbor-group { border: 1px solid var(--border); border-radius: var(--radius);
|
| 246 |
+
margin-bottom: 0.45rem; background: var(--surface); }
|
| 247 |
+
.graph-weak-links { border-style: dashed; background: rgba(100,116,139,0.06); }
|
| 248 |
+
.graph-weak-links summary { color: var(--muted-text); }
|
| 249 |
+
.graph-weak-links p { margin: 0; padding: 0 0.55rem 0.55rem; }
|
| 250 |
+
.graph-neighbor-group > summary { cursor: pointer; padding: 0.42rem 0.55rem; font-weight: 700; }
|
| 251 |
+
.graph-neighbor-group ul { list-style: none; padding: 0; margin: 0; }
|
| 252 |
+
.graph-neighbor-item { border-top: 1px solid var(--border); padding: 0.5rem 0.55rem; }
|
| 253 |
+
.graph-neighbor-row { display: flex; justify-content: space-between; gap: 0.55rem; align-items: center; }
|
| 254 |
+
.graph-edge-signals { display: flex; gap: 0.35rem; flex-wrap: wrap; margin-top: 0.28rem; }
|
| 255 |
+
.graph-metric { background: var(--surface-3); border-radius: 999px; padding: 0.08rem 0.42rem;
|
| 256 |
+
font-size: 0.76rem; }
|
| 257 |
+
.graph-inner-links { margin-top: 0.35rem; }
|
| 258 |
+
.graph-inner-links summary { cursor: pointer; color: var(--muted-text); font-size: 0.82rem; }
|
| 259 |
+
.graph-inner-links li { padding: 0.18rem 0; font-size: 0.82rem; }
|
| 260 |
+
.docs-shell { display: flex; flex-direction: column; gap: 1rem; }
|
| 261 |
+
.docs-hero { border: 1px solid var(--border); border-radius: 12px;
|
| 262 |
+
background: linear-gradient(135deg, #ffffff 0%, #f8fbff 62%, #eef6ff 100%);
|
| 263 |
+
box-shadow: var(--shadow); padding: 1.25rem; overflow: hidden; }
|
| 264 |
+
.docs-hero-grid { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 1.25rem;
|
| 265 |
+
align-items: end; }
|
| 266 |
+
.docs-eyebrow { color: var(--accent); font-size: 0.78rem; font-weight: 750; margin-bottom: 0.35rem; }
|
| 267 |
+
.docs-hero h1 { margin: 0; font-size: clamp(2rem, 4vw, 3.2rem); line-height: 1.04; }
|
| 268 |
+
.docs-hero p { max-width: 52rem; margin: 0.65rem 0 0; color: var(--muted-text); font-size: 1rem; }
|
| 269 |
+
.docs-hero-meta { display: flex; gap: 0.5rem; flex-wrap: wrap; justify-content: flex-end; }
|
| 270 |
+
.docs-stat { border: 1px solid rgba(37,99,235,0.18); border-radius: 999px;
|
| 271 |
+
background: rgba(37,99,235,0.08); color: #1e3a8a; padding: 0.28rem 0.65rem;
|
| 272 |
+
font-size: 0.82rem; font-weight: 700; white-space: nowrap; }
|
| 273 |
+
.docs-actions { display: flex; align-items: center; gap: 0.65rem; flex-wrap: wrap;
|
| 274 |
+
margin-top: 1rem; }
|
| 275 |
+
.docs-search-wrap { flex: 1 1 22rem; max-width: 38rem; }
|
| 276 |
+
.docs-search-wrap input { width: 100%; padding: 0.62rem 0.75rem; border-radius: var(--radius);
|
| 277 |
+
border-color: rgba(37,99,235,0.24); background: rgba(255,255,255,0.86); }
|
| 278 |
+
.docs-public-link { font-weight: 700; white-space: nowrap; }
|
| 279 |
+
.docs-tabs { display: flex; gap: 0.4rem; flex-wrap: wrap; margin: 0;
|
| 280 |
+
border: 1px solid var(--border); border-radius: 12px; background: var(--surface);
|
| 281 |
+
padding: 0.45rem; box-shadow: 0 1px 2px rgba(15,23,42,0.04); }
|
| 282 |
+
.docs-tab-button { border: 1px solid transparent; border-radius: 999px; background: transparent;
|
| 283 |
+
color: var(--muted-text); padding: 0.42rem 0.85rem; }
|
| 284 |
+
.docs-tab-button:hover { background: var(--surface-3); color: var(--text); }
|
| 285 |
+
.docs-tab-button.active { background: #111827; color: #fff; border-color: #111827; }
|
| 286 |
+
.docs-tab-panel[hidden] { display: none; }
|
| 287 |
+
.docs-reader { display: grid; grid-template-columns: minmax(220px, 280px) minmax(0, 1fr);
|
| 288 |
+
gap: 1rem; align-items: start; }
|
| 289 |
+
.docs-page-list { position: sticky; top: 4.5rem; display: flex; flex-direction: column;
|
| 290 |
+
gap: 0.25rem; border: 1px solid var(--border); border-radius: 12px;
|
| 291 |
+
background: var(--surface); padding: 0.6rem; box-shadow: 0 1px 2px rgba(15,23,42,0.04); }
|
| 292 |
+
.docs-toc-page { border-bottom: 1px solid var(--border); padding: 0.2rem 0 0.35rem; }
|
| 293 |
+
.docs-toc-page:last-child { border-bottom: 0; }
|
| 294 |
+
.docs-page-list a { display: block; padding: 0.38rem 0.55rem; border-radius: 8px;
|
| 295 |
+
color: var(--muted-text); line-height: 1.25; }
|
| 296 |
+
.docs-page-list a:hover { background: var(--surface-3); color: var(--text); text-decoration: none; }
|
| 297 |
+
.docs-page-link { color: var(--text) !important; font-weight: 750; }
|
| 298 |
+
.docs-heading-list { display: flex; flex-direction: column; gap: 0.05rem; margin: 0.1rem 0 0.2rem; }
|
| 299 |
+
.docs-heading-link { font-size: 0.82rem; font-weight: 600; }
|
| 300 |
+
.docs-heading-level-2 { margin-left: 0.45rem; }
|
| 301 |
+
.docs-heading-level-3 { margin-left: 1.1rem; }
|
| 302 |
+
.docs-heading-level-4 { margin-left: 1.75rem; font-size: 0.78rem; }
|
| 303 |
+
.docs-page { border: 1px solid var(--border); border-radius: 12px;
|
| 304 |
+
background: var(--surface); padding: 1.25rem 1.45rem; margin-bottom: 1rem;
|
| 305 |
+
box-shadow: 0 1px 2px rgba(15,23,42,0.04); }
|
| 306 |
+
.docs-page-source { display: flex; justify-content: space-between; gap: 0.75rem;
|
| 307 |
+
align-items: center; margin-bottom: 0.85rem; color: var(--muted-text); }
|
| 308 |
+
.docs-page-source code { background: var(--surface-3); color: var(--text); }
|
| 309 |
+
.docs-page .admonition { border-left: 4px solid var(--accent); background: var(--surface-2);
|
| 310 |
+
border-radius: var(--radius); padding: 0.75rem 0.9rem; margin: 1rem 0; }
|
| 311 |
+
.docs-page .admonition-title { font-weight: 750; margin: 0 0 0.45rem; }
|
| 312 |
+
.docs-page .tabbed-set { border: 1px solid var(--border); border-radius: var(--radius);
|
| 313 |
+
padding: 0.75rem; margin: 1rem 0; }
|
| 314 |
+
.docs-page p, .docs-page li { line-height: 1.65; }
|
| 315 |
+
.docs-page h1 { font-size: 2rem; line-height: 1.12; }
|
| 316 |
+
.docs-page h2 { font-size: 1.45rem; margin-top: 1.45rem; }
|
| 317 |
+
.docs-page h3 { font-size: 1.12rem; margin-top: 1.15rem; }
|
| 318 |
+
.docs-page .grid.cards > ul { list-style: none; padding-left: 0; display: grid;
|
| 319 |
+
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
| 320 |
+
gap: 0.85rem; }
|
| 321 |
+
.docs-page .grid.cards > ul > li { border: 1px solid var(--border); border-radius: 12px;
|
| 322 |
+
background: var(--surface-2); padding: 0.95rem 1rem;
|
| 323 |
+
box-shadow: 0 1px 2px rgba(15,23,42,0.04); }
|
| 324 |
+
.docs-page .grid.cards > ul > li:hover { border-color: rgba(37,99,235,0.32);
|
| 325 |
+
background: #ffffff; }
|
| 326 |
+
.docs-page .grid.cards hr { border: 0; border-top: 1px solid var(--border); margin: 0.55rem 0; }
|
| 327 |
+
.docs-page .headerlink { color: var(--muted-text); font-size: 0.78em; margin-left: 0.35rem; }
|
| 328 |
+
.docs-search-results { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
| 329 |
+
gap: 0.45rem; margin-top: 0.75rem; }
|
| 330 |
+
.docs-search-results[hidden] { display: none; }
|
| 331 |
+
.docs-search-result { display: flex; flex-direction: column; gap: 0.12rem; text-align: left;
|
| 332 |
+
background: var(--surface); color: var(--text); border-color: var(--border);
|
| 333 |
+
border-radius: var(--radius); padding: 0.55rem 0.65rem; }
|
| 334 |
+
.docs-search-result span { color: var(--muted-text); font-size: 0.78rem; font-weight: 500; }
|
| 335 |
+
.docs-search-empty { color: var(--muted-text); font-size: 0.86rem; padding: 0.4rem 0.1rem; }
|
| 336 |
+
.quality-signal-table { table-layout: fixed; }
|
| 337 |
+
.quality-signal-table td:last-child code { white-space: pre-wrap; overflow-wrap: anywhere; }
|
| 338 |
+
.wizard-layout { display: grid; grid-template-columns: minmax(0, 1.2fr) minmax(320px, 0.8fr);
|
| 339 |
+
gap: 1rem; align-items: start; }
|
| 340 |
+
.wizard-step { border-left: 3px solid var(--accent); padding-left: 0.8rem; margin-bottom: 1rem; }
|
| 341 |
+
.wizard-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0.75rem; }
|
| 342 |
+
.wizard-grid label { display: flex; flex-direction: column; gap: 0.25rem; font-size: 0.9rem; }
|
| 343 |
+
.wizard-grid .wide { grid-column: 1 / -1; }
|
| 344 |
+
.setup-header { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 1rem;
|
| 345 |
+
align-items: end; margin-bottom: 1rem; }
|
| 346 |
+
.setup-kicker { text-transform: uppercase; letter-spacing: 0; font-size: 0.74rem;
|
| 347 |
+
font-weight: 750; color: var(--muted-text); }
|
| 348 |
+
.setup-flow { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 0.55rem;
|
| 349 |
+
margin: 0.8rem 0 1rem; }
|
| 350 |
+
.setup-flow-step { border: 1px solid var(--border); border-radius: var(--radius);
|
| 351 |
+
background: var(--surface); padding: 0.7rem; min-height: 4.4rem; }
|
| 352 |
+
.setup-flow-step strong { display: block; font-size: 0.88rem; margin-bottom: 0.2rem; }
|
| 353 |
+
.command-box { background: #0f172a; color: #e2e8f0; border-radius: var(--radius);
|
| 354 |
+
padding: 0.85rem; white-space: pre-wrap; overflow-x: auto; min-height: 8rem; }
|
| 355 |
+
.harness-card { border: 1px solid var(--border); border-radius: var(--radius); padding: 0.8rem;
|
| 356 |
+
background: var(--surface); display: flex; flex-direction: column; gap: 0.35rem; }
|
| 357 |
+
.harness-card[data-fit-hidden="true"] { display: none; }
|
| 358 |
+
.harness-card.selected { outline: 2px solid var(--accent); outline-offset: 2px; }
|
| 359 |
+
.harness-card button { align-self: flex-start; }
|
| 360 |
+
.manage-results { display: flex; flex-direction: column; gap: 0.45rem; max-height: 65vh; overflow-y: auto; }
|
| 361 |
+
.manage-result { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 0.25rem 0.5rem;
|
| 362 |
+
text-align: left; border: 1px solid var(--border); border-radius: var(--radius);
|
| 363 |
+
padding: 0.65rem 0.75rem; background: var(--surface); cursor: pointer; }
|
| 364 |
+
.manage-result:hover { border-color: var(--accent); background: var(--surface-2); }
|
| 365 |
+
.manage-result .muted { grid-column: 1 / -1; font-size: 0.82rem; }
|
| 366 |
+
@media (max-width: 860px) {
|
| 367 |
+
.wiki-entity-grid { grid-template-columns: 1fr; }
|
| 368 |
+
.wizard-layout, .wizard-grid, .setup-header, .setup-flow { grid-template-columns: 1fr; }
|
| 369 |
+
.docs-hero-grid { grid-template-columns: 1fr; }
|
| 370 |
+
.docs-hero-meta { justify-content: flex-start; }
|
| 371 |
+
.docs-reader { grid-template-columns: 1fr; }
|
| 372 |
+
.docs-page-list { position: static; }
|
| 373 |
+
}
|
| 374 |
+
@media (prefers-color-scheme: dark) {
|
| 375 |
+
:root {
|
| 376 |
+
--bg: #0b1120;
|
| 377 |
+
--surface: #111827;
|
| 378 |
+
--surface-2: #0f172a;
|
| 379 |
+
--surface-3: #1f2937;
|
| 380 |
+
--text: #e5e7eb;
|
| 381 |
+
--muted-text: #94a3b8;
|
| 382 |
+
--border: #334155;
|
| 383 |
+
--accent: #60a5fa;
|
| 384 |
+
--accent-strong: #93c5fd;
|
| 385 |
+
--accent-soft: rgba(96,165,250,0.28);
|
| 386 |
+
--accent-ring: rgba(96,165,250,0.26);
|
| 387 |
+
--shadow: 0 12px 34px rgba(0,0,0,0.28);
|
| 388 |
+
--shadow-soft: 0 1px 2px rgba(0,0,0,0.28);
|
| 389 |
+
}
|
| 390 |
+
body { background: var(--bg); color: var(--text); }
|
| 391 |
+
body::before {
|
| 392 |
+
background:
|
| 393 |
+
radial-gradient(circle at 18% -10%, rgba(37,99,235,0.20), transparent 30rem),
|
| 394 |
+
radial-gradient(circle at 88% 4%, rgba(20,184,166,0.12), transparent 28rem),
|
| 395 |
+
linear-gradient(180deg, #0f172a 0%, #0b1120 100%);
|
| 396 |
+
}
|
| 397 |
+
.app-brand-mark { background: #e2e8f0; color: #0f172a; }
|
| 398 |
+
th { background: rgba(255,255,255,0.05); }
|
| 399 |
+
tr:hover { background: rgba(255,255,255,0.03); }
|
| 400 |
+
.nav { background: rgba(17,24,39,0.92); }
|
| 401 |
+
.nav a[draggable="true"] { color: #e5e7eb; }
|
| 402 |
+
.nav a[draggable="true"]:hover { background: #1f2937; }
|
| 403 |
+
.card { border-color: var(--border); }
|
| 404 |
+
.graph-renderer-shell,
|
| 405 |
+
.graph-toolbar,
|
| 406 |
+
.graph-inspector-grid,
|
| 407 |
+
.graph-list-panel { background: rgba(17,24,39,0.90); }
|
| 408 |
+
.graph-canvas-wrap svg {
|
| 409 |
+
background:
|
| 410 |
+
radial-gradient(circle at 50% 42%, rgba(96,165,250,0.14), transparent 22rem),
|
| 411 |
+
linear-gradient(180deg, #0f172a 0%, #111827 100%) !important;
|
| 412 |
+
}
|
| 413 |
+
.entity-tab-button { background: #0f172a; border-color: #334155; }
|
| 414 |
+
.entity-tab-button.active { background: #e2e8f0; color: #0f172a; }
|
| 415 |
+
.docs-hero { background: linear-gradient(135deg, #111827 0%, #0f172a 62%, #0b1120 100%); }
|
| 416 |
+
.docs-stat { border-color: rgba(96,165,250,0.28); background: rgba(96,165,250,0.12);
|
| 417 |
+
color: #bfdbfe; }
|
| 418 |
+
.docs-search-wrap input { background: rgba(15,23,42,0.86); border-color: #334155; }
|
| 419 |
+
.docs-tab-button.active { background: #e2e8f0; color: #0f172a; }
|
| 420 |
+
.docs-page .grid.cards > ul > li:hover { background: #111827; }
|
| 421 |
+
code, pre { background: rgba(255,255,255,0.06); }
|
| 422 |
+
.error { color: #fecaca; background: rgba(127,29,29,0.25);
|
| 423 |
+
border-color: rgba(248,113,113,0.35); }
|
| 424 |
+
}
|
src/ctx/cli/run.py
CHANGED
|
@@ -30,6 +30,7 @@ import math
|
|
| 30 |
import os
|
| 31 |
import shlex
|
| 32 |
import sys
|
|
|
|
| 33 |
from dataclasses import replace
|
| 34 |
from fnmatch import fnmatchcase
|
| 35 |
from pathlib import Path
|
|
@@ -52,6 +53,7 @@ from ctx.adapters.generic.state import (
|
|
| 52 |
new_session_id,
|
| 53 |
)
|
| 54 |
from ctx.adapters.generic.tools import McpRouter, McpServerConfig
|
|
|
|
| 55 |
|
| 56 |
|
| 57 |
_logger = logging.getLogger(__name__)
|
|
@@ -73,6 +75,7 @@ _PROVIDER_KEY_ENV: dict[str, str] = {
|
|
| 73 |
"openrouter": "OPENROUTER_API_KEY",
|
| 74 |
"anthropic": "ANTHROPIC_API_KEY",
|
| 75 |
"openai": "OPENAI_API_KEY",
|
|
|
|
| 76 |
"gemini": "GEMINI_API_KEY",
|
| 77 |
"mistral": "MISTRAL_API_KEY",
|
| 78 |
"deepseek": "DEEPSEEK_API_KEY",
|
|
@@ -457,10 +460,143 @@ def _record_lifecycle_safely(
|
|
| 457 |
**kwargs: Any,
|
| 458 |
) -> None:
|
| 459 |
method = getattr(lifecycle, method_name)
|
|
|
|
| 460 |
try:
|
| 461 |
method(**kwargs)
|
| 462 |
except (OSError, ValueError) as exc:
|
| 463 |
_logger.warning("ctx runtime lifecycle record failed: %s", exc)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 464 |
|
| 465 |
|
| 466 |
# ── Main entry ─────────────────────────────────────────────────────────────
|
|
@@ -780,6 +916,7 @@ def _cmd_run(args: argparse.Namespace) -> int:
|
|
| 780 |
if profile_error:
|
| 781 |
print(profile_error, file=sys.stderr)
|
| 782 |
return 2
|
|
|
|
| 783 |
|
| 784 |
sdir = Path(args.sessions_dir) if args.sessions_dir else default_sessions_dir()
|
| 785 |
|
|
@@ -902,163 +1039,209 @@ def _cmd_run(args: argparse.Namespace) -> int:
|
|
| 902 |
),
|
| 903 |
}
|
| 904 |
observer = JsonlObserver(store, session_metadata=metadata)
|
| 905 |
-
|
| 906 |
-
|
| 907 |
-
|
| 908 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 909 |
session_id=session_id,
|
| 910 |
-
|
| 911 |
-
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
|
|
|
|
|
|
|
|
|
|
| 918 |
)
|
| 919 |
|
| 920 |
-
|
| 921 |
-
|
| 922 |
-
|
| 923 |
-
|
| 924 |
-
|
| 925 |
-
|
| 926 |
-
|
| 927 |
-
|
| 928 |
-
|
| 929 |
-
|
| 930 |
-
|
| 931 |
-
|
| 932 |
-
|
| 933 |
-
|
| 934 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 935 |
)
|
| 936 |
-
|
| 937 |
-
|
| 938 |
-
|
| 939 |
-
|
| 940 |
-
|
| 941 |
-
|
| 942 |
-
"error: --contract requires --planner (the contract "
|
| 943 |
-
"refines the planner's success_criteria into "
|
| 944 |
-
"testable clauses)."
|
| 945 |
)
|
| 946 |
-
|
| 947 |
-
|
| 948 |
-
if args.planner:
|
| 949 |
-
pieces.insert(0, "planner")
|
| 950 |
-
if args.contract:
|
| 951 |
-
pieces.append("contract")
|
| 952 |
-
print(
|
| 953 |
-
f"[ctx] triad enabled: {' → '.join(pieces)} "
|
| 954 |
-
f"(max_rounds={args.evaluator_rounds})",
|
| 955 |
-
file=sys.stderr,
|
| 956 |
)
|
| 957 |
-
|
| 958 |
-
|
| 959 |
-
|
| 960 |
-
|
| 961 |
-
|
| 962 |
-
|
| 963 |
-
|
| 964 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 965 |
)
|
| 966 |
-
|
| 967 |
-
|
| 968 |
-
|
| 969 |
-
|
| 970 |
-
|
| 971 |
-
|
| 972 |
-
|
| 973 |
-
|
| 974 |
-
|
| 975 |
-
|
| 976 |
-
|
| 977 |
-
|
| 978 |
-
|
| 979 |
-
|
| 980 |
-
|
| 981 |
-
|
| 982 |
-
|
| 983 |
-
|
| 984 |
-
|
| 985 |
-
|
| 986 |
-
|
| 987 |
-
|
| 988 |
-
|
| 989 |
-
|
| 990 |
-
|
| 991 |
-
|
| 992 |
-
|
| 993 |
-
|
| 994 |
-
|
| 995 |
-
|
| 996 |
-
|
| 997 |
-
|
| 998 |
-
|
| 999 |
-
|
| 1000 |
-
|
| 1001 |
-
|
| 1002 |
-
|
| 1003 |
-
|
| 1004 |
-
|
| 1005 |
-
|
| 1006 |
-
|
| 1007 |
-
|
| 1008 |
-
|
| 1009 |
-
|
| 1010 |
-
|
| 1011 |
-
|
| 1012 |
-
|
| 1013 |
-
|
| 1014 |
-
|
| 1015 |
-
|
| 1016 |
-
|
| 1017 |
-
|
| 1018 |
-
|
| 1019 |
-
|
| 1020 |
-
if
|
| 1021 |
-
print(
|
| 1022 |
-
f"[ctx] evaluator: {len(eval_outcome.rounds)} "
|
| 1023 |
-
f"round(s); final verdict = {last.evaluation.verdict}",
|
| 1024 |
-
file=sys.stderr,
|
| 1025 |
-
)
|
| 1026 |
-
else:
|
| 1027 |
-
result = run_loop(
|
| 1028 |
-
provider=provider,
|
| 1029 |
-
system_prompt=system_prompt,
|
| 1030 |
-
task=args.task,
|
| 1031 |
-
router=router,
|
| 1032 |
-
extra_tools=extra_tools or None,
|
| 1033 |
-
tool_executor=tool_executor,
|
| 1034 |
-
tool_policy=tool_policy,
|
| 1035 |
-
model=args.model,
|
| 1036 |
-
temperature=args.temperature,
|
| 1037 |
-
max_tokens=args.max_tokens,
|
| 1038 |
-
provider_timeout=args.provider_timeout,
|
| 1039 |
-
max_iterations=args.max_iterations,
|
| 1040 |
-
budget_usd=args.budget_usd,
|
| 1041 |
-
budget_tokens=args.budget_tokens,
|
| 1042 |
-
observer=observer,
|
| 1043 |
-
compactor=compactor,
|
| 1044 |
)
|
| 1045 |
-
|
| 1046 |
-
|
| 1047 |
-
_record_lifecycle_safely(
|
| 1048 |
-
lifecycle,
|
| 1049 |
-
"end_session",
|
| 1050 |
session_id=session_id,
|
| 1051 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1052 |
)
|
| 1053 |
-
|
| 1054 |
-
|
| 1055 |
-
|
| 1056 |
-
|
| 1057 |
-
|
| 1058 |
-
|
| 1059 |
-
|
| 1060 |
-
|
| 1061 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1062 |
|
| 1063 |
|
| 1064 |
# ── Command: resume ────────────────────────────────────────────────────────
|
|
@@ -1077,6 +1260,7 @@ def _cmd_resume(args: argparse.Namespace) -> int:
|
|
| 1077 |
state = _load_session_for_cli(args.session_id, sdir)
|
| 1078 |
if state is None:
|
| 1079 |
return 1
|
|
|
|
| 1080 |
|
| 1081 |
meta = state.metadata
|
| 1082 |
model = args.model or meta.get("model")
|
|
@@ -1150,88 +1334,128 @@ def _cmd_resume(args: argparse.Namespace) -> int:
|
|
| 1150 |
allow_tools, deny_tools = _resume_tool_policy_patterns(args, meta)
|
| 1151 |
tool_policy = _compile_tool_policy(allow_tools, deny_tools)
|
| 1152 |
|
| 1153 |
-
|
| 1154 |
-
|
| 1155 |
-
|
| 1156 |
-
|
| 1157 |
-
|
| 1158 |
-
|
| 1159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1160 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1161 |
if use_ctx_tools:
|
| 1162 |
-
|
| 1163 |
-
|
| 1164 |
-
|
| 1165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1166 |
)
|
| 1167 |
-
|
| 1168 |
-
|
| 1169 |
-
f"[ctx] resuming {args.session_id} "
|
| 1170 |
-
f"({len(state.messages)} prior messages{suffix})",
|
| 1171 |
-
file=sys.stderr,
|
| 1172 |
-
)
|
| 1173 |
-
if mcp_configs:
|
| 1174 |
-
for cfg in mcp_configs:
|
| 1175 |
-
argv = " ".join([cfg.command, *cfg.args])
|
| 1176 |
-
print(
|
| 1177 |
-
f"[ctx] restoring MCP server {cfg.name}: {argv}",
|
| 1178 |
-
file=sys.stderr,
|
| 1179 |
-
)
|
| 1180 |
-
|
| 1181 |
-
if use_ctx_tools:
|
| 1182 |
-
_record_lifecycle_safely(
|
| 1183 |
-
lifecycle,
|
| 1184 |
-
"record_dev_event",
|
| 1185 |
session_id=args.session_id,
|
| 1186 |
-
|
| 1187 |
-
|
| 1188 |
-
|
| 1189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1190 |
)
|
| 1191 |
|
| 1192 |
-
|
| 1193 |
-
|
| 1194 |
-
|
| 1195 |
-
|
| 1196 |
-
|
| 1197 |
-
|
| 1198 |
-
|
| 1199 |
-
|
| 1200 |
-
|
| 1201 |
-
|
| 1202 |
-
|
| 1203 |
-
|
| 1204 |
-
|
| 1205 |
-
|
| 1206 |
-
|
| 1207 |
-
|
| 1208 |
-
|
| 1209 |
-
|
| 1210 |
-
|
| 1211 |
-
|
| 1212 |
-
|
| 1213 |
-
|
| 1214 |
-
|
| 1215 |
-
|
| 1216 |
-
|
| 1217 |
-
|
| 1218 |
-
|
| 1219 |
-
|
| 1220 |
-
|
| 1221 |
-
|
| 1222 |
-
|
| 1223 |
-
|
| 1224 |
-
|
| 1225 |
-
lifecycle,
|
| 1226 |
-
"end_session",
|
| 1227 |
session_id=args.session_id,
|
| 1228 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1229 |
)
|
| 1230 |
-
|
| 1231 |
-
|
| 1232 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1233 |
|
| 1234 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1235 |
|
| 1236 |
|
| 1237 |
# ── Command: sessions ─────────────────────────────────────────────────────
|
|
|
|
| 30 |
import os
|
| 31 |
import shlex
|
| 32 |
import sys
|
| 33 |
+
import time
|
| 34 |
from dataclasses import replace
|
| 35 |
from fnmatch import fnmatchcase
|
| 36 |
from pathlib import Path
|
|
|
|
| 53 |
new_session_id,
|
| 54 |
)
|
| 55 |
from ctx.adapters.generic.tools import McpRouter, McpServerConfig
|
| 56 |
+
from ctx.telemetry import record_event, record_exception, telemetry_span
|
| 57 |
|
| 58 |
|
| 59 |
_logger = logging.getLogger(__name__)
|
|
|
|
| 75 |
"openrouter": "OPENROUTER_API_KEY",
|
| 76 |
"anthropic": "ANTHROPIC_API_KEY",
|
| 77 |
"openai": "OPENAI_API_KEY",
|
| 78 |
+
"huggingface": "HF_TOKEN",
|
| 79 |
"gemini": "GEMINI_API_KEY",
|
| 80 |
"mistral": "MISTRAL_API_KEY",
|
| 81 |
"deepseek": "DEEPSEEK_API_KEY",
|
|
|
|
| 460 |
**kwargs: Any,
|
| 461 |
) -> None:
|
| 462 |
method = getattr(lifecycle, method_name)
|
| 463 |
+
started = time.perf_counter()
|
| 464 |
try:
|
| 465 |
method(**kwargs)
|
| 466 |
except (OSError, ValueError) as exc:
|
| 467 |
_logger.warning("ctx runtime lifecycle record failed: %s", exc)
|
| 468 |
+
_record_cli_telemetry(
|
| 469 |
+
"ctx.runtime_lifecycle.write",
|
| 470 |
+
session_id=str(kwargs.get("session_id") or "") or None,
|
| 471 |
+
phase="failed",
|
| 472 |
+
payload={"ctx.lifecycle.method": method_name},
|
| 473 |
+
outcome="error",
|
| 474 |
+
duration_ms=_duration_ms(started),
|
| 475 |
+
error_kind=type(exc).__name__,
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def _duration_ms(started: float) -> float:
|
| 480 |
+
return (time.perf_counter() - started) * 1000.0
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def _record_cli_telemetry(
|
| 484 |
+
event_name: str,
|
| 485 |
+
*,
|
| 486 |
+
session_id: str | None,
|
| 487 |
+
phase: str,
|
| 488 |
+
payload: dict[str, Any],
|
| 489 |
+
outcome: str,
|
| 490 |
+
duration_ms: float,
|
| 491 |
+
error_kind: str | None = None,
|
| 492 |
+
exc: BaseException | None = None,
|
| 493 |
+
) -> None:
|
| 494 |
+
event_payload = dict(payload)
|
| 495 |
+
event_payload["ctx.run.phase"] = phase
|
| 496 |
+
event_payload["otel.status_code"] = "ERROR" if outcome == "error" else "OK"
|
| 497 |
+
if error_kind:
|
| 498 |
+
event_payload["error.type"] = error_kind
|
| 499 |
+
try:
|
| 500 |
+
if exc is not None:
|
| 501 |
+
record_exception(
|
| 502 |
+
event_name,
|
| 503 |
+
source="ctx-cli",
|
| 504 |
+
exc=exc,
|
| 505 |
+
transport="cli",
|
| 506 |
+
actor="user",
|
| 507 |
+
session_id=session_id,
|
| 508 |
+
outcome=outcome,
|
| 509 |
+
duration_ms=duration_ms,
|
| 510 |
+
error_kind=error_kind,
|
| 511 |
+
cwd=str(Path.cwd()),
|
| 512 |
+
payload=event_payload,
|
| 513 |
+
)
|
| 514 |
+
else:
|
| 515 |
+
record_event(
|
| 516 |
+
event_name,
|
| 517 |
+
source="ctx-cli",
|
| 518 |
+
transport="cli",
|
| 519 |
+
actor="user",
|
| 520 |
+
session_id=session_id,
|
| 521 |
+
outcome=outcome,
|
| 522 |
+
duration_ms=duration_ms,
|
| 523 |
+
error_kind=error_kind,
|
| 524 |
+
cwd=str(Path.cwd()),
|
| 525 |
+
payload=event_payload,
|
| 526 |
+
)
|
| 527 |
+
except Exception: # noqa: BLE001 - telemetry must never break the CLI.
|
| 528 |
+
pass
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def _run_start_payload(
|
| 532 |
+
args: argparse.Namespace,
|
| 533 |
+
*,
|
| 534 |
+
ctx_tools_enabled: bool,
|
| 535 |
+
mcp_count: int,
|
| 536 |
+
allow_count: int,
|
| 537 |
+
deny_count: int,
|
| 538 |
+
plan_available: bool,
|
| 539 |
+
) -> dict[str, Any]:
|
| 540 |
+
return {
|
| 541 |
+
"ctx.model": args.model,
|
| 542 |
+
"ctx.provider": args.provider or _model_provider_prefix(args.model),
|
| 543 |
+
"ctx.provider_prefix": _model_provider_prefix(args.model),
|
| 544 |
+
"ctx.task.length": len(str(args.task or "")),
|
| 545 |
+
"ctx.ctx_tools.enabled": ctx_tools_enabled,
|
| 546 |
+
"ctx.mcp.count": mcp_count,
|
| 547 |
+
"ctx.planner.enabled": bool(args.planner),
|
| 548 |
+
"ctx.planner.result_available": plan_available,
|
| 549 |
+
"ctx.evaluator.enabled": bool(args.evaluator),
|
| 550 |
+
"ctx.contract.enabled": bool(args.contract),
|
| 551 |
+
"ctx.budget.usd_configured": args.budget_usd is not None,
|
| 552 |
+
"ctx.budget.tokens_configured": args.budget_tokens is not None,
|
| 553 |
+
"ctx.tool_policy.allow_count": allow_count,
|
| 554 |
+
"ctx.tool_policy.deny_count": deny_count,
|
| 555 |
+
}
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
def _resume_start_payload(
|
| 559 |
+
args: argparse.Namespace,
|
| 560 |
+
*,
|
| 561 |
+
model: str,
|
| 562 |
+
use_ctx_tools: bool,
|
| 563 |
+
prior_message_count: int,
|
| 564 |
+
recorded_mcp_count: int,
|
| 565 |
+
restored_mcp_count: int,
|
| 566 |
+
allow_count: int,
|
| 567 |
+
deny_count: int,
|
| 568 |
+
) -> dict[str, Any]:
|
| 569 |
+
return {
|
| 570 |
+
"ctx.model": model,
|
| 571 |
+
"ctx.task.length": len(str(args.task or "")),
|
| 572 |
+
"ctx.ctx_tools.enabled": use_ctx_tools,
|
| 573 |
+
"ctx.messages.prior_count": prior_message_count,
|
| 574 |
+
"ctx.mcp.recorded_count": recorded_mcp_count,
|
| 575 |
+
"ctx.mcp.restored_count": restored_mcp_count,
|
| 576 |
+
"ctx.tool_policy.allow_count": allow_count,
|
| 577 |
+
"ctx.tool_policy.deny_count": deny_count,
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
def _loop_result_payload(result: Any) -> dict[str, Any]:
|
| 582 |
+
stop_reason = str(getattr(result, "stop_reason", "error"))
|
| 583 |
+
payload: dict[str, Any] = {"ctx.stop_reason": stop_reason}
|
| 584 |
+
if result is None:
|
| 585 |
+
return payload
|
| 586 |
+
payload["ctx.iterations"] = int(getattr(result, "iterations", 0) or 0)
|
| 587 |
+
usage = getattr(result, "usage", None)
|
| 588 |
+
if usage is not None:
|
| 589 |
+
payload["ctx.usage.input_tokens"] = int(getattr(usage, "input_tokens", 0) or 0)
|
| 590 |
+
payload["ctx.usage.output_tokens"] = int(getattr(usage, "output_tokens", 0) or 0)
|
| 591 |
+
payload["ctx.usage.cost_present"] = getattr(usage, "cost_usd", None) is not None
|
| 592 |
+
return payload
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def _loop_result_outcome(result: Any) -> tuple[str, str | None]:
|
| 596 |
+
stop_reason = str(getattr(result, "stop_reason", "error"))
|
| 597 |
+
if result is None or stop_reason in _ERROR_STOP_REASONS:
|
| 598 |
+
return "error", stop_reason
|
| 599 |
+
return "ok", None
|
| 600 |
|
| 601 |
|
| 602 |
# ── Main entry ─────────────────────────────────────────────────────────────
|
|
|
|
| 916 |
if profile_error:
|
| 917 |
print(profile_error, file=sys.stderr)
|
| 918 |
return 2
|
| 919 |
+
telemetry_started = time.perf_counter()
|
| 920 |
|
| 921 |
sdir = Path(args.sessions_dir) if args.sessions_dir else default_sessions_dir()
|
| 922 |
|
|
|
|
| 1039 |
),
|
| 1040 |
}
|
| 1041 |
observer = JsonlObserver(store, session_metadata=metadata)
|
| 1042 |
+
with telemetry_span():
|
| 1043 |
+
if ctx_tools_enabled:
|
| 1044 |
+
_record_lifecycle_safely(
|
| 1045 |
+
lifecycle,
|
| 1046 |
+
"record_dev_event",
|
| 1047 |
+
session_id=session_id,
|
| 1048 |
+
event_type="task",
|
| 1049 |
+
host="ctx-run",
|
| 1050 |
+
cwd=str(Path.cwd()),
|
| 1051 |
+
payload={
|
| 1052 |
+
"task": args.task,
|
| 1053 |
+
"model": args.model,
|
| 1054 |
+
"provider": args.provider or _model_provider_prefix(args.model),
|
| 1055 |
+
},
|
| 1056 |
+
)
|
| 1057 |
+
_record_cli_telemetry(
|
| 1058 |
+
"ctx.cli.run",
|
| 1059 |
session_id=session_id,
|
| 1060 |
+
phase="started",
|
| 1061 |
+
payload=_run_start_payload(
|
| 1062 |
+
args,
|
| 1063 |
+
ctx_tools_enabled=ctx_tools_enabled,
|
| 1064 |
+
mcp_count=len(mcp_configs),
|
| 1065 |
+
allow_count=len(allow_tools),
|
| 1066 |
+
deny_count=len(deny_tools),
|
| 1067 |
+
plan_available=plan_artifact is not None,
|
| 1068 |
+
),
|
| 1069 |
+
outcome="ok",
|
| 1070 |
+
duration_ms=_duration_ms(telemetry_started),
|
| 1071 |
)
|
| 1072 |
|
| 1073 |
+
if not args.quiet:
|
| 1074 |
+
print(f"[ctx] session {session_id} ({store.path})", file=sys.stderr)
|
| 1075 |
+
print(f"[ctx] model: {args.model}", file=sys.stderr)
|
| 1076 |
+
if args.budget_usd is not None:
|
| 1077 |
+
print(f"[ctx] budget: ${args.budget_usd:.2f}", file=sys.stderr)
|
| 1078 |
+
|
| 1079 |
+
evaluator_rounds: list[dict[str, Any]] | None = None
|
| 1080 |
+
contract_artifact = None # populated only on P/C/G/E path
|
| 1081 |
+
result = None
|
| 1082 |
+
try:
|
| 1083 |
+
if router is not None:
|
| 1084 |
+
if not args.quiet:
|
| 1085 |
+
print(
|
| 1086 |
+
f"[ctx] starting MCP servers: {[c.name for c in mcp_configs]}",
|
| 1087 |
+
file=sys.stderr,
|
| 1088 |
+
)
|
| 1089 |
+
router.start()
|
| 1090 |
+
if args.evaluator:
|
| 1091 |
+
if args.contract and not args.planner:
|
| 1092 |
+
# Contracts refine planner output; without a plan
|
| 1093 |
+
# they'd have no prior spec to refine.
|
| 1094 |
+
raise SystemExit(
|
| 1095 |
+
"error: --contract requires --planner (the contract "
|
| 1096 |
+
"refines the planner's success_criteria into "
|
| 1097 |
+
"testable clauses)."
|
| 1098 |
+
)
|
| 1099 |
+
if not args.quiet:
|
| 1100 |
+
pieces = ["evaluator"]
|
| 1101 |
+
if args.planner:
|
| 1102 |
+
pieces.insert(0, "planner")
|
| 1103 |
+
if args.contract:
|
| 1104 |
+
pieces.append("contract")
|
| 1105 |
+
print(
|
| 1106 |
+
f"[ctx] triad enabled: {' → '.join(pieces)} "
|
| 1107 |
+
f"(max_rounds={args.evaluator_rounds})",
|
| 1108 |
+
file=sys.stderr,
|
| 1109 |
+
)
|
| 1110 |
+
planner_agent = (
|
| 1111 |
+
Planner(provider, model=args.planner_model or args.model)
|
| 1112 |
+
if args.planner
|
| 1113 |
+
else None
|
| 1114 |
)
|
| 1115 |
+
contract_builder = (
|
| 1116 |
+
ContractBuilder(
|
| 1117 |
+
provider, model=args.contract_model or args.model,
|
| 1118 |
+
)
|
| 1119 |
+
if args.contract
|
| 1120 |
+
else None
|
|
|
|
|
|
|
|
|
|
| 1121 |
)
|
| 1122 |
+
evaluator_agent = Evaluator(
|
| 1123 |
+
provider, model=args.evaluator_model or args.model,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1124 |
)
|
| 1125 |
+
eval_outcome = run_with_evaluation(
|
| 1126 |
+
provider=provider,
|
| 1127 |
+
system_prompt=system_prompt,
|
| 1128 |
+
task=args.task,
|
| 1129 |
+
evaluator=evaluator_agent,
|
| 1130 |
+
max_rounds=args.evaluator_rounds,
|
| 1131 |
+
planner=planner_agent,
|
| 1132 |
+
contract_builder=contract_builder,
|
| 1133 |
+
router=router,
|
| 1134 |
+
extra_tools=extra_tools or None,
|
| 1135 |
+
tool_executor=tool_executor,
|
| 1136 |
+
tool_policy=tool_policy,
|
| 1137 |
+
model=args.model,
|
| 1138 |
+
temperature=args.temperature,
|
| 1139 |
+
max_tokens=args.max_tokens,
|
| 1140 |
+
provider_timeout=args.provider_timeout,
|
| 1141 |
+
max_iterations=args.max_iterations,
|
| 1142 |
+
budget_usd=args.budget_usd,
|
| 1143 |
+
budget_tokens=args.budget_tokens,
|
| 1144 |
+
observer=observer,
|
| 1145 |
+
compactor=compactor,
|
| 1146 |
)
|
| 1147 |
+
result = eval_outcome.final
|
| 1148 |
+
plan_artifact = eval_outcome.plan
|
| 1149 |
+
contract_artifact = eval_outcome.contract
|
| 1150 |
+
# session_start metadata was snapshotted BEFORE the planner
|
| 1151 |
+
# and contract ran (they live inside run_with_evaluation),
|
| 1152 |
+
# so plan/contract fields on that event are null. Emit
|
| 1153 |
+
# explicit events here so load_session still surfaces the
|
| 1154 |
+
# refined artifacts for resume + audit.
|
| 1155 |
+
if plan_artifact is not None:
|
| 1156 |
+
store.write_event("plan", plan_artifact.to_dict())
|
| 1157 |
+
if contract_artifact is not None:
|
| 1158 |
+
store.write_event("contract", contract_artifact.to_dict())
|
| 1159 |
+
evaluator_rounds = [
|
| 1160 |
+
{
|
| 1161 |
+
"index": r.index,
|
| 1162 |
+
"stop_reason": r.loop_result.stop_reason,
|
| 1163 |
+
"verdict": r.evaluation.verdict,
|
| 1164 |
+
"overall_score": r.evaluation.overall_score,
|
| 1165 |
+
"summary_feedback": r.evaluation.summary_feedback,
|
| 1166 |
+
"revision_directive": r.evaluation.revision_directive,
|
| 1167 |
+
"parsed_ok": r.evaluation.parsed_ok,
|
| 1168 |
+
}
|
| 1169 |
+
for r in eval_outcome.rounds
|
| 1170 |
+
]
|
| 1171 |
+
if not args.quiet:
|
| 1172 |
+
last = eval_outcome.rounds[-1] if eval_outcome.rounds else None
|
| 1173 |
+
if last is not None:
|
| 1174 |
+
print(
|
| 1175 |
+
f"[ctx] evaluator: {len(eval_outcome.rounds)} "
|
| 1176 |
+
f"round(s); final verdict = {last.evaluation.verdict}",
|
| 1177 |
+
file=sys.stderr,
|
| 1178 |
+
)
|
| 1179 |
+
else:
|
| 1180 |
+
result = run_loop(
|
| 1181 |
+
provider=provider,
|
| 1182 |
+
system_prompt=system_prompt,
|
| 1183 |
+
task=args.task,
|
| 1184 |
+
router=router,
|
| 1185 |
+
extra_tools=extra_tools or None,
|
| 1186 |
+
tool_executor=tool_executor,
|
| 1187 |
+
tool_policy=tool_policy,
|
| 1188 |
+
model=args.model,
|
| 1189 |
+
temperature=args.temperature,
|
| 1190 |
+
max_tokens=args.max_tokens,
|
| 1191 |
+
provider_timeout=args.provider_timeout,
|
| 1192 |
+
max_iterations=args.max_iterations,
|
| 1193 |
+
budget_usd=args.budget_usd,
|
| 1194 |
+
budget_tokens=args.budget_tokens,
|
| 1195 |
+
observer=observer,
|
| 1196 |
+
compactor=compactor,
|
| 1197 |
+
)
|
| 1198 |
+
except Exception as exc:
|
| 1199 |
+
failure_payload = _loop_result_payload(result)
|
| 1200 |
+
failure_payload["ctx.evaluator.round_count"] = (
|
| 1201 |
+
len(evaluator_rounds) if evaluator_rounds is not None else 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1202 |
)
|
| 1203 |
+
_record_cli_telemetry(
|
| 1204 |
+
"ctx.cli.run",
|
|
|
|
|
|
|
|
|
|
| 1205 |
session_id=session_id,
|
| 1206 |
+
phase="failed",
|
| 1207 |
+
payload=failure_payload,
|
| 1208 |
+
outcome="error",
|
| 1209 |
+
duration_ms=_duration_ms(telemetry_started),
|
| 1210 |
+
error_kind=type(exc).__name__,
|
| 1211 |
+
exc=exc,
|
| 1212 |
)
|
| 1213 |
+
raise
|
| 1214 |
+
finally:
|
| 1215 |
+
if ctx_tools_enabled:
|
| 1216 |
+
_record_lifecycle_safely(
|
| 1217 |
+
lifecycle,
|
| 1218 |
+
"end_session",
|
| 1219 |
+
session_id=session_id,
|
| 1220 |
+
status=str(getattr(result, "stop_reason", "error")),
|
| 1221 |
+
)
|
| 1222 |
+
store.close()
|
| 1223 |
+
if router is not None:
|
| 1224 |
+
router.stop()
|
| 1225 |
+
|
| 1226 |
+
outcome, error_kind = _loop_result_outcome(result)
|
| 1227 |
+
finish_payload = _loop_result_payload(result)
|
| 1228 |
+
finish_payload["ctx.evaluator.round_count"] = (
|
| 1229 |
+
len(evaluator_rounds) if evaluator_rounds is not None else 0
|
| 1230 |
+
)
|
| 1231 |
+
_record_cli_telemetry(
|
| 1232 |
+
"ctx.cli.run",
|
| 1233 |
+
session_id=session_id,
|
| 1234 |
+
phase="finished",
|
| 1235 |
+
payload=finish_payload,
|
| 1236 |
+
outcome=outcome,
|
| 1237 |
+
duration_ms=_duration_ms(telemetry_started),
|
| 1238 |
+
error_kind=error_kind,
|
| 1239 |
+
)
|
| 1240 |
+
return _emit_result(
|
| 1241 |
+
result, session_id,
|
| 1242 |
+
as_json=args.json, quiet=args.quiet,
|
| 1243 |
+
evaluator_rounds=evaluator_rounds,
|
| 1244 |
+
)
|
| 1245 |
|
| 1246 |
|
| 1247 |
# ── Command: resume ────────────────────────────────────────────────────────
|
|
|
|
| 1260 |
state = _load_session_for_cli(args.session_id, sdir)
|
| 1261 |
if state is None:
|
| 1262 |
return 1
|
| 1263 |
+
telemetry_started = time.perf_counter()
|
| 1264 |
|
| 1265 |
meta = state.metadata
|
| 1266 |
model = args.model or meta.get("model")
|
|
|
|
| 1334 |
allow_tools, deny_tools = _resume_tool_policy_patterns(args, meta)
|
| 1335 |
tool_policy = _compile_tool_policy(allow_tools, deny_tools)
|
| 1336 |
|
| 1337 |
+
with telemetry_span():
|
| 1338 |
+
if not args.quiet:
|
| 1339 |
+
bits = []
|
| 1340 |
+
if mcp_configs:
|
| 1341 |
+
bits.append(f"{len(mcp_configs)} MCP server(s)")
|
| 1342 |
+
elif recorded_mcp_configs:
|
| 1343 |
+
bits.append(
|
| 1344 |
+
f"{len(recorded_mcp_configs)} recorded MCP server(s) skipped"
|
| 1345 |
+
)
|
| 1346 |
+
if use_ctx_tools:
|
| 1347 |
+
bits.append("ctx-core tools")
|
| 1348 |
+
if allow_tools or deny_tools:
|
| 1349 |
+
bits.append(
|
| 1350 |
+
f"tool policy allow={len(allow_tools)} deny={len(deny_tools)}"
|
| 1351 |
+
)
|
| 1352 |
+
suffix = f" + {', '.join(bits)}" if bits else ""
|
| 1353 |
+
print(
|
| 1354 |
+
f"[ctx] resuming {args.session_id} "
|
| 1355 |
+
f"({len(state.messages)} prior messages{suffix})",
|
| 1356 |
+
file=sys.stderr,
|
| 1357 |
)
|
| 1358 |
+
if mcp_configs:
|
| 1359 |
+
for cfg in mcp_configs:
|
| 1360 |
+
argv = " ".join([cfg.command, *cfg.args])
|
| 1361 |
+
print(
|
| 1362 |
+
f"[ctx] restoring MCP server {cfg.name}: {argv}",
|
| 1363 |
+
file=sys.stderr,
|
| 1364 |
+
)
|
| 1365 |
+
|
| 1366 |
if use_ctx_tools:
|
| 1367 |
+
_record_lifecycle_safely(
|
| 1368 |
+
lifecycle,
|
| 1369 |
+
"record_dev_event",
|
| 1370 |
+
session_id=args.session_id,
|
| 1371 |
+
event_type="resume_task",
|
| 1372 |
+
host="ctx-resume",
|
| 1373 |
+
cwd=str(Path.cwd()),
|
| 1374 |
+
payload={"task": args.task, "model": model},
|
| 1375 |
)
|
| 1376 |
+
_record_cli_telemetry(
|
| 1377 |
+
"ctx.cli.resume",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1378 |
session_id=args.session_id,
|
| 1379 |
+
phase="started",
|
| 1380 |
+
payload=_resume_start_payload(
|
| 1381 |
+
args,
|
| 1382 |
+
model=str(model),
|
| 1383 |
+
use_ctx_tools=use_ctx_tools,
|
| 1384 |
+
prior_message_count=len(state.messages),
|
| 1385 |
+
recorded_mcp_count=len(recorded_mcp_configs),
|
| 1386 |
+
restored_mcp_count=len(mcp_configs),
|
| 1387 |
+
allow_count=len(allow_tools),
|
| 1388 |
+
deny_count=len(deny_tools),
|
| 1389 |
+
),
|
| 1390 |
+
outcome="ok",
|
| 1391 |
+
duration_ms=_duration_ms(telemetry_started),
|
| 1392 |
)
|
| 1393 |
|
| 1394 |
+
result = None
|
| 1395 |
+
try:
|
| 1396 |
+
if router is not None:
|
| 1397 |
+
router.start()
|
| 1398 |
+
result = run_loop(
|
| 1399 |
+
provider=provider,
|
| 1400 |
+
system_prompt=system_prompt,
|
| 1401 |
+
task=args.task,
|
| 1402 |
+
messages=list(state.messages),
|
| 1403 |
+
model=model,
|
| 1404 |
+
observer=observer,
|
| 1405 |
+
compactor=compactor,
|
| 1406 |
+
router=router,
|
| 1407 |
+
extra_tools=extra_tools or None,
|
| 1408 |
+
tool_executor=tool_executor,
|
| 1409 |
+
tool_policy=tool_policy,
|
| 1410 |
+
# Resume must keep the replayed transcript first; the
|
| 1411 |
+
# follow-up task is appended at the end, not shoved before
|
| 1412 |
+
# the prior conversation.
|
| 1413 |
+
append_task_after_messages=True,
|
| 1414 |
+
# Inherit the original run's safety limits when present
|
| 1415 |
+
# so the resume doesn't blow past the original ceiling.
|
| 1416 |
+
max_iterations=int(meta.get("max_iterations") or 25),
|
| 1417 |
+
temperature=float(meta.get("temperature") or 0.7),
|
| 1418 |
+
max_tokens=meta.get("max_tokens"),
|
| 1419 |
+
provider_timeout=provider_timeout,
|
| 1420 |
+
budget_usd=meta.get("budget_usd"),
|
| 1421 |
+
budget_tokens=meta.get("budget_tokens"),
|
| 1422 |
+
initial_usage=state.usage,
|
| 1423 |
+
)
|
| 1424 |
+
except Exception as exc:
|
| 1425 |
+
_record_cli_telemetry(
|
| 1426 |
+
"ctx.cli.resume",
|
|
|
|
|
|
|
| 1427 |
session_id=args.session_id,
|
| 1428 |
+
phase="failed",
|
| 1429 |
+
payload=_loop_result_payload(result),
|
| 1430 |
+
outcome="error",
|
| 1431 |
+
duration_ms=_duration_ms(telemetry_started),
|
| 1432 |
+
error_kind=type(exc).__name__,
|
| 1433 |
+
exc=exc,
|
| 1434 |
)
|
| 1435 |
+
raise
|
| 1436 |
+
finally:
|
| 1437 |
+
if use_ctx_tools:
|
| 1438 |
+
_record_lifecycle_safely(
|
| 1439 |
+
lifecycle,
|
| 1440 |
+
"end_session",
|
| 1441 |
+
session_id=args.session_id,
|
| 1442 |
+
status=str(getattr(result, "stop_reason", "error")),
|
| 1443 |
+
)
|
| 1444 |
+
store.close()
|
| 1445 |
+
if router is not None:
|
| 1446 |
+
router.stop()
|
| 1447 |
|
| 1448 |
+
outcome, error_kind = _loop_result_outcome(result)
|
| 1449 |
+
_record_cli_telemetry(
|
| 1450 |
+
"ctx.cli.resume",
|
| 1451 |
+
session_id=args.session_id,
|
| 1452 |
+
phase="finished",
|
| 1453 |
+
payload=_loop_result_payload(result),
|
| 1454 |
+
outcome=outcome,
|
| 1455 |
+
duration_ms=_duration_ms(telemetry_started),
|
| 1456 |
+
error_kind=error_kind,
|
| 1457 |
+
)
|
| 1458 |
+
return _emit_result(result, args.session_id, as_json=args.json, quiet=args.quiet)
|
| 1459 |
|
| 1460 |
|
| 1461 |
# ── Command: sessions ─────────────────────────────────────────────────────
|
src/ctx/cli/telemetry.py
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CLI helpers for operating ctx enterprise telemetry."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import copy
|
| 7 |
+
from dataclasses import asdict
|
| 8 |
+
import json
|
| 9 |
+
import sys
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Any, Mapping
|
| 12 |
+
|
| 13 |
+
from ctx.telemetry import (
|
| 14 |
+
enforce_telemetry_retention,
|
| 15 |
+
export_events,
|
| 16 |
+
export_metrics,
|
| 17 |
+
plan_telemetry_retention,
|
| 18 |
+
preview_export,
|
| 19 |
+
preview_metrics_export,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _build_parser() -> argparse.ArgumentParser:
|
| 24 |
+
parser = argparse.ArgumentParser(
|
| 25 |
+
prog="ctx-telemetry-export",
|
| 26 |
+
description="Export the local ctx telemetry spool to a configured enterprise sink.",
|
| 27 |
+
)
|
| 28 |
+
parser.add_argument(
|
| 29 |
+
"--signal",
|
| 30 |
+
choices=("events", "metrics"),
|
| 31 |
+
default="events",
|
| 32 |
+
help="Telemetry signal to export.",
|
| 33 |
+
)
|
| 34 |
+
parser.add_argument(
|
| 35 |
+
"--path",
|
| 36 |
+
type=Path,
|
| 37 |
+
default=None,
|
| 38 |
+
help="Telemetry spool to read (default: configured event or metric spool).",
|
| 39 |
+
)
|
| 40 |
+
parser.add_argument(
|
| 41 |
+
"--sink",
|
| 42 |
+
choices=("local_jsonl", "otlp_http"),
|
| 43 |
+
default=None,
|
| 44 |
+
help="Export sink for this run (default: telemetry.export.sink from config).",
|
| 45 |
+
)
|
| 46 |
+
parser.add_argument(
|
| 47 |
+
"--output",
|
| 48 |
+
type=Path,
|
| 49 |
+
default=None,
|
| 50 |
+
help="Output file for --sink local_jsonl.",
|
| 51 |
+
)
|
| 52 |
+
parser.add_argument(
|
| 53 |
+
"--otlp-endpoint",
|
| 54 |
+
default=None,
|
| 55 |
+
help="OTLP/HTTP logs or metrics endpoint for --sink otlp_http.",
|
| 56 |
+
)
|
| 57 |
+
parser.add_argument(
|
| 58 |
+
"--otlp-allowed-host",
|
| 59 |
+
action="append",
|
| 60 |
+
default=[],
|
| 61 |
+
help=(
|
| 62 |
+
"Allow one remote OTLP endpoint host for this run; repeat for "
|
| 63 |
+
"multiple hosts."
|
| 64 |
+
),
|
| 65 |
+
)
|
| 66 |
+
parser.add_argument(
|
| 67 |
+
"--checkpoint",
|
| 68 |
+
type=Path,
|
| 69 |
+
default=None,
|
| 70 |
+
help="Export checkpoint file (default: <spool>.export-checkpoint.json).",
|
| 71 |
+
)
|
| 72 |
+
parser.add_argument(
|
| 73 |
+
"--all",
|
| 74 |
+
action="store_true",
|
| 75 |
+
help="Replay the full spool instead of only events after the checkpoint.",
|
| 76 |
+
)
|
| 77 |
+
parser.add_argument(
|
| 78 |
+
"--trusted-root",
|
| 79 |
+
type=Path,
|
| 80 |
+
default=None,
|
| 81 |
+
help=argparse.SUPPRESS,
|
| 82 |
+
)
|
| 83 |
+
parser.add_argument(
|
| 84 |
+
"--dry-run",
|
| 85 |
+
action="store_true",
|
| 86 |
+
help="Read and count telemetry records without exporting them.",
|
| 87 |
+
)
|
| 88 |
+
parser.add_argument(
|
| 89 |
+
"--fail-on-degraded",
|
| 90 |
+
action="store_true",
|
| 91 |
+
help="Exit non-zero when export status is degraded, even if no sink failed.",
|
| 92 |
+
)
|
| 93 |
+
parser.add_argument("--json", action="store_true", help="Emit machine-readable JSON.")
|
| 94 |
+
return parser
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _build_retention_parser() -> argparse.ArgumentParser:
|
| 98 |
+
parser = argparse.ArgumentParser(
|
| 99 |
+
prog="ctx-telemetry-retention",
|
| 100 |
+
description="Plan or enforce local ctx telemetry retention.",
|
| 101 |
+
)
|
| 102 |
+
parser.add_argument("command", choices=("plan", "enforce"))
|
| 103 |
+
parser.add_argument(
|
| 104 |
+
"--signal",
|
| 105 |
+
choices=("all", "events", "metrics"),
|
| 106 |
+
default="all",
|
| 107 |
+
help="Telemetry signal to process.",
|
| 108 |
+
)
|
| 109 |
+
parser.add_argument(
|
| 110 |
+
"--event-path",
|
| 111 |
+
type=Path,
|
| 112 |
+
default=None,
|
| 113 |
+
help="Event spool to process (default: telemetry.path from config).",
|
| 114 |
+
)
|
| 115 |
+
parser.add_argument(
|
| 116 |
+
"--metrics-path",
|
| 117 |
+
type=Path,
|
| 118 |
+
default=None,
|
| 119 |
+
help="Metric spool to process (default: telemetry.metrics.path from config).",
|
| 120 |
+
)
|
| 121 |
+
parser.add_argument(
|
| 122 |
+
"--trusted-root",
|
| 123 |
+
type=Path,
|
| 124 |
+
default=None,
|
| 125 |
+
help=argparse.SUPPRESS,
|
| 126 |
+
)
|
| 127 |
+
parser.add_argument(
|
| 128 |
+
"--drop-malformed",
|
| 129 |
+
action="store_true",
|
| 130 |
+
help="Drop malformed JSONL records instead of preserving them.",
|
| 131 |
+
)
|
| 132 |
+
parser.add_argument("--json", action="store_true", help="Emit machine-readable JSON.")
|
| 133 |
+
return parser
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _base_telemetry_config() -> dict[str, Any]:
|
| 137 |
+
try:
|
| 138 |
+
from ctx_config import cfg # noqa: PLC0415
|
| 139 |
+
|
| 140 |
+
raw = cfg.get("telemetry", {})
|
| 141 |
+
except Exception: # noqa: BLE001 - CLI must still work in minimal installs.
|
| 142 |
+
raw = {}
|
| 143 |
+
return copy.deepcopy(dict(raw)) if isinstance(raw, Mapping) else {}
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _effective_config(args: argparse.Namespace) -> dict[str, Any]:
|
| 147 |
+
config = _base_telemetry_config()
|
| 148 |
+
if args.signal == "metrics":
|
| 149 |
+
metrics = config.get("metrics")
|
| 150 |
+
if not isinstance(metrics, dict):
|
| 151 |
+
metrics = {}
|
| 152 |
+
config["metrics"] = metrics
|
| 153 |
+
metrics["enabled"] = True
|
| 154 |
+
export = metrics.get("export")
|
| 155 |
+
if not isinstance(export, dict):
|
| 156 |
+
export = {}
|
| 157 |
+
metrics["export"] = export
|
| 158 |
+
if args.path is not None:
|
| 159 |
+
metrics["path"] = str(args.path)
|
| 160 |
+
else:
|
| 161 |
+
export = config.get("export")
|
| 162 |
+
if args.path is not None:
|
| 163 |
+
config["path"] = str(args.path)
|
| 164 |
+
if not isinstance(export, dict):
|
| 165 |
+
export = {}
|
| 166 |
+
if args.signal == "metrics":
|
| 167 |
+
config["metrics"]["export"] = export
|
| 168 |
+
else:
|
| 169 |
+
config["export"] = export
|
| 170 |
+
export["enabled"] = True
|
| 171 |
+
if args.sink is not None:
|
| 172 |
+
export["sink"] = args.sink
|
| 173 |
+
if args.output is not None:
|
| 174 |
+
export["path"] = str(args.output)
|
| 175 |
+
if args.checkpoint is not None:
|
| 176 |
+
export["checkpoint_path"] = str(args.checkpoint)
|
| 177 |
+
if args.otlp_endpoint is not None:
|
| 178 |
+
otlp = export.get("otlp")
|
| 179 |
+
if not isinstance(otlp, dict):
|
| 180 |
+
otlp = {}
|
| 181 |
+
export["otlp"] = otlp
|
| 182 |
+
otlp["endpoint"] = args.otlp_endpoint
|
| 183 |
+
if args.otlp_allowed_host:
|
| 184 |
+
otlp = export.get("otlp")
|
| 185 |
+
if not isinstance(otlp, dict):
|
| 186 |
+
otlp = {}
|
| 187 |
+
export["otlp"] = otlp
|
| 188 |
+
existing = otlp.get("allowed_hosts")
|
| 189 |
+
allowed_hosts = list(existing) if isinstance(existing, list) else []
|
| 190 |
+
allowed_hosts.extend(str(host) for host in args.otlp_allowed_host)
|
| 191 |
+
otlp["allowed_hosts"] = allowed_hosts
|
| 192 |
+
return config
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def _print_json(payload: Mapping[str, Any]) -> None:
|
| 196 |
+
print(json.dumps(payload, indent=2, sort_keys=True))
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _exit_code(*, failed: int, status: str, fail_on_degraded: bool) -> int:
|
| 200 |
+
if failed != 0:
|
| 201 |
+
return 1
|
| 202 |
+
if fail_on_degraded and status == "degraded":
|
| 203 |
+
return 1
|
| 204 |
+
return 0
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _export_summary(result: Any, *, signal: str, dry_run: bool) -> dict[str, Any]:
|
| 208 |
+
payload = {
|
| 209 |
+
"signal": signal,
|
| 210 |
+
"attempted": result.attempted,
|
| 211 |
+
"exported": 0 if dry_run else result.exported,
|
| 212 |
+
"failed": 0 if dry_run else result.failed,
|
| 213 |
+
"sink": result.sink,
|
| 214 |
+
"status": result.status,
|
| 215 |
+
"dry_run": dry_run,
|
| 216 |
+
"checkpoint_path": result.checkpoint_path,
|
| 217 |
+
"checkpoint_advanced": result.checkpoint_advanced,
|
| 218 |
+
"checkpoint_found": result.checkpoint_found,
|
| 219 |
+
"malformed_records": result.malformed_records,
|
| 220 |
+
"malformed_pending_records": result.malformed_pending_records,
|
| 221 |
+
"malformed_first_line": result.malformed_first_line,
|
| 222 |
+
"malformed_last_line": result.malformed_last_line,
|
| 223 |
+
"destination_hash": result.destination_hash,
|
| 224 |
+
"last_success_at": result.last_success_at,
|
| 225 |
+
"status_path": result.status_path,
|
| 226 |
+
}
|
| 227 |
+
if signal == "metrics":
|
| 228 |
+
payload.update(
|
| 229 |
+
{
|
| 230 |
+
"last_metric_id": result.last_metric_id,
|
| 231 |
+
"checkpoint_before_metric_id": result.checkpoint_before_metric_id,
|
| 232 |
+
"checkpoint_after_metric_id": result.checkpoint_after_metric_id,
|
| 233 |
+
"last_success_metric_id": result.last_success_metric_id,
|
| 234 |
+
"error_kind": None if dry_run else result.error_kind,
|
| 235 |
+
}
|
| 236 |
+
)
|
| 237 |
+
else:
|
| 238 |
+
payload.update(
|
| 239 |
+
{
|
| 240 |
+
"last_event_id": result.last_event_id,
|
| 241 |
+
"checkpoint_before_event_id": result.checkpoint_before_event_id,
|
| 242 |
+
"checkpoint_after_event_id": result.checkpoint_after_event_id,
|
| 243 |
+
"last_success_event_id": result.last_success_event_id,
|
| 244 |
+
"error_kind": None if dry_run else result.error_kind,
|
| 245 |
+
}
|
| 246 |
+
)
|
| 247 |
+
return payload
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def _print_export_human(payload: Mapping[str, Any], *, dry_run: bool) -> None:
|
| 251 |
+
noun = "metric(s)" if payload["signal"] == "metrics" else "event(s)"
|
| 252 |
+
if dry_run:
|
| 253 |
+
print(
|
| 254 |
+
f"Would export {payload['attempted']} telemetry {noun} "
|
| 255 |
+
f"to {payload['sink']}."
|
| 256 |
+
)
|
| 257 |
+
else:
|
| 258 |
+
print(
|
| 259 |
+
"Exported "
|
| 260 |
+
f"{payload['exported']}/{payload['attempted']} telemetry {noun} "
|
| 261 |
+
f"to {payload['sink']}."
|
| 262 |
+
)
|
| 263 |
+
if payload.get("error_kind"):
|
| 264 |
+
print(f"Telemetry export failed: {payload['error_kind']}", file=sys.stderr)
|
| 265 |
+
print(f"Export status: {payload['status']}")
|
| 266 |
+
if payload["malformed_pending_records"]:
|
| 267 |
+
print(
|
| 268 |
+
"Skipped "
|
| 269 |
+
f"{payload['malformed_pending_records']} pending malformed telemetry "
|
| 270 |
+
"record(s)."
|
| 271 |
+
)
|
| 272 |
+
if payload.get("status_path"):
|
| 273 |
+
print(f"Export status path: {payload['status_path']}")
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def main(argv: list[str] | None = None) -> int:
|
| 277 |
+
args = _build_parser().parse_args(argv)
|
| 278 |
+
config = _effective_config(args)
|
| 279 |
+
|
| 280 |
+
try:
|
| 281 |
+
if args.dry_run:
|
| 282 |
+
preview_result: Any
|
| 283 |
+
if args.signal == "metrics":
|
| 284 |
+
preview_result = preview_metrics_export(
|
| 285 |
+
args.path,
|
| 286 |
+
trusted_root=args.trusted_root,
|
| 287 |
+
config=config,
|
| 288 |
+
include_exported=args.all,
|
| 289 |
+
)
|
| 290 |
+
else:
|
| 291 |
+
preview_result = preview_export(
|
| 292 |
+
args.path,
|
| 293 |
+
trusted_root=args.trusted_root,
|
| 294 |
+
config=config,
|
| 295 |
+
include_exported=args.all,
|
| 296 |
+
)
|
| 297 |
+
payload = _export_summary(preview_result, signal=args.signal, dry_run=True)
|
| 298 |
+
if args.json:
|
| 299 |
+
_print_json(payload)
|
| 300 |
+
else:
|
| 301 |
+
_print_export_human(payload, dry_run=True)
|
| 302 |
+
return _exit_code(
|
| 303 |
+
failed=0,
|
| 304 |
+
status=str(payload["status"]),
|
| 305 |
+
fail_on_degraded=args.fail_on_degraded,
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
export_result: Any
|
| 309 |
+
if args.signal == "metrics":
|
| 310 |
+
export_result = export_metrics(
|
| 311 |
+
args.path,
|
| 312 |
+
trusted_root=args.trusted_root,
|
| 313 |
+
config=config,
|
| 314 |
+
include_exported=args.all,
|
| 315 |
+
)
|
| 316 |
+
else:
|
| 317 |
+
export_result = export_events(
|
| 318 |
+
args.path,
|
| 319 |
+
trusted_root=args.trusted_root,
|
| 320 |
+
config=config,
|
| 321 |
+
include_exported=args.all,
|
| 322 |
+
)
|
| 323 |
+
except ValueError as exc:
|
| 324 |
+
if args.json:
|
| 325 |
+
_print_json({"attempted": 0, "exported": 0, "failed": 1, "error": str(exc)})
|
| 326 |
+
else:
|
| 327 |
+
print(f"Telemetry export failed: {exc}", file=sys.stderr)
|
| 328 |
+
return 1
|
| 329 |
+
payload = _export_summary(export_result, signal=args.signal, dry_run=False)
|
| 330 |
+
if args.json:
|
| 331 |
+
_print_json(payload)
|
| 332 |
+
else:
|
| 333 |
+
_print_export_human(payload, dry_run=False)
|
| 334 |
+
return _exit_code(
|
| 335 |
+
failed=int(payload["failed"]),
|
| 336 |
+
status=str(payload["status"]),
|
| 337 |
+
fail_on_degraded=args.fail_on_degraded,
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def retention_main(argv: list[str] | None = None) -> int:
|
| 342 |
+
args = _build_retention_parser().parse_args(argv)
|
| 343 |
+
config = _base_telemetry_config()
|
| 344 |
+
drop_malformed = True if args.drop_malformed else None
|
| 345 |
+
try:
|
| 346 |
+
if args.command == "plan":
|
| 347 |
+
results = plan_telemetry_retention(
|
| 348 |
+
signal=args.signal,
|
| 349 |
+
event_path=args.event_path,
|
| 350 |
+
metrics_path=args.metrics_path,
|
| 351 |
+
trusted_root=args.trusted_root,
|
| 352 |
+
config=config,
|
| 353 |
+
drop_malformed=drop_malformed,
|
| 354 |
+
)
|
| 355 |
+
else:
|
| 356 |
+
results = enforce_telemetry_retention(
|
| 357 |
+
signal=args.signal,
|
| 358 |
+
event_path=args.event_path,
|
| 359 |
+
metrics_path=args.metrics_path,
|
| 360 |
+
trusted_root=args.trusted_root,
|
| 361 |
+
config=config,
|
| 362 |
+
drop_malformed=drop_malformed,
|
| 363 |
+
)
|
| 364 |
+
except ValueError as exc:
|
| 365 |
+
if args.json:
|
| 366 |
+
_print_json({"failed": 1, "error": str(exc)})
|
| 367 |
+
else:
|
| 368 |
+
print(f"Telemetry retention failed: {exc}", file=sys.stderr)
|
| 369 |
+
return 1
|
| 370 |
+
payload = {
|
| 371 |
+
"dry_run": args.command == "plan",
|
| 372 |
+
"results": [asdict(result) for result in results],
|
| 373 |
+
}
|
| 374 |
+
if args.json:
|
| 375 |
+
_print_json(payload)
|
| 376 |
+
else:
|
| 377 |
+
for result in results:
|
| 378 |
+
print(
|
| 379 |
+
f"{result.signal}: {result.status}; "
|
| 380 |
+
f"retained={result.retained_records} "
|
| 381 |
+
f"dropped={result.dropped_records} "
|
| 382 |
+
f"malformed_dropped={result.malformed_dropped_records}"
|
| 383 |
+
)
|
| 384 |
+
return 0
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
if __name__ == "__main__":
|
| 388 |
+
raise SystemExit(main())
|
src/ctx/config.json
CHANGED
|
@@ -41,6 +41,72 @@
|
|
| 41 |
"keep_log_days": 5
|
| 42 |
},
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
"harness": {
|
| 45 |
"_comment": "Harness catalog recommendation tuning for custom/API/local model users. Harnesses are separate from the execution bundle and are only recommended when their absolute fit score is at or above recommendation_min_fit_score. The normalized floor is kept for older user configs and display compatibility.",
|
| 46 |
"recommendation_min_normalized_score": 0.85,
|
|
@@ -106,6 +172,10 @@
|
|
| 106 |
"_comment": "Source-overlap edge construction. Pages with the same repo/source/homepage/detail/package URL can connect even when their tags differ. Buckets above dense_source_threshold are skipped so broad catalog URLs cannot create noise edges.",
|
| 107 |
"dense_source_threshold": 50
|
| 108 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
"edge_boosts": {
|
| 110 |
"_comment": "Additive edge boosts. These never create edges alone; they only strengthen pairs already justified by semantic, tags, slug tokens, source overlap, or direct wikilinks. Set a value to 0 to disable that signal.",
|
| 111 |
"direct_link": 0.10,
|
|
|
|
| 41 |
"keep_log_days": 5
|
| 42 |
},
|
| 43 |
|
| 44 |
+
"telemetry": {
|
| 45 |
+
"_comment": "Enterprise telemetry spine. Writes a redacted ctx.telemetry.v1 JSONL spool by default. Exporters are ready to use but disabled until explicitly enabled.",
|
| 46 |
+
"enabled": true,
|
| 47 |
+
"mode": "local_redacted",
|
| 48 |
+
"path": "~/.ctx/telemetry/events.jsonl",
|
| 49 |
+
"export": {
|
| 50 |
+
"enabled": false,
|
| 51 |
+
"sink": "otlp_http",
|
| 52 |
+
"path": "~/.ctx/telemetry/exported-events.jsonl",
|
| 53 |
+
"otlp": {
|
| 54 |
+
"endpoint": "http://localhost:4318/v1/logs",
|
| 55 |
+
"allowed_hosts": [],
|
| 56 |
+
"headers": {},
|
| 57 |
+
"timeout_seconds": 5.0,
|
| 58 |
+
"service_name": "ctx",
|
| 59 |
+
"service_namespace": "ctx",
|
| 60 |
+
"deployment_environment": "local"
|
| 61 |
+
}
|
| 62 |
+
},
|
| 63 |
+
"metrics": {
|
| 64 |
+
"_comment": "OpenTelemetry-style counters and histograms. Writes a separate redacted metric spool by default; metric exporters use independent checkpoint/status files.",
|
| 65 |
+
"enabled": true,
|
| 66 |
+
"path": "~/.ctx/telemetry/metrics.jsonl",
|
| 67 |
+
"histogram_bounds": [1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000],
|
| 68 |
+
"export": {
|
| 69 |
+
"enabled": false,
|
| 70 |
+
"sink": "otlp_http",
|
| 71 |
+
"path": "~/.ctx/telemetry/exported-metrics.jsonl",
|
| 72 |
+
"otlp": {
|
| 73 |
+
"endpoint": "http://localhost:4318/v1/metrics",
|
| 74 |
+
"allowed_hosts": [],
|
| 75 |
+
"headers": {},
|
| 76 |
+
"timeout_seconds": 5.0,
|
| 77 |
+
"service_name": "ctx",
|
| 78 |
+
"service_namespace": "ctx",
|
| 79 |
+
"deployment_environment": "local"
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
},
|
| 83 |
+
"privacy": {
|
| 84 |
+
"store_raw_inputs": false,
|
| 85 |
+
"hash_identifiers": true,
|
| 86 |
+
"hash_salt_env": "CTX_TELEMETRY_HASH_SALT",
|
| 87 |
+
"hash_salt_path": "~/.ctx/telemetry/hash-salt"
|
| 88 |
+
},
|
| 89 |
+
"retention": {
|
| 90 |
+
"_comment": "Retention is applied only by explicit operator command/API calls. Dry-runs do not write, malformed records are preserved by default, and min_keep_records prevents accidental full deletion.",
|
| 91 |
+
"enabled": true,
|
| 92 |
+
"status_path": "~/.ctx/telemetry/retention-status.json",
|
| 93 |
+
"min_keep_records": 1000,
|
| 94 |
+
"drop_malformed": false,
|
| 95 |
+
"events": {
|
| 96 |
+
"max_age_days": 90,
|
| 97 |
+
"max_records": 100000
|
| 98 |
+
},
|
| 99 |
+
"metrics": {
|
| 100 |
+
"max_age_days": 30,
|
| 101 |
+
"max_records": 200000
|
| 102 |
+
}
|
| 103 |
+
},
|
| 104 |
+
"limits": {
|
| 105 |
+
"max_payload_keys": 40,
|
| 106 |
+
"max_payload_value_chars": 1024
|
| 107 |
+
}
|
| 108 |
+
},
|
| 109 |
+
|
| 110 |
"harness": {
|
| 111 |
"_comment": "Harness catalog recommendation tuning for custom/API/local model users. Harnesses are separate from the execution bundle and are only recommended when their absolute fit score is at or above recommendation_min_fit_score. The normalized floor is kept for older user configs and display compatibility.",
|
| 112 |
"recommendation_min_normalized_score": 0.85,
|
|
|
|
| 172 |
"_comment": "Source-overlap edge construction. Pages with the same repo/source/homepage/detail/package URL can connect even when their tags differ. Buckets above dense_source_threshold are skipped so broad catalog URLs cannot create noise edges.",
|
| 173 |
"dense_source_threshold": 50
|
| 174 |
},
|
| 175 |
+
"pack_compaction": {
|
| 176 |
+
"_comment": "Operational threshold for modular graph/wiki maintenance. ctx writes small overlay packs for local entity updates; when either graph or wiki overlays reach this count, status reports that periodic compaction is due. Compaction still requires an explicit ctx.core.wiki.pack_compaction compact/promote command.",
|
| 177 |
+
"overlay_threshold": 25
|
| 178 |
+
},
|
| 179 |
"edge_boosts": {
|
| 180 |
"_comment": "Additive edge boosts. These never create edges alone; they only strengthen pairs already justified by semantic, tags, slug tokens, source overlap, or direct wikilinks. Set a value to 0 to disable that signal.",
|
| 181 |
"direct_link": 0.10,
|
src/ctx/core/entity_types.py
CHANGED
|
@@ -3,6 +3,7 @@
|
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
from pathlib import Path
|
|
|
|
| 6 |
|
| 7 |
|
| 8 |
ENTITY_TYPES: tuple[str, ...] = (
|
|
@@ -48,6 +49,48 @@ RELATED_SECTION_FOR_ENTITY_TYPE: dict[str, str] = {
|
|
| 48 |
"harness": "## Related Harnesses",
|
| 49 |
}
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
def mcp_shard(slug: str) -> str:
|
| 53 |
"""Return the shard segment for an MCP slug."""
|
|
@@ -71,6 +114,17 @@ def entity_page_path(wiki: Path, entity_type: str, slug: str) -> Path | None:
|
|
| 71 |
return wiki / relpath if relpath is not None else None
|
| 72 |
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
def entity_wikilink(entity_type: str, slug: str) -> str | None:
|
| 75 |
"""Return an Obsidian-style wikilink for an entity."""
|
| 76 |
relpath = entity_relpath(entity_type, slug)
|
|
|
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
from pathlib import Path
|
| 6 |
+
from typing import Collection
|
| 7 |
|
| 8 |
|
| 9 |
ENTITY_TYPES: tuple[str, ...] = (
|
|
|
|
| 49 |
"harness": "## Related Harnesses",
|
| 50 |
}
|
| 51 |
|
| 52 |
+
ENTITY_TYPE_ALIASES: dict[str, str] = {
|
| 53 |
+
"skills": "skill",
|
| 54 |
+
"skill": "skill",
|
| 55 |
+
"agents": "agent",
|
| 56 |
+
"agent": "agent",
|
| 57 |
+
"mcp": "mcp-server",
|
| 58 |
+
"mcp-server": "mcp-server",
|
| 59 |
+
"mcp-servers": "mcp-server",
|
| 60 |
+
"plugins": "plugin",
|
| 61 |
+
"plugin": "plugin",
|
| 62 |
+
"harness": "harness",
|
| 63 |
+
"harnesses": "harness",
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def normalize_entity_type(
|
| 68 |
+
raw: object,
|
| 69 |
+
*,
|
| 70 |
+
allowed: Collection[str] = ENTITY_TYPES,
|
| 71 |
+
) -> str | None:
|
| 72 |
+
"""Return a canonical entity type for user/API aliases."""
|
| 73 |
+
if raw is None:
|
| 74 |
+
return None
|
| 75 |
+
value = str(raw).strip()
|
| 76 |
+
if not value:
|
| 77 |
+
return None
|
| 78 |
+
normalized = ENTITY_TYPE_ALIASES.get(value.lower(), value)
|
| 79 |
+
return normalized if normalized in allowed else None
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def entity_source_specs(
|
| 83 |
+
entity_types: Collection[str] = RECOMMENDABLE_ENTITY_TYPES,
|
| 84 |
+
) -> tuple[tuple[str, str, bool], ...]:
|
| 85 |
+
"""Return ``(subject_type, entity_type, recursive)`` wiki source specs."""
|
| 86 |
+
specs: list[tuple[str, str, bool]] = []
|
| 87 |
+
for entity_type in RECOMMENDABLE_ENTITY_TYPES:
|
| 88 |
+
if entity_type not in entity_types:
|
| 89 |
+
continue
|
| 90 |
+
subject_type = SUBJECT_TYPE_FOR_ENTITY_TYPE[entity_type]
|
| 91 |
+
specs.append((subject_type, entity_type, entity_type == "mcp-server"))
|
| 92 |
+
return tuple(specs)
|
| 93 |
+
|
| 94 |
|
| 95 |
def mcp_shard(slug: str) -> str:
|
| 96 |
"""Return the shard segment for an MCP slug."""
|
|
|
|
| 114 |
return wiki / relpath if relpath is not None else None
|
| 115 |
|
| 116 |
|
| 117 |
+
def entity_index_link(subject_type: str, slug: str) -> str | None:
|
| 118 |
+
"""Return the extensionless wiki index target for a subject/slug pair."""
|
| 119 |
+
entity_type = ENTITY_TYPE_FOR_SUBJECT_TYPE.get(subject_type)
|
| 120 |
+
if entity_type is None:
|
| 121 |
+
return None
|
| 122 |
+
if entity_type == "mcp-server" and not slug:
|
| 123 |
+
return f"entities/{subject_type}/{mcp_shard(slug)}/"
|
| 124 |
+
relpath = entity_relpath(entity_type, slug)
|
| 125 |
+
return relpath.with_suffix("").as_posix() if relpath is not None else None
|
| 126 |
+
|
| 127 |
+
|
| 128 |
def entity_wikilink(entity_type: str, slug: str) -> str | None:
|
| 129 |
"""Return an Obsidian-style wikilink for an entity."""
|
| 130 |
relpath = entity_relpath(entity_type, slug)
|
src/ctx/core/graph/graph_packs.py
ADDED
|
@@ -0,0 +1,797 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Graph pack manifest contract.
|
| 2 |
+
|
| 3 |
+
Graph packs are the planned modular graph artifact unit:
|
| 4 |
+
|
| 5 |
+
``base-*`` packs hold a complete graph export, while ``overlay-*`` packs hold
|
| 6 |
+
incremental nodes, edges, and tombstones that can be merged over a base pack.
|
| 7 |
+
This module defines the pack manifest contract plus the small reader/writer
|
| 8 |
+
primitives used to stage overlay packs and periodic compacted base packs.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import hashlib
|
| 15 |
+
import json
|
| 16 |
+
import re
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from datetime import UTC, datetime
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
import sys
|
| 21 |
+
from typing import Any, Literal
|
| 22 |
+
|
| 23 |
+
import networkx as nx
|
| 24 |
+
|
| 25 |
+
from ctx.utils._fs_utils import atomic_write_text
|
| 26 |
+
|
| 27 |
+
GRAPH_PACK_MANIFEST = "graph-pack-manifest.json"
|
| 28 |
+
GRAPH_PACK_SCHEMA_VERSION = 1
|
| 29 |
+
PACK_TYPES = frozenset({"base", "overlay"})
|
| 30 |
+
_SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
|
| 31 |
+
|
| 32 |
+
PackType = Literal["base", "overlay"]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class GraphPackManifestError(ValueError):
|
| 36 |
+
"""Raised when a graph pack manifest is malformed."""
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@dataclass(frozen=True)
|
| 40 |
+
class GraphPackEntry:
|
| 41 |
+
"""A validated graph pack manifest and its directory."""
|
| 42 |
+
|
| 43 |
+
path: Path
|
| 44 |
+
manifest: "GraphPackManifest"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclass(frozen=True)
|
| 48 |
+
class GraphPackPromotion:
|
| 49 |
+
"""Result of promoting a staged graph pack set into the active location."""
|
| 50 |
+
|
| 51 |
+
active_packs_dir: Path
|
| 52 |
+
backup_packs_dir: Path | None
|
| 53 |
+
rollback_metadata_path: Path
|
| 54 |
+
promoted_pack_ids: list[str]
|
| 55 |
+
replaced_pack_ids: list[str]
|
| 56 |
+
replaced_validation_error: str | None = None
|
| 57 |
+
|
| 58 |
+
def to_mapping(self) -> dict[str, Any]:
|
| 59 |
+
"""Serialise promotion metadata for CLI output and rollback records."""
|
| 60 |
+
return {
|
| 61 |
+
"schema_version": GRAPH_PACK_SCHEMA_VERSION,
|
| 62 |
+
"operation": "graph-pack-promote",
|
| 63 |
+
"active_packs_dir": str(self.active_packs_dir),
|
| 64 |
+
"backup_packs_dir": str(self.backup_packs_dir) if self.backup_packs_dir else None,
|
| 65 |
+
"rollback_metadata_path": str(self.rollback_metadata_path),
|
| 66 |
+
"promoted_pack_ids": self.promoted_pack_ids,
|
| 67 |
+
"replaced_pack_ids": self.replaced_pack_ids,
|
| 68 |
+
"replaced_validation_error": self.replaced_validation_error,
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@dataclass(frozen=True)
|
| 73 |
+
class GraphPackManifest:
|
| 74 |
+
"""Validated manifest for one graph pack directory."""
|
| 75 |
+
|
| 76 |
+
pack_id: str
|
| 77 |
+
pack_type: PackType
|
| 78 |
+
base_export_id: str
|
| 79 |
+
parent_export_id: str | None
|
| 80 |
+
config_hash: str
|
| 81 |
+
model_id: str
|
| 82 |
+
node_count: int
|
| 83 |
+
edge_count: int
|
| 84 |
+
checksums: dict[str, str]
|
| 85 |
+
tombstone_count: int = 0
|
| 86 |
+
created_at: str | None = None
|
| 87 |
+
|
| 88 |
+
@classmethod
|
| 89 |
+
def from_mapping(cls, payload: dict[str, Any]) -> "GraphPackManifest":
|
| 90 |
+
"""Build and validate a manifest from JSON-decoded data."""
|
| 91 |
+
if payload.get("schema_version") != GRAPH_PACK_SCHEMA_VERSION:
|
| 92 |
+
raise GraphPackManifestError("graph pack manifest schema_version must be 1")
|
| 93 |
+
pack_type = payload.get("pack_type")
|
| 94 |
+
if pack_type not in PACK_TYPES:
|
| 95 |
+
raise GraphPackManifestError("graph pack manifest pack_type must be base or overlay")
|
| 96 |
+
manifest = cls(
|
| 97 |
+
pack_id=_required_str(payload, "pack_id"),
|
| 98 |
+
pack_type=pack_type,
|
| 99 |
+
base_export_id=_required_str(payload, "base_export_id"),
|
| 100 |
+
parent_export_id=_optional_str(payload, "parent_export_id"),
|
| 101 |
+
config_hash=_required_str(payload, "config_hash"),
|
| 102 |
+
model_id=_required_str(payload, "model_id"),
|
| 103 |
+
node_count=_nonnegative_int(payload, "node_count"),
|
| 104 |
+
edge_count=_nonnegative_int(payload, "edge_count"),
|
| 105 |
+
checksums=_checksums(payload.get("checksums")),
|
| 106 |
+
tombstone_count=_nonnegative_int(payload, "tombstone_count", default=0),
|
| 107 |
+
created_at=_optional_str(payload, "created_at"),
|
| 108 |
+
)
|
| 109 |
+
manifest.validate()
|
| 110 |
+
return manifest
|
| 111 |
+
|
| 112 |
+
def validate(self) -> None:
|
| 113 |
+
"""Validate cross-field invariants."""
|
| 114 |
+
_validate_relative_manifest_name(self.pack_id, "pack_id")
|
| 115 |
+
if self.pack_type == "base" and self.parent_export_id:
|
| 116 |
+
raise GraphPackManifestError("base graph packs must not set parent_export_id")
|
| 117 |
+
if self.pack_type == "overlay" and not self.parent_export_id:
|
| 118 |
+
raise GraphPackManifestError("overlay graph packs must set parent_export_id")
|
| 119 |
+
if not self.checksums:
|
| 120 |
+
raise GraphPackManifestError("graph pack manifest checksums must not be empty")
|
| 121 |
+
|
| 122 |
+
def to_mapping(self) -> dict[str, Any]:
|
| 123 |
+
"""Return deterministic JSON-serialisable manifest data."""
|
| 124 |
+
payload: dict[str, Any] = {
|
| 125 |
+
"schema_version": GRAPH_PACK_SCHEMA_VERSION,
|
| 126 |
+
"pack_id": self.pack_id,
|
| 127 |
+
"pack_type": self.pack_type,
|
| 128 |
+
"base_export_id": self.base_export_id,
|
| 129 |
+
"parent_export_id": self.parent_export_id,
|
| 130 |
+
"config_hash": self.config_hash,
|
| 131 |
+
"model_id": self.model_id,
|
| 132 |
+
"node_count": self.node_count,
|
| 133 |
+
"edge_count": self.edge_count,
|
| 134 |
+
"tombstone_count": self.tombstone_count,
|
| 135 |
+
"checksums": dict(sorted(self.checksums.items())),
|
| 136 |
+
}
|
| 137 |
+
if self.created_at is not None:
|
| 138 |
+
payload["created_at"] = self.created_at
|
| 139 |
+
return payload
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def build_pack_manifest(
|
| 143 |
+
*,
|
| 144 |
+
pack_dir: Path,
|
| 145 |
+
pack_id: str,
|
| 146 |
+
pack_type: PackType,
|
| 147 |
+
base_export_id: str,
|
| 148 |
+
parent_export_id: str | None,
|
| 149 |
+
config_hash: str,
|
| 150 |
+
model_id: str,
|
| 151 |
+
node_count: int,
|
| 152 |
+
edge_count: int,
|
| 153 |
+
artifact_paths: list[str],
|
| 154 |
+
tombstone_count: int = 0,
|
| 155 |
+
created_at: str | None = None,
|
| 156 |
+
) -> GraphPackManifest:
|
| 157 |
+
"""Create a manifest and compute SHA-256 checksums for pack artifacts."""
|
| 158 |
+
checksums = {
|
| 159 |
+
_normalise_artifact_name(name): sha256_file(pack_dir / name)
|
| 160 |
+
for name in artifact_paths
|
| 161 |
+
}
|
| 162 |
+
return GraphPackManifest(
|
| 163 |
+
pack_id=pack_id,
|
| 164 |
+
pack_type=pack_type,
|
| 165 |
+
base_export_id=base_export_id,
|
| 166 |
+
parent_export_id=parent_export_id,
|
| 167 |
+
config_hash=config_hash,
|
| 168 |
+
model_id=model_id,
|
| 169 |
+
node_count=node_count,
|
| 170 |
+
edge_count=edge_count,
|
| 171 |
+
checksums=checksums,
|
| 172 |
+
tombstone_count=tombstone_count,
|
| 173 |
+
created_at=created_at,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def read_pack_manifest(path: Path) -> GraphPackManifest:
|
| 178 |
+
"""Read and validate ``graph-pack-manifest.json``."""
|
| 179 |
+
try:
|
| 180 |
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
| 181 |
+
except json.JSONDecodeError as exc:
|
| 182 |
+
raise GraphPackManifestError(f"{path} is not valid JSON: {exc}") from exc
|
| 183 |
+
if not isinstance(payload, dict):
|
| 184 |
+
raise GraphPackManifestError(f"{path} did not contain a JSON object")
|
| 185 |
+
return GraphPackManifest.from_mapping(payload)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def write_pack_manifest(path: Path, manifest: GraphPackManifest) -> None:
|
| 189 |
+
"""Atomically write a graph pack manifest."""
|
| 190 |
+
manifest.validate()
|
| 191 |
+
atomic_write_text(
|
| 192 |
+
path,
|
| 193 |
+
json.dumps(manifest.to_mapping(), indent=2, sort_keys=True) + "\n",
|
| 194 |
+
encoding="utf-8",
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def write_overlay_pack(
|
| 199 |
+
*,
|
| 200 |
+
pack_dir: Path,
|
| 201 |
+
pack_id: str,
|
| 202 |
+
base_export_id: str,
|
| 203 |
+
parent_export_id: str,
|
| 204 |
+
config_hash: str,
|
| 205 |
+
model_id: str,
|
| 206 |
+
nodes: list[dict[str, Any]],
|
| 207 |
+
edges: list[dict[str, Any]],
|
| 208 |
+
tombstones: list[dict[str, Any]],
|
| 209 |
+
created_at: str | None = None,
|
| 210 |
+
) -> GraphPackManifest:
|
| 211 |
+
"""Write a first-class overlay pack with JSONL payload artifacts."""
|
| 212 |
+
_validate_relative_manifest_name(pack_id, "pack_id")
|
| 213 |
+
created_at = created_at or datetime.now(UTC).isoformat()
|
| 214 |
+
artifact_paths: list[str] = []
|
| 215 |
+
if nodes:
|
| 216 |
+
artifact_paths.append("nodes.jsonl")
|
| 217 |
+
if edges:
|
| 218 |
+
artifact_paths.append("edges.jsonl")
|
| 219 |
+
if tombstones:
|
| 220 |
+
artifact_paths.append("tombstones.jsonl")
|
| 221 |
+
if not artifact_paths:
|
| 222 |
+
raise GraphPackManifestError("empty overlay pack cannot be written")
|
| 223 |
+
|
| 224 |
+
manifest_path = pack_dir / GRAPH_PACK_MANIFEST
|
| 225 |
+
if manifest_path.exists():
|
| 226 |
+
raise GraphPackManifestError(f"graph overlay pack already exists: {pack_id}")
|
| 227 |
+
|
| 228 |
+
pack_dir.mkdir(parents=True, exist_ok=True)
|
| 229 |
+
for stale_name in ("nodes.jsonl", "edges.jsonl", "tombstones.jsonl"):
|
| 230 |
+
(pack_dir / stale_name).unlink(missing_ok=True)
|
| 231 |
+
if nodes:
|
| 232 |
+
_write_jsonl(pack_dir / "nodes.jsonl", nodes)
|
| 233 |
+
if edges:
|
| 234 |
+
_write_jsonl(pack_dir / "edges.jsonl", edges)
|
| 235 |
+
if tombstones:
|
| 236 |
+
_write_jsonl(pack_dir / "tombstones.jsonl", tombstones)
|
| 237 |
+
|
| 238 |
+
manifest = build_pack_manifest(
|
| 239 |
+
pack_dir=pack_dir,
|
| 240 |
+
pack_id=pack_id,
|
| 241 |
+
pack_type="overlay",
|
| 242 |
+
base_export_id=base_export_id,
|
| 243 |
+
parent_export_id=parent_export_id,
|
| 244 |
+
config_hash=config_hash,
|
| 245 |
+
model_id=model_id,
|
| 246 |
+
node_count=len(nodes),
|
| 247 |
+
edge_count=len(edges),
|
| 248 |
+
artifact_paths=artifact_paths,
|
| 249 |
+
tombstone_count=len(tombstones),
|
| 250 |
+
created_at=created_at,
|
| 251 |
+
)
|
| 252 |
+
write_pack_manifest(manifest_path, manifest)
|
| 253 |
+
return manifest
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def write_base_pack(
|
| 257 |
+
*,
|
| 258 |
+
pack_dir: Path,
|
| 259 |
+
pack_id: str,
|
| 260 |
+
base_export_id: str,
|
| 261 |
+
config_hash: str,
|
| 262 |
+
model_id: str,
|
| 263 |
+
graph: nx.Graph,
|
| 264 |
+
created_at: str | None = None,
|
| 265 |
+
) -> GraphPackManifest:
|
| 266 |
+
"""Write an immutable base graph pack from a NetworkX graph."""
|
| 267 |
+
_validate_relative_manifest_name(pack_id, "pack_id")
|
| 268 |
+
manifest_path = pack_dir / GRAPH_PACK_MANIFEST
|
| 269 |
+
if manifest_path.exists():
|
| 270 |
+
raise GraphPackManifestError(f"graph base pack already exists: {pack_id}")
|
| 271 |
+
|
| 272 |
+
pack_dir.mkdir(parents=True, exist_ok=True)
|
| 273 |
+
graph_copy = graph.copy()
|
| 274 |
+
graph_copy.graph["export_id"] = base_export_id
|
| 275 |
+
graph_data = _node_link_payload(graph_copy)
|
| 276 |
+
atomic_write_text(
|
| 277 |
+
pack_dir / "graph.json",
|
| 278 |
+
json.dumps(graph_data, indent=2, sort_keys=True, default=str) + "\n",
|
| 279 |
+
encoding="utf-8",
|
| 280 |
+
)
|
| 281 |
+
manifest = build_pack_manifest(
|
| 282 |
+
pack_dir=pack_dir,
|
| 283 |
+
pack_id=pack_id,
|
| 284 |
+
pack_type="base",
|
| 285 |
+
base_export_id=base_export_id,
|
| 286 |
+
parent_export_id=None,
|
| 287 |
+
config_hash=config_hash,
|
| 288 |
+
model_id=model_id,
|
| 289 |
+
node_count=graph_copy.number_of_nodes(),
|
| 290 |
+
edge_count=graph_copy.number_of_edges(),
|
| 291 |
+
artifact_paths=["graph.json"],
|
| 292 |
+
created_at=created_at,
|
| 293 |
+
)
|
| 294 |
+
write_pack_manifest(manifest_path, manifest)
|
| 295 |
+
return manifest
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def compact_graph_packs(
|
| 299 |
+
*,
|
| 300 |
+
packs_dir: Path,
|
| 301 |
+
compacted_pack_dir: Path,
|
| 302 |
+
base_export_id: str,
|
| 303 |
+
config_hash: str | None = None,
|
| 304 |
+
model_id: str | None = None,
|
| 305 |
+
created_at: str | None = None,
|
| 306 |
+
) -> GraphPackManifest:
|
| 307 |
+
"""Merge active base+overlay packs into one staged immutable base pack."""
|
| 308 |
+
entries = discover_pack_manifests(packs_dir)
|
| 309 |
+
if len(entries) <= 1:
|
| 310 |
+
raise GraphPackManifestError("graph pack compaction requires at least one overlay pack")
|
| 311 |
+
|
| 312 |
+
source_base = entries[0].manifest
|
| 313 |
+
graph = load_merged_pack_graph(packs_dir)
|
| 314 |
+
graph.graph["ctx_compacted_from_base_export_id"] = source_base.base_export_id
|
| 315 |
+
graph.graph["ctx_compacted_pack_ids"] = [
|
| 316 |
+
entry.manifest.pack_id for entry in entries
|
| 317 |
+
]
|
| 318 |
+
graph.graph["ctx_compacted_overlay_count"] = len(entries) - 1
|
| 319 |
+
return write_base_pack(
|
| 320 |
+
pack_dir=compacted_pack_dir,
|
| 321 |
+
pack_id=compacted_pack_dir.name,
|
| 322 |
+
base_export_id=base_export_id,
|
| 323 |
+
config_hash=config_hash or source_base.config_hash,
|
| 324 |
+
model_id=model_id or source_base.model_id,
|
| 325 |
+
graph=graph,
|
| 326 |
+
created_at=created_at,
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def promote_graph_pack_set(
|
| 331 |
+
*,
|
| 332 |
+
staged_packs_dir: Path,
|
| 333 |
+
active_packs_dir: Path,
|
| 334 |
+
backup_packs_dir: Path | None = None,
|
| 335 |
+
) -> GraphPackPromotion:
|
| 336 |
+
"""Promote a validated staged pack set into the active packs directory.
|
| 337 |
+
|
| 338 |
+
The swap is a same-filesystem directory rename: the previous active pack set
|
| 339 |
+
is moved to a rollback directory before the staged set is moved into place.
|
| 340 |
+
If the final move fails after the active directory was backed up, the old
|
| 341 |
+
active directory is restored before returning an error.
|
| 342 |
+
"""
|
| 343 |
+
if _paths_same(staged_packs_dir, active_packs_dir):
|
| 344 |
+
raise GraphPackManifestError("staged and active graph pack directories must differ")
|
| 345 |
+
|
| 346 |
+
staged_entries = discover_pack_manifests(staged_packs_dir)
|
| 347 |
+
if not staged_entries:
|
| 348 |
+
raise GraphPackManifestError("staged graph pack set does not contain a valid base pack")
|
| 349 |
+
# Force endpoint/tombstone validation before the active directory is touched.
|
| 350 |
+
load_merged_pack_graph(staged_packs_dir)
|
| 351 |
+
promoted_pack_ids = [entry.manifest.pack_id for entry in staged_entries]
|
| 352 |
+
|
| 353 |
+
replaced_pack_ids: list[str] = []
|
| 354 |
+
replaced_validation_error: str | None = None
|
| 355 |
+
active_exists = active_packs_dir.exists()
|
| 356 |
+
if active_exists:
|
| 357 |
+
if not active_packs_dir.is_dir():
|
| 358 |
+
raise GraphPackManifestError("active graph packs path exists but is not a directory")
|
| 359 |
+
try:
|
| 360 |
+
replaced_pack_ids = [
|
| 361 |
+
entry.manifest.pack_id for entry in discover_pack_manifests(active_packs_dir)
|
| 362 |
+
]
|
| 363 |
+
except GraphPackManifestError as exc:
|
| 364 |
+
replaced_validation_error = str(exc)
|
| 365 |
+
|
| 366 |
+
backup_dir = backup_packs_dir if active_exists else None
|
| 367 |
+
if backup_dir is None and active_exists:
|
| 368 |
+
backup_dir = _next_rollback_dir(active_packs_dir)
|
| 369 |
+
if backup_dir is not None:
|
| 370 |
+
if _paths_same(backup_dir, active_packs_dir) or _paths_same(backup_dir, staged_packs_dir):
|
| 371 |
+
raise GraphPackManifestError("backup graph packs directory must be distinct")
|
| 372 |
+
if backup_dir.exists():
|
| 373 |
+
raise GraphPackManifestError(f"backup graph packs directory already exists: {backup_dir}")
|
| 374 |
+
backup_dir.parent.mkdir(parents=True, exist_ok=True)
|
| 375 |
+
|
| 376 |
+
active_packs_dir.parent.mkdir(parents=True, exist_ok=True)
|
| 377 |
+
moved_active = False
|
| 378 |
+
try:
|
| 379 |
+
if active_exists and backup_dir is not None:
|
| 380 |
+
active_packs_dir.replace(backup_dir)
|
| 381 |
+
moved_active = True
|
| 382 |
+
staged_packs_dir.replace(active_packs_dir)
|
| 383 |
+
except OSError as exc:
|
| 384 |
+
if moved_active and backup_dir is not None and backup_dir.exists() and not active_packs_dir.exists():
|
| 385 |
+
backup_dir.replace(active_packs_dir)
|
| 386 |
+
raise GraphPackManifestError(f"failed to promote graph pack set: {exc}") from exc
|
| 387 |
+
|
| 388 |
+
metadata_path = active_packs_dir.with_name(f"{active_packs_dir.name}.rollback.json")
|
| 389 |
+
result = GraphPackPromotion(
|
| 390 |
+
active_packs_dir=active_packs_dir,
|
| 391 |
+
backup_packs_dir=backup_dir,
|
| 392 |
+
rollback_metadata_path=metadata_path,
|
| 393 |
+
promoted_pack_ids=promoted_pack_ids,
|
| 394 |
+
replaced_pack_ids=replaced_pack_ids,
|
| 395 |
+
replaced_validation_error=replaced_validation_error,
|
| 396 |
+
)
|
| 397 |
+
metadata = result.to_mapping()
|
| 398 |
+
metadata["created_at"] = datetime.now(UTC).isoformat()
|
| 399 |
+
atomic_write_text(
|
| 400 |
+
metadata_path,
|
| 401 |
+
json.dumps(metadata, indent=2, sort_keys=True) + "\n",
|
| 402 |
+
encoding="utf-8",
|
| 403 |
+
)
|
| 404 |
+
return result
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def main(argv: list[str] | None = None) -> int:
|
| 408 |
+
parser = argparse.ArgumentParser(
|
| 409 |
+
prog="python -m ctx.core.graph.graph_packs",
|
| 410 |
+
description="Manage ctx graph base and overlay packs.",
|
| 411 |
+
)
|
| 412 |
+
sub = parser.add_subparsers(dest="command", required=True)
|
| 413 |
+
compact = sub.add_parser(
|
| 414 |
+
"compact",
|
| 415 |
+
help="Merge active base+overlay packs into one staged base pack.",
|
| 416 |
+
)
|
| 417 |
+
compact.add_argument("--packs-dir", required=True, help="Active graph packs directory")
|
| 418 |
+
compact.add_argument(
|
| 419 |
+
"--staged-pack-dir",
|
| 420 |
+
required=True,
|
| 421 |
+
help="Destination directory for the compacted base pack",
|
| 422 |
+
)
|
| 423 |
+
compact.add_argument("--base-export-id", required=True, help="New compacted base export id")
|
| 424 |
+
compact.add_argument("--config-hash", help="Override config hash; defaults to source base")
|
| 425 |
+
compact.add_argument("--model-id", help="Override model id; defaults to source base")
|
| 426 |
+
compact.add_argument("--created-at", help="Optional created_at value for the new manifest")
|
| 427 |
+
compact.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
| 428 |
+
promote = sub.add_parser(
|
| 429 |
+
"promote",
|
| 430 |
+
help="Promote a staged graph pack set into the active packs directory.",
|
| 431 |
+
)
|
| 432 |
+
promote.add_argument(
|
| 433 |
+
"--staged-packs-dir",
|
| 434 |
+
required=True,
|
| 435 |
+
help="Validated staged graph packs root to promote",
|
| 436 |
+
)
|
| 437 |
+
promote.add_argument("--active-packs-dir", required=True, help="Active graph packs root")
|
| 438 |
+
promote.add_argument("--backup-packs-dir", help="Optional rollback directory for old active packs")
|
| 439 |
+
promote.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
| 440 |
+
args = parser.parse_args(argv)
|
| 441 |
+
|
| 442 |
+
if args.command == "compact":
|
| 443 |
+
try:
|
| 444 |
+
manifest = compact_graph_packs(
|
| 445 |
+
packs_dir=Path(args.packs_dir),
|
| 446 |
+
compacted_pack_dir=Path(args.staged_pack_dir),
|
| 447 |
+
base_export_id=args.base_export_id,
|
| 448 |
+
config_hash=args.config_hash,
|
| 449 |
+
model_id=args.model_id,
|
| 450 |
+
created_at=args.created_at,
|
| 451 |
+
)
|
| 452 |
+
except GraphPackManifestError as exc:
|
| 453 |
+
print(f"error: {exc}", file=sys.stderr)
|
| 454 |
+
return 1
|
| 455 |
+
payload = manifest.to_mapping()
|
| 456 |
+
payload["pack_dir"] = str(Path(args.staged_pack_dir))
|
| 457 |
+
if args.json:
|
| 458 |
+
print(json.dumps(payload, indent=2, sort_keys=True))
|
| 459 |
+
else:
|
| 460 |
+
print(
|
| 461 |
+
"compacted "
|
| 462 |
+
f"{manifest.pack_id}: {manifest.node_count} nodes, "
|
| 463 |
+
f"{manifest.edge_count} edges"
|
| 464 |
+
)
|
| 465 |
+
return 0
|
| 466 |
+
if args.command == "promote":
|
| 467 |
+
try:
|
| 468 |
+
result = promote_graph_pack_set(
|
| 469 |
+
staged_packs_dir=Path(args.staged_packs_dir),
|
| 470 |
+
active_packs_dir=Path(args.active_packs_dir),
|
| 471 |
+
backup_packs_dir=Path(args.backup_packs_dir) if args.backup_packs_dir else None,
|
| 472 |
+
)
|
| 473 |
+
except GraphPackManifestError as exc:
|
| 474 |
+
print(f"error: {exc}", file=sys.stderr)
|
| 475 |
+
return 1
|
| 476 |
+
payload = result.to_mapping()
|
| 477 |
+
if args.json:
|
| 478 |
+
print(json.dumps(payload, indent=2, sort_keys=True))
|
| 479 |
+
else:
|
| 480 |
+
backup = result.backup_packs_dir or "<none>"
|
| 481 |
+
print(f"promoted {', '.join(result.promoted_pack_ids)}; backup: {backup}")
|
| 482 |
+
return 0
|
| 483 |
+
return 1
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
def discover_pack_manifests(packs_dir: Path) -> list[GraphPackEntry]:
|
| 487 |
+
"""Discover and validate graph pack manifests under ``packs_dir``.
|
| 488 |
+
|
| 489 |
+
The returned order is always the active base pack first, followed by
|
| 490 |
+
overlay packs sorted by creation time, then pack id. This keeps immutable
|
| 491 |
+
overlay application deterministic while preserving "latest pack wins"
|
| 492 |
+
semantics for repeated updates to the same node or edge.
|
| 493 |
+
"""
|
| 494 |
+
if not packs_dir.is_dir():
|
| 495 |
+
return []
|
| 496 |
+
entries: list[GraphPackEntry] = []
|
| 497 |
+
for child in sorted(packs_dir.iterdir(), key=lambda item: item.name):
|
| 498 |
+
manifest_path = child / GRAPH_PACK_MANIFEST
|
| 499 |
+
if not child.is_dir() or not manifest_path.is_file():
|
| 500 |
+
continue
|
| 501 |
+
manifest = read_pack_manifest(manifest_path)
|
| 502 |
+
_verify_pack_checksums(child, manifest)
|
| 503 |
+
entries.append(GraphPackEntry(path=child, manifest=manifest))
|
| 504 |
+
|
| 505 |
+
base_entries = [entry for entry in entries if entry.manifest.pack_type == "base"]
|
| 506 |
+
overlay_entries = [entry for entry in entries if entry.manifest.pack_type == "overlay"]
|
| 507 |
+
if len(base_entries) > 1:
|
| 508 |
+
raise GraphPackManifestError("graph packs must contain at most one base pack")
|
| 509 |
+
if not base_entries and overlay_entries:
|
| 510 |
+
raise GraphPackManifestError("graph overlay packs require a base pack")
|
| 511 |
+
if not base_entries:
|
| 512 |
+
return []
|
| 513 |
+
|
| 514 |
+
base = base_entries[0]
|
| 515 |
+
for overlay in overlay_entries:
|
| 516 |
+
if overlay.manifest.parent_export_id != base.manifest.base_export_id:
|
| 517 |
+
raise GraphPackManifestError(
|
| 518 |
+
f"overlay {overlay.manifest.pack_id} parent_export_id "
|
| 519 |
+
f"{overlay.manifest.parent_export_id!r} does not match base export "
|
| 520 |
+
f"{base.manifest.base_export_id!r}"
|
| 521 |
+
)
|
| 522 |
+
if overlay.manifest.base_export_id != base.manifest.base_export_id:
|
| 523 |
+
raise GraphPackManifestError(
|
| 524 |
+
f"overlay {overlay.manifest.pack_id} base_export_id "
|
| 525 |
+
f"{overlay.manifest.base_export_id!r} does not match active base "
|
| 526 |
+
f"{base.manifest.base_export_id!r}"
|
| 527 |
+
)
|
| 528 |
+
return [base, *sorted(overlay_entries, key=_overlay_sort_key)]
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def _overlay_sort_key(entry: GraphPackEntry) -> tuple[str, str]:
|
| 532 |
+
return entry.manifest.created_at or "", entry.manifest.pack_id
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def load_merged_pack_graph(packs_dir: Path) -> nx.Graph:
|
| 536 |
+
"""Load one base graph pack plus active overlay packs into a NetworkX graph."""
|
| 537 |
+
entries = discover_pack_manifests(packs_dir)
|
| 538 |
+
if not entries:
|
| 539 |
+
return nx.Graph()
|
| 540 |
+
base = entries[0]
|
| 541 |
+
graph = _load_base_graph(base.path / "graph.json", base.manifest)
|
| 542 |
+
pack_ids = [base.manifest.pack_id]
|
| 543 |
+
for overlay in entries[1:]:
|
| 544 |
+
_apply_overlay_pack(graph, overlay)
|
| 545 |
+
pack_ids.append(overlay.manifest.pack_id)
|
| 546 |
+
graph.graph["ctx_pack_ids"] = pack_ids
|
| 547 |
+
graph.graph["ctx_pack_base_export_id"] = base.manifest.base_export_id
|
| 548 |
+
return graph
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def sha256_file(path: Path) -> str:
|
| 552 |
+
"""Return SHA-256 hex digest for a file."""
|
| 553 |
+
digest = hashlib.sha256()
|
| 554 |
+
with path.open("rb") as fh:
|
| 555 |
+
for chunk in iter(lambda: fh.read(1024 * 1024), b""):
|
| 556 |
+
digest.update(chunk)
|
| 557 |
+
return digest.hexdigest()
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def _verify_pack_checksums(pack_dir: Path, manifest: GraphPackManifest) -> None:
|
| 561 |
+
for name, expected in manifest.checksums.items():
|
| 562 |
+
path = pack_dir / name
|
| 563 |
+
if not path.is_file():
|
| 564 |
+
raise GraphPackManifestError(
|
| 565 |
+
f"graph pack {manifest.pack_id} checksum target missing: {name}"
|
| 566 |
+
)
|
| 567 |
+
actual = sha256_file(path)
|
| 568 |
+
if actual != expected:
|
| 569 |
+
raise GraphPackManifestError(
|
| 570 |
+
f"graph pack {manifest.pack_id} checksum mismatch for {name}"
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def _write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
|
| 575 |
+
atomic_write_text(
|
| 576 |
+
path,
|
| 577 |
+
"".join(json.dumps(row, sort_keys=True, separators=(",", ":")) + "\n" for row in rows),
|
| 578 |
+
encoding="utf-8",
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
def _node_link_payload(graph: nx.Graph) -> dict[str, Any]:
|
| 583 |
+
try:
|
| 584 |
+
payload = nx.node_link_data(graph, edges="edges")
|
| 585 |
+
except TypeError: # pragma: no cover - networkx < 3 compatibility.
|
| 586 |
+
payload = nx.node_link_data(graph)
|
| 587 |
+
payload["edges"] = payload.pop("links", payload.get("edges", []))
|
| 588 |
+
if not isinstance(payload, dict):
|
| 589 |
+
raise GraphPackManifestError("node-link export did not produce an object")
|
| 590 |
+
return payload
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def _load_base_graph(path: Path, manifest: GraphPackManifest) -> nx.Graph:
|
| 594 |
+
payload = _read_json_object(path)
|
| 595 |
+
graph = nx.Graph()
|
| 596 |
+
graph_meta = payload.get("graph")
|
| 597 |
+
if isinstance(graph_meta, dict):
|
| 598 |
+
graph.graph.update(graph_meta)
|
| 599 |
+
nodes = payload.get("nodes")
|
| 600 |
+
if not isinstance(nodes, list):
|
| 601 |
+
raise GraphPackManifestError(f"{path} missing nodes list")
|
| 602 |
+
for raw_node in nodes:
|
| 603 |
+
if not isinstance(raw_node, dict):
|
| 604 |
+
raise GraphPackManifestError(f"{path} contains non-object node")
|
| 605 |
+
node_id = raw_node.get("id")
|
| 606 |
+
if not isinstance(node_id, str) or not node_id:
|
| 607 |
+
raise GraphPackManifestError(f"{path} contains node without id")
|
| 608 |
+
graph.add_node(node_id, **{key: value for key, value in raw_node.items() if key != "id"})
|
| 609 |
+
raw_edges = payload.get("edges", payload.get("links", []))
|
| 610 |
+
if not isinstance(raw_edges, list):
|
| 611 |
+
raise GraphPackManifestError(f"{path} edges must be a list")
|
| 612 |
+
for raw_edge in raw_edges:
|
| 613 |
+
_add_edge(graph, raw_edge, context=str(path))
|
| 614 |
+
_validate_pack_count(
|
| 615 |
+
manifest.pack_id,
|
| 616 |
+
"node_count",
|
| 617 |
+
actual=graph.number_of_nodes(),
|
| 618 |
+
expected=manifest.node_count,
|
| 619 |
+
)
|
| 620 |
+
_validate_pack_count(
|
| 621 |
+
manifest.pack_id,
|
| 622 |
+
"edge_count",
|
| 623 |
+
actual=graph.number_of_edges(),
|
| 624 |
+
expected=manifest.edge_count,
|
| 625 |
+
)
|
| 626 |
+
return graph
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def _apply_overlay_pack(graph: nx.Graph, overlay: GraphPackEntry) -> None:
|
| 630 |
+
overlay_dir = overlay.path
|
| 631 |
+
manifest = overlay.manifest
|
| 632 |
+
tombstones = _read_jsonl_objects(overlay_dir / "tombstones.jsonl")
|
| 633 |
+
nodes = _read_jsonl_objects(overlay_dir / "nodes.jsonl")
|
| 634 |
+
edges = _read_jsonl_objects(overlay_dir / "edges.jsonl")
|
| 635 |
+
_validate_pack_count(
|
| 636 |
+
manifest.pack_id,
|
| 637 |
+
"node_count",
|
| 638 |
+
actual=len(nodes),
|
| 639 |
+
expected=manifest.node_count,
|
| 640 |
+
)
|
| 641 |
+
_validate_pack_count(
|
| 642 |
+
manifest.pack_id,
|
| 643 |
+
"edge_count",
|
| 644 |
+
actual=len(edges),
|
| 645 |
+
expected=manifest.edge_count,
|
| 646 |
+
)
|
| 647 |
+
_validate_pack_count(
|
| 648 |
+
manifest.pack_id,
|
| 649 |
+
"tombstone_count",
|
| 650 |
+
actual=len(tombstones),
|
| 651 |
+
expected=manifest.tombstone_count,
|
| 652 |
+
)
|
| 653 |
+
for tombstone in tombstones:
|
| 654 |
+
node_id = tombstone.get("node_id", tombstone.get("id"))
|
| 655 |
+
if not isinstance(node_id, str) or not node_id:
|
| 656 |
+
raise GraphPackManifestError(f"{overlay_dir} tombstone missing node_id")
|
| 657 |
+
if node_id in graph:
|
| 658 |
+
graph.remove_node(node_id)
|
| 659 |
+
for raw_node in nodes:
|
| 660 |
+
node_id = raw_node.get("id")
|
| 661 |
+
if not isinstance(node_id, str) or not node_id:
|
| 662 |
+
raise GraphPackManifestError(f"{overlay_dir} node overlay missing id")
|
| 663 |
+
graph.add_node(node_id, **{key: value for key, value in raw_node.items() if key != "id"})
|
| 664 |
+
for raw_edge in edges:
|
| 665 |
+
_add_edge(graph, raw_edge, context=str(overlay_dir))
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
def _validate_pack_count(
|
| 669 |
+
pack_id: str,
|
| 670 |
+
field_name: str,
|
| 671 |
+
*,
|
| 672 |
+
actual: int,
|
| 673 |
+
expected: int,
|
| 674 |
+
) -> None:
|
| 675 |
+
if actual != expected:
|
| 676 |
+
raise GraphPackManifestError(
|
| 677 |
+
f"graph pack {pack_id} {field_name} mismatch: expected {expected}, got {actual}"
|
| 678 |
+
)
|
| 679 |
+
|
| 680 |
+
|
| 681 |
+
def _add_edge(graph: nx.Graph, raw_edge: object, *, context: str) -> None:
|
| 682 |
+
if not isinstance(raw_edge, dict):
|
| 683 |
+
raise GraphPackManifestError(f"{context} contains non-object edge")
|
| 684 |
+
source = raw_edge.get("source")
|
| 685 |
+
target = raw_edge.get("target")
|
| 686 |
+
if not isinstance(source, str) or not isinstance(target, str) or not source or not target:
|
| 687 |
+
raise GraphPackManifestError(f"{context} contains edge without source/target")
|
| 688 |
+
if source not in graph or target not in graph:
|
| 689 |
+
raise GraphPackManifestError(f"{context} contains edge with unknown endpoint")
|
| 690 |
+
graph.add_edge(
|
| 691 |
+
source,
|
| 692 |
+
target,
|
| 693 |
+
**{key: value for key, value in raw_edge.items() if key not in {"source", "target"}},
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
|
| 697 |
+
def _read_json_object(path: Path) -> dict[str, Any]:
|
| 698 |
+
try:
|
| 699 |
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
| 700 |
+
except json.JSONDecodeError as exc:
|
| 701 |
+
raise GraphPackManifestError(f"{path} is not valid JSON: {exc}") from exc
|
| 702 |
+
if not isinstance(payload, dict):
|
| 703 |
+
raise GraphPackManifestError(f"{path} did not contain a JSON object")
|
| 704 |
+
return payload
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
def _read_jsonl_objects(path: Path) -> list[dict[str, Any]]:
|
| 708 |
+
if not path.is_file():
|
| 709 |
+
return []
|
| 710 |
+
rows: list[dict[str, Any]] = []
|
| 711 |
+
for lineno, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
|
| 712 |
+
if not line.strip():
|
| 713 |
+
continue
|
| 714 |
+
try:
|
| 715 |
+
payload = json.loads(line)
|
| 716 |
+
except json.JSONDecodeError as exc:
|
| 717 |
+
raise GraphPackManifestError(f"{path} line {lineno} is not valid JSON: {exc}") from exc
|
| 718 |
+
if not isinstance(payload, dict):
|
| 719 |
+
raise GraphPackManifestError(f"{path} line {lineno} did not contain a JSON object")
|
| 720 |
+
rows.append(payload)
|
| 721 |
+
return rows
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
def _required_str(payload: dict[str, Any], key: str) -> str:
|
| 725 |
+
value = payload.get(key)
|
| 726 |
+
if not isinstance(value, str) or not value.strip():
|
| 727 |
+
raise GraphPackManifestError(f"graph pack manifest {key} must be a non-empty string")
|
| 728 |
+
return value
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
def _optional_str(payload: dict[str, Any], key: str) -> str | None:
|
| 732 |
+
value = payload.get(key)
|
| 733 |
+
if value is None:
|
| 734 |
+
return None
|
| 735 |
+
if not isinstance(value, str) or not value.strip():
|
| 736 |
+
raise GraphPackManifestError(f"graph pack manifest {key} must be a string or null")
|
| 737 |
+
return value
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
def _nonnegative_int(payload: dict[str, Any], key: str, *, default: int | None = None) -> int:
|
| 741 |
+
value = payload.get(key, default)
|
| 742 |
+
if not isinstance(value, int) or value < 0:
|
| 743 |
+
raise GraphPackManifestError(f"graph pack manifest {key} must be a non-negative integer")
|
| 744 |
+
return value
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
def _checksums(value: object) -> dict[str, str]:
|
| 748 |
+
if not isinstance(value, dict):
|
| 749 |
+
raise GraphPackManifestError("graph pack manifest checksums must be an object")
|
| 750 |
+
result: dict[str, str] = {}
|
| 751 |
+
for raw_name, raw_digest in value.items():
|
| 752 |
+
if not isinstance(raw_name, str):
|
| 753 |
+
raise GraphPackManifestError("graph pack manifest checksum names must be strings")
|
| 754 |
+
name = _normalise_artifact_name(raw_name)
|
| 755 |
+
if not isinstance(raw_digest, str) or not _SHA256_RE.match(raw_digest):
|
| 756 |
+
raise GraphPackManifestError(
|
| 757 |
+
f"graph pack manifest checksum for {name} must be a SHA-256 hex digest"
|
| 758 |
+
)
|
| 759 |
+
result[name] = raw_digest
|
| 760 |
+
return result
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
def _normalise_artifact_name(name: str) -> str:
|
| 764 |
+
normalised = name.replace("\\", "/").strip()
|
| 765 |
+
_validate_relative_manifest_name(normalised, "artifact name")
|
| 766 |
+
return normalised
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
def _validate_relative_manifest_name(value: str, label: str) -> None:
|
| 770 |
+
path = Path(value)
|
| 771 |
+
if path.is_absolute() or value.startswith(("/", "\\")):
|
| 772 |
+
raise GraphPackManifestError(f"graph pack manifest {label} must be relative")
|
| 773 |
+
parts = value.replace("\\", "/").split("/")
|
| 774 |
+
if any(part in {"", ".", ".."} for part in parts):
|
| 775 |
+
raise GraphPackManifestError(f"graph pack manifest {label} is unsafe")
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
def _paths_same(left: Path, right: Path) -> bool:
|
| 779 |
+
try:
|
| 780 |
+
return left.resolve() == right.resolve()
|
| 781 |
+
except OSError:
|
| 782 |
+
return left.absolute() == right.absolute()
|
| 783 |
+
|
| 784 |
+
|
| 785 |
+
def _next_rollback_dir(active_packs_dir: Path) -> Path:
|
| 786 |
+
first = active_packs_dir.with_name(f"{active_packs_dir.name}.rollback")
|
| 787 |
+
if not first.exists():
|
| 788 |
+
return first
|
| 789 |
+
for index in range(2, 1000):
|
| 790 |
+
candidate = active_packs_dir.with_name(f"{active_packs_dir.name}.rollback-{index}")
|
| 791 |
+
if not candidate.exists():
|
| 792 |
+
return candidate
|
| 793 |
+
raise GraphPackManifestError("could not allocate graph packs rollback directory")
|
| 794 |
+
|
| 795 |
+
|
| 796 |
+
if __name__ == "__main__": # pragma: no cover - exercised through main() tests.
|
| 797 |
+
raise SystemExit(main())
|
src/ctx/core/graph/graph_store.py
ADDED
|
@@ -0,0 +1,561 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SQLite operational store for merged ctx graph reads.
|
| 2 |
+
|
| 3 |
+
The JSON/pack graph remains the source artifact. This module materializes a
|
| 4 |
+
small local SQLite store for fast node search and neighborhood lookups.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import sqlite3
|
| 13 |
+
from collections.abc import Iterator, Mapping
|
| 14 |
+
from contextlib import contextmanager
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
import networkx as nx
|
| 19 |
+
|
| 20 |
+
SCHEMA_VERSION = 1
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def build_graph_store(
|
| 24 |
+
db_path: Path,
|
| 25 |
+
graph: nx.Graph,
|
| 26 |
+
*,
|
| 27 |
+
extra_metadata: Mapping[str, str] | None = None,
|
| 28 |
+
) -> None:
|
| 29 |
+
"""Materialize *graph* into a SQLite store at *db_path*."""
|
| 30 |
+
db_path.parent.mkdir(parents=True, exist_ok=True)
|
| 31 |
+
with _connect(db_path) as conn:
|
| 32 |
+
conn.executescript(
|
| 33 |
+
"""
|
| 34 |
+
DROP TABLE IF EXISTS metadata;
|
| 35 |
+
DROP TABLE IF EXISTS nodes;
|
| 36 |
+
DROP TABLE IF EXISTS edges;
|
| 37 |
+
CREATE TABLE metadata (
|
| 38 |
+
key TEXT PRIMARY KEY,
|
| 39 |
+
value TEXT NOT NULL
|
| 40 |
+
);
|
| 41 |
+
CREATE TABLE nodes (
|
| 42 |
+
id TEXT PRIMARY KEY,
|
| 43 |
+
type TEXT,
|
| 44 |
+
label TEXT,
|
| 45 |
+
title TEXT,
|
| 46 |
+
tags_json TEXT NOT NULL,
|
| 47 |
+
attrs_json TEXT NOT NULL,
|
| 48 |
+
search_text TEXT NOT NULL
|
| 49 |
+
);
|
| 50 |
+
CREATE TABLE edges (
|
| 51 |
+
source TEXT NOT NULL,
|
| 52 |
+
target TEXT NOT NULL,
|
| 53 |
+
weight REAL NOT NULL DEFAULT 0.0,
|
| 54 |
+
attrs_json TEXT NOT NULL,
|
| 55 |
+
PRIMARY KEY (source, target)
|
| 56 |
+
);
|
| 57 |
+
CREATE INDEX idx_nodes_type ON nodes(type);
|
| 58 |
+
CREATE INDEX idx_nodes_search_text ON nodes(search_text);
|
| 59 |
+
CREATE INDEX idx_edges_source ON edges(source);
|
| 60 |
+
CREATE INDEX idx_edges_target ON edges(target);
|
| 61 |
+
"""
|
| 62 |
+
)
|
| 63 |
+
conn.executemany(
|
| 64 |
+
"INSERT INTO metadata(key, value) VALUES(:key, :value)",
|
| 65 |
+
_metadata_rows(graph, extra_metadata=extra_metadata),
|
| 66 |
+
)
|
| 67 |
+
conn.executemany(
|
| 68 |
+
"""
|
| 69 |
+
INSERT INTO nodes(id, type, label, title, tags_json, attrs_json, search_text)
|
| 70 |
+
VALUES(:id, :type, :label, :title, :tags_json, :attrs_json, :search_text)
|
| 71 |
+
""",
|
| 72 |
+
(_node_row(node_id, attrs) for node_id, attrs in graph.nodes(data=True)),
|
| 73 |
+
)
|
| 74 |
+
conn.executemany(
|
| 75 |
+
"""
|
| 76 |
+
INSERT INTO edges(source, target, weight, attrs_json)
|
| 77 |
+
VALUES(:source, :target, :weight, :attrs_json)
|
| 78 |
+
""",
|
| 79 |
+
(_edge_row(source, target, attrs) for source, target, attrs in graph.edges(data=True)),
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def build_graph_store_from_graph_dir(
|
| 84 |
+
graph_dir: Path,
|
| 85 |
+
db_path: Path,
|
| 86 |
+
*,
|
| 87 |
+
apply_runtime_filter: bool = True,
|
| 88 |
+
) -> dict[str, int]:
|
| 89 |
+
"""Build a SQLite store from a graphify-out directory.
|
| 90 |
+
|
| 91 |
+
``resolve_graph.load_graph`` is the single source of truth for graph
|
| 92 |
+
loading. It prefers active graph packs beside ``graph.json`` and falls
|
| 93 |
+
back to the legacy monolithic ``graph.json`` only when packs are absent.
|
| 94 |
+
"""
|
| 95 |
+
from ctx.core.graph.resolve_graph import load_graph # noqa: PLC0415
|
| 96 |
+
|
| 97 |
+
source_metadata = _graph_dir_source_metadata(graph_dir)
|
| 98 |
+
if source_metadata.get("ctx_graph_store_source") == "missing":
|
| 99 |
+
raise ValueError("source graph is missing")
|
| 100 |
+
|
| 101 |
+
graph = load_graph(
|
| 102 |
+
graph_dir / "graph.json",
|
| 103 |
+
apply_runtime_filter=apply_runtime_filter,
|
| 104 |
+
)
|
| 105 |
+
build_graph_store(
|
| 106 |
+
db_path,
|
| 107 |
+
graph,
|
| 108 |
+
extra_metadata=source_metadata,
|
| 109 |
+
)
|
| 110 |
+
return graph_store_stats(db_path)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def ensure_graph_store(
|
| 114 |
+
graph_dir: Path,
|
| 115 |
+
db_path: Path,
|
| 116 |
+
*,
|
| 117 |
+
apply_runtime_filter: bool = True,
|
| 118 |
+
) -> dict[str, bool | int]:
|
| 119 |
+
"""Reuse a fresh SQLite store or rebuild it from the graph directory."""
|
| 120 |
+
if graph_store_is_fresh(db_path, graph_dir):
|
| 121 |
+
return {"rebuilt": False, **graph_store_stats(db_path)}
|
| 122 |
+
stats = build_graph_store_from_graph_dir(
|
| 123 |
+
graph_dir,
|
| 124 |
+
db_path,
|
| 125 |
+
apply_runtime_filter=apply_runtime_filter,
|
| 126 |
+
)
|
| 127 |
+
return {"rebuilt": True, **stats}
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def graph_store_stats(db_path: Path) -> dict[str, int]:
|
| 131 |
+
"""Return node/edge counts for an existing graph store."""
|
| 132 |
+
with _connect(db_path) as conn:
|
| 133 |
+
return {
|
| 134 |
+
"nodes": int(conn.execute("SELECT COUNT(*) FROM nodes").fetchone()[0]),
|
| 135 |
+
"edges": int(conn.execute("SELECT COUNT(*) FROM edges").fetchone()[0]),
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def graph_store_metadata(db_path: Path) -> dict[str, str]:
|
| 140 |
+
"""Return metadata recorded when the graph store was materialized."""
|
| 141 |
+
with _connect(db_path) as conn:
|
| 142 |
+
rows = conn.execute("SELECT key, value FROM metadata ORDER BY key").fetchall()
|
| 143 |
+
return {row["key"]: row["value"] for row in rows}
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def graph_store_is_fresh(db_path: Path, graph_dir: Path) -> bool:
|
| 147 |
+
"""Return whether *db_path* still reflects *graph_dir* sources."""
|
| 148 |
+
if not db_path.is_file():
|
| 149 |
+
return False
|
| 150 |
+
try:
|
| 151 |
+
stored = graph_store_metadata(db_path)
|
| 152 |
+
current = _graph_dir_source_metadata(graph_dir)
|
| 153 |
+
except (OSError, sqlite3.DatabaseError, ValueError):
|
| 154 |
+
return False
|
| 155 |
+
if current.get("ctx_graph_store_source") == "missing":
|
| 156 |
+
return False
|
| 157 |
+
return all(stored.get(key) == value for key, value in current.items())
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def validate_graph_store(db_path: Path, graph_dir: Path) -> dict[str, object]:
|
| 161 |
+
"""Validate a SQLite store against its recorded source graph directory."""
|
| 162 |
+
errors: list[str] = []
|
| 163 |
+
if not db_path.is_file():
|
| 164 |
+
return {
|
| 165 |
+
"ok": False,
|
| 166 |
+
"fresh": False,
|
| 167 |
+
"nodes": 0,
|
| 168 |
+
"edges": 0,
|
| 169 |
+
"errors": ["graph store is missing"],
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
try:
|
| 173 |
+
stats = graph_store_stats(db_path)
|
| 174 |
+
metadata = graph_store_metadata(db_path)
|
| 175 |
+
except sqlite3.DatabaseError as exc:
|
| 176 |
+
return {
|
| 177 |
+
"ok": False,
|
| 178 |
+
"fresh": False,
|
| 179 |
+
"nodes": 0,
|
| 180 |
+
"edges": 0,
|
| 181 |
+
"errors": [f"graph store is unreadable: {exc}"],
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
if metadata.get("schema_version") != str(SCHEMA_VERSION):
|
| 185 |
+
errors.append("schema_version is not supported")
|
| 186 |
+
_validate_count_metadata(metadata, stats, "node_count", "nodes", errors)
|
| 187 |
+
_validate_count_metadata(metadata, stats, "edge_count", "edges", errors)
|
| 188 |
+
source_missing = _source_graph_is_missing(graph_dir)
|
| 189 |
+
fresh = graph_store_is_fresh(db_path, graph_dir)
|
| 190 |
+
if source_missing:
|
| 191 |
+
errors.append("source graph is missing")
|
| 192 |
+
elif not fresh:
|
| 193 |
+
errors.append("source fingerprint is stale")
|
| 194 |
+
return {
|
| 195 |
+
"ok": not errors,
|
| 196 |
+
"fresh": fresh,
|
| 197 |
+
"nodes": stats["nodes"],
|
| 198 |
+
"edges": stats["edges"],
|
| 199 |
+
"errors": errors,
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def search_nodes(db_path: Path, query: str, *, limit: int = 20) -> list[dict[str, Any]]:
|
| 204 |
+
"""Search nodes by id, label, title, type, or tags."""
|
| 205 |
+
term = query.strip().lower()
|
| 206 |
+
if not term or limit <= 0:
|
| 207 |
+
return []
|
| 208 |
+
like = f"%{term}%"
|
| 209 |
+
prefix = f"{term}%"
|
| 210 |
+
with _connect(db_path) as conn:
|
| 211 |
+
rows = conn.execute(
|
| 212 |
+
"""
|
| 213 |
+
SELECT id, type, label, title, tags_json
|
| 214 |
+
FROM nodes
|
| 215 |
+
WHERE search_text LIKE ?
|
| 216 |
+
ORDER BY
|
| 217 |
+
CASE
|
| 218 |
+
WHEN lower(id) = ? OR lower(label) = ? THEN 0
|
| 219 |
+
WHEN lower(id) LIKE ? OR lower(label) LIKE ? THEN 1
|
| 220 |
+
WHEN lower(title) LIKE ? THEN 2
|
| 221 |
+
ELSE 3
|
| 222 |
+
END,
|
| 223 |
+
id
|
| 224 |
+
LIMIT ?
|
| 225 |
+
""",
|
| 226 |
+
(like, term, term, prefix, prefix, like, limit),
|
| 227 |
+
).fetchall()
|
| 228 |
+
return [_node_result(row) for row in rows]
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def load_neighborhood(db_path: Path, node_id: str, *, limit: int = 50) -> dict[str, list[dict[str, Any]]]:
|
| 232 |
+
"""Return a 1-hop neighborhood centered on *node_id*."""
|
| 233 |
+
if limit <= 0:
|
| 234 |
+
limit = 1
|
| 235 |
+
with _connect(db_path) as conn:
|
| 236 |
+
center = conn.execute(
|
| 237 |
+
"SELECT id, type, label, title, tags_json FROM nodes WHERE id = ?",
|
| 238 |
+
(node_id,),
|
| 239 |
+
).fetchone()
|
| 240 |
+
if center is None:
|
| 241 |
+
return {"nodes": [], "edges": []}
|
| 242 |
+
edge_rows = conn.execute(
|
| 243 |
+
"""
|
| 244 |
+
SELECT source, target, weight, attrs_json
|
| 245 |
+
FROM edges
|
| 246 |
+
WHERE source = ? OR target = ?
|
| 247 |
+
ORDER BY weight DESC, source, target
|
| 248 |
+
LIMIT ?
|
| 249 |
+
""",
|
| 250 |
+
(node_id, node_id, limit),
|
| 251 |
+
).fetchall()
|
| 252 |
+
neighbor_ids = {
|
| 253 |
+
row["target"] if row["source"] == node_id else row["source"]
|
| 254 |
+
for row in edge_rows
|
| 255 |
+
}
|
| 256 |
+
nodes = [_node_result(center)]
|
| 257 |
+
if neighbor_ids:
|
| 258 |
+
placeholders = ",".join("?" for _ in neighbor_ids)
|
| 259 |
+
nodes.extend(
|
| 260 |
+
_node_result(row)
|
| 261 |
+
for row in conn.execute(
|
| 262 |
+
f"SELECT id, type, label, title, tags_json FROM nodes WHERE id IN ({placeholders})",
|
| 263 |
+
tuple(sorted(neighbor_ids)),
|
| 264 |
+
).fetchall()
|
| 265 |
+
)
|
| 266 |
+
edges = [_edge_result(row, center_id=node_id) for row in edge_rows]
|
| 267 |
+
return {"nodes": nodes, "edges": edges}
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def main(argv: list[str] | None = None) -> int:
|
| 271 |
+
"""CLI for materializing a graph directory into the SQLite store."""
|
| 272 |
+
parser = argparse.ArgumentParser(
|
| 273 |
+
prog="python -m ctx.core.graph.graph_store",
|
| 274 |
+
description="Build and inspect the ctx SQLite graph operational store.",
|
| 275 |
+
)
|
| 276 |
+
sub = parser.add_subparsers(dest="command", required=True)
|
| 277 |
+
build = sub.add_parser(
|
| 278 |
+
"build",
|
| 279 |
+
help="Build a SQLite store from graphify-out packs or graph.json.",
|
| 280 |
+
)
|
| 281 |
+
build.add_argument("--graph-dir", required=True, help="Path to graphify-out")
|
| 282 |
+
build.add_argument("--db", required=True, help="Destination SQLite database")
|
| 283 |
+
build.add_argument(
|
| 284 |
+
"--no-runtime-filter",
|
| 285 |
+
action="store_true",
|
| 286 |
+
help="Preserve all stored edges instead of applying runtime graph filters.",
|
| 287 |
+
)
|
| 288 |
+
validate = sub.add_parser(
|
| 289 |
+
"validate",
|
| 290 |
+
help="Validate a SQLite store against graphify-out sources.",
|
| 291 |
+
)
|
| 292 |
+
validate.add_argument("--graph-dir", required=True, help="Path to graphify-out")
|
| 293 |
+
validate.add_argument("--db", required=True, help="SQLite database to validate")
|
| 294 |
+
search = sub.add_parser(
|
| 295 |
+
"search",
|
| 296 |
+
help="Search a built SQLite graph store.",
|
| 297 |
+
)
|
| 298 |
+
search.add_argument("--db", required=True, help="SQLite database to query")
|
| 299 |
+
search.add_argument("--graph-dir", help="Require the store to be fresh for this graphify-out")
|
| 300 |
+
search.add_argument("--query", required=True, help="Search text")
|
| 301 |
+
search.add_argument("--limit", type=int, default=20, help="Maximum rows to return")
|
| 302 |
+
neighborhood = sub.add_parser(
|
| 303 |
+
"neighborhood",
|
| 304 |
+
help="Read a 1-hop neighborhood from a built SQLite graph store.",
|
| 305 |
+
)
|
| 306 |
+
neighborhood.add_argument("--db", required=True, help="SQLite database to query")
|
| 307 |
+
neighborhood.add_argument("--graph-dir", help="Require the store to be fresh for this graphify-out")
|
| 308 |
+
neighborhood.add_argument("--node-id", required=True, help="Center node id")
|
| 309 |
+
neighborhood.add_argument("--limit", type=int, default=50, help="Maximum edges to return")
|
| 310 |
+
|
| 311 |
+
args = parser.parse_args(argv)
|
| 312 |
+
if args.command == "build":
|
| 313 |
+
try:
|
| 314 |
+
stats = build_graph_store_from_graph_dir(
|
| 315 |
+
Path(args.graph_dir),
|
| 316 |
+
Path(args.db),
|
| 317 |
+
apply_runtime_filter=not args.no_runtime_filter,
|
| 318 |
+
)
|
| 319 |
+
except ValueError as exc:
|
| 320 |
+
print(json.dumps({"error": str(exc), "ok": False}, sort_keys=True))
|
| 321 |
+
return 1
|
| 322 |
+
print(json.dumps(stats, sort_keys=True))
|
| 323 |
+
return 0
|
| 324 |
+
if args.command == "validate":
|
| 325 |
+
report = validate_graph_store(Path(args.db), Path(args.graph_dir))
|
| 326 |
+
print(json.dumps(report, sort_keys=True))
|
| 327 |
+
return 0 if report["ok"] else 1
|
| 328 |
+
if args.command == "search":
|
| 329 |
+
db_path = Path(args.db)
|
| 330 |
+
if args.graph_dir:
|
| 331 |
+
report = validate_graph_store(db_path, Path(args.graph_dir))
|
| 332 |
+
if not report["ok"]:
|
| 333 |
+
print(json.dumps(report, sort_keys=True))
|
| 334 |
+
return 1
|
| 335 |
+
rows = search_nodes(db_path, args.query, limit=args.limit)
|
| 336 |
+
print(json.dumps({"results": rows}, sort_keys=True))
|
| 337 |
+
return 0
|
| 338 |
+
if args.command == "neighborhood":
|
| 339 |
+
db_path = Path(args.db)
|
| 340 |
+
if args.graph_dir:
|
| 341 |
+
report = validate_graph_store(db_path, Path(args.graph_dir))
|
| 342 |
+
if not report["ok"]:
|
| 343 |
+
print(json.dumps(report, sort_keys=True))
|
| 344 |
+
return 1
|
| 345 |
+
neighborhood_payload = load_neighborhood(db_path, args.node_id, limit=args.limit)
|
| 346 |
+
print(json.dumps(neighborhood_payload, sort_keys=True))
|
| 347 |
+
return 0
|
| 348 |
+
parser.error(f"unknown command: {args.command}")
|
| 349 |
+
return 2
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
@contextmanager
|
| 353 |
+
def _connect(db_path: Path) -> Iterator[sqlite3.Connection]:
|
| 354 |
+
conn = sqlite3.connect(db_path)
|
| 355 |
+
conn.row_factory = sqlite3.Row
|
| 356 |
+
conn.execute("PRAGMA journal_mode=WAL")
|
| 357 |
+
conn.execute("PRAGMA foreign_keys=ON")
|
| 358 |
+
try:
|
| 359 |
+
yield conn
|
| 360 |
+
conn.commit()
|
| 361 |
+
except Exception:
|
| 362 |
+
conn.rollback()
|
| 363 |
+
raise
|
| 364 |
+
finally:
|
| 365 |
+
conn.close()
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def _metadata_rows(
|
| 369 |
+
graph: nx.Graph,
|
| 370 |
+
*,
|
| 371 |
+
extra_metadata: Mapping[str, str] | None = None,
|
| 372 |
+
) -> list[dict[str, str]]:
|
| 373 |
+
metadata = {
|
| 374 |
+
"schema_version": str(SCHEMA_VERSION),
|
| 375 |
+
"node_count": str(graph.number_of_nodes()),
|
| 376 |
+
"edge_count": str(graph.number_of_edges()),
|
| 377 |
+
}
|
| 378 |
+
for key, value in sorted(graph.graph.items()):
|
| 379 |
+
if value is None:
|
| 380 |
+
continue
|
| 381 |
+
metadata[str(key)] = _metadata_value(value)
|
| 382 |
+
if extra_metadata:
|
| 383 |
+
metadata.update(extra_metadata)
|
| 384 |
+
return [
|
| 385 |
+
{"key": key, "value": value}
|
| 386 |
+
for key, value in sorted(metadata.items())
|
| 387 |
+
]
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def _graph_dir_source_metadata(graph_dir: Path) -> dict[str, str]:
|
| 391 |
+
from ctx.core.graph.graph_packs import ( # noqa: PLC0415
|
| 392 |
+
discover_pack_manifests,
|
| 393 |
+
sha256_file,
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
overlay_metadata = _entity_overlay_source_metadata(graph_dir)
|
| 397 |
+
packs_dir = graph_dir / "packs"
|
| 398 |
+
if packs_dir.is_dir():
|
| 399 |
+
entries = discover_pack_manifests(packs_dir)
|
| 400 |
+
if entries:
|
| 401 |
+
pack_ids = [entry.manifest.pack_id for entry in entries]
|
| 402 |
+
pack_payload = [entry.manifest.to_mapping() for entry in entries]
|
| 403 |
+
return {
|
| 404 |
+
"ctx_graph_store_source": "packs",
|
| 405 |
+
"ctx_graph_store_fingerprint": _fingerprint_payload(pack_payload),
|
| 406 |
+
"ctx_graph_store_pack_ids": json.dumps(pack_ids, sort_keys=True),
|
| 407 |
+
**overlay_metadata,
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
graph_json = graph_dir / "graph.json"
|
| 411 |
+
if graph_json.is_file():
|
| 412 |
+
return {
|
| 413 |
+
"ctx_graph_store_source": "graph.json",
|
| 414 |
+
"ctx_graph_store_fingerprint": sha256_file(graph_json),
|
| 415 |
+
**overlay_metadata,
|
| 416 |
+
}
|
| 417 |
+
return {
|
| 418 |
+
"ctx_graph_store_source": "missing",
|
| 419 |
+
"ctx_graph_store_fingerprint": "",
|
| 420 |
+
**overlay_metadata,
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def _entity_overlay_source_metadata(graph_dir: Path) -> dict[str, str]:
|
| 425 |
+
from ctx.core.graph.graph_packs import sha256_file # noqa: PLC0415
|
| 426 |
+
|
| 427 |
+
overlay_path = graph_dir / "entity-overlays.jsonl"
|
| 428 |
+
if not overlay_path.is_file():
|
| 429 |
+
return {
|
| 430 |
+
"ctx_graph_store_entity_overlay": "absent",
|
| 431 |
+
"ctx_graph_store_entity_overlay_fingerprint": "",
|
| 432 |
+
}
|
| 433 |
+
return {
|
| 434 |
+
"ctx_graph_store_entity_overlay": "present",
|
| 435 |
+
"ctx_graph_store_entity_overlay_fingerprint": sha256_file(overlay_path),
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def _source_graph_is_missing(graph_dir: Path) -> bool:
|
| 440 |
+
try:
|
| 441 |
+
return _graph_dir_source_metadata(graph_dir).get("ctx_graph_store_source") == "missing"
|
| 442 |
+
except (OSError, ValueError):
|
| 443 |
+
return False
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def _fingerprint_payload(payload: object) -> str:
|
| 447 |
+
encoded = json.dumps(
|
| 448 |
+
_jsonable(payload),
|
| 449 |
+
sort_keys=True,
|
| 450 |
+
separators=(",", ":"),
|
| 451 |
+
default=str,
|
| 452 |
+
).encode("utf-8")
|
| 453 |
+
return hashlib.sha256(encoded).hexdigest()
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def _metadata_value(value: object) -> str:
|
| 457 |
+
if isinstance(value, str):
|
| 458 |
+
return value
|
| 459 |
+
if isinstance(value, bool):
|
| 460 |
+
return "true" if value else "false"
|
| 461 |
+
if isinstance(value, int | float):
|
| 462 |
+
return str(value)
|
| 463 |
+
return json.dumps(_jsonable(value), sort_keys=True, default=str)
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def _validate_count_metadata(
|
| 467 |
+
metadata: Mapping[str, str],
|
| 468 |
+
stats: Mapping[str, int],
|
| 469 |
+
metadata_key: str,
|
| 470 |
+
stats_key: str,
|
| 471 |
+
errors: list[str],
|
| 472 |
+
) -> None:
|
| 473 |
+
raw_value = metadata.get(metadata_key)
|
| 474 |
+
if raw_value is None:
|
| 475 |
+
errors.append(f"metadata {metadata_key} is missing")
|
| 476 |
+
return
|
| 477 |
+
try:
|
| 478 |
+
value = int(raw_value)
|
| 479 |
+
except ValueError:
|
| 480 |
+
errors.append(f"metadata {metadata_key} is not an integer")
|
| 481 |
+
return
|
| 482 |
+
actual = stats[stats_key]
|
| 483 |
+
if value != actual:
|
| 484 |
+
errors.append(f"metadata {metadata_key} {value} != actual {actual}")
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def _node_row(node_id: str, attrs: dict[str, Any]) -> dict[str, Any]:
|
| 488 |
+
label = _optional_str(attrs.get("label")) or node_id.split(":", 1)[-1]
|
| 489 |
+
title = _optional_str(attrs.get("title")) or label
|
| 490 |
+
entity_type = _optional_str(attrs.get("type"))
|
| 491 |
+
tags = _string_list(attrs.get("tags"))
|
| 492 |
+
search_text = " ".join([node_id, label, title, entity_type or "", *tags]).lower()
|
| 493 |
+
return {
|
| 494 |
+
"id": node_id,
|
| 495 |
+
"type": entity_type,
|
| 496 |
+
"label": label,
|
| 497 |
+
"title": title,
|
| 498 |
+
"tags_json": json.dumps(tags, sort_keys=True),
|
| 499 |
+
"attrs_json": json.dumps(_jsonable(attrs), sort_keys=True),
|
| 500 |
+
"search_text": search_text,
|
| 501 |
+
}
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def _edge_row(source: str, target: str, attrs: dict[str, Any]) -> dict[str, Any]:
|
| 505 |
+
weight = attrs.get("final_weight", attrs.get("weight", 0.0))
|
| 506 |
+
try:
|
| 507 |
+
numeric_weight = float(weight)
|
| 508 |
+
except (TypeError, ValueError):
|
| 509 |
+
numeric_weight = 0.0
|
| 510 |
+
return {
|
| 511 |
+
"source": source,
|
| 512 |
+
"target": target,
|
| 513 |
+
"weight": numeric_weight,
|
| 514 |
+
"attrs_json": json.dumps(_jsonable(attrs), sort_keys=True),
|
| 515 |
+
}
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def _node_result(row: sqlite3.Row) -> dict[str, Any]:
|
| 519 |
+
return {
|
| 520 |
+
"id": row["id"],
|
| 521 |
+
"type": row["type"],
|
| 522 |
+
"label": row["label"],
|
| 523 |
+
"title": row["title"],
|
| 524 |
+
"tags": json.loads(row["tags_json"]),
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def _edge_result(row: sqlite3.Row, *, center_id: str) -> dict[str, Any]:
|
| 529 |
+
source = row["source"]
|
| 530 |
+
target = row["target"]
|
| 531 |
+
if target == center_id:
|
| 532 |
+
source, target = target, source
|
| 533 |
+
attrs = json.loads(row["attrs_json"])
|
| 534 |
+
return {
|
| 535 |
+
"source": source,
|
| 536 |
+
"target": target,
|
| 537 |
+
"weight": row["weight"],
|
| 538 |
+
"attrs": attrs,
|
| 539 |
+
}
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def _optional_str(value: object) -> str | None:
|
| 543 |
+
return value if isinstance(value, str) and value else None
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def _string_list(value: object) -> list[str]:
|
| 547 |
+
if not isinstance(value, list):
|
| 548 |
+
return []
|
| 549 |
+
return [item for item in value if isinstance(item, str)]
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
def _jsonable(value: object) -> object:
|
| 553 |
+
try:
|
| 554 |
+
json.dumps(value)
|
| 555 |
+
except (TypeError, ValueError):
|
| 556 |
+
return str(value)
|
| 557 |
+
return value
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
if __name__ == "__main__": # pragma: no cover
|
| 561 |
+
raise SystemExit(main())
|
src/ctx/core/graph/incremental_attach.py
CHANGED
|
@@ -9,6 +9,7 @@ import hashlib
|
|
| 9 |
import json
|
| 10 |
from math import ceil
|
| 11 |
from pathlib import Path
|
|
|
|
| 12 |
import sys
|
| 13 |
from typing import Any, Iterable
|
| 14 |
|
|
@@ -17,7 +18,12 @@ import numpy as np
|
|
| 17 |
|
| 18 |
from ctx.core.graph.edge_scoring import type_affinity_score
|
| 19 |
from ctx.core.graph.entity_overlays import upsert_overlay_record
|
| 20 |
-
from ctx.core.graph.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
_PERCENTILES = (50, 60, 75, 90, 95)
|
| 23 |
_DEFAULT_MIN_SEMANTIC_SCORE = 0.80
|
|
@@ -124,6 +130,55 @@ def render_calibration_markdown(summary: AttachCalibrationSummary) -> str:
|
|
| 124 |
return "\n".join(lines) + "\n"
|
| 125 |
|
| 126 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
def attach_entity(
|
| 128 |
*,
|
| 129 |
index_dir: Path,
|
|
@@ -141,6 +196,12 @@ def attach_entity(
|
|
| 141 |
dry_run: bool = False,
|
| 142 |
embedding_backend: str = "sentence-transformers",
|
| 143 |
embedding_model: str | None = None,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
) -> dict[str, Any]:
|
| 145 |
"""Attach one new/updated entity to an existing semantic vector index."""
|
| 146 |
meta = _read_index_meta(index_dir)
|
|
@@ -162,8 +223,23 @@ def attach_entity(
|
|
| 162 |
"vector index metadata mismatch or index files are unreadable "
|
| 163 |
f"for model {resolved_model_id!r}"
|
| 164 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
|
| 166 |
-
neighbors =
|
| 167 |
vector,
|
| 168 |
top_k=top_k,
|
| 169 |
min_score=min_score,
|
|
@@ -190,7 +266,37 @@ def attach_entity(
|
|
| 190 |
],
|
| 191 |
)
|
| 192 |
status = "dry-run" if dry_run else upsert_overlay_record(overlay_path, record)
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
|
| 196 |
def main(argv: list[str] | None = None) -> int:
|
|
@@ -199,11 +305,41 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 199 |
description="Incremental graph attach utilities.",
|
| 200 |
)
|
| 201 |
sub = parser.add_subparsers(dest="command", required=True)
|
| 202 |
-
calibrate = sub.add_parser(
|
| 203 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
calibrate.add_argument("--json", action="store_true", help="Emit JSON instead of Markdown")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
attach = sub.add_parser("attach", help="Attach one entity through the semantic vector index")
|
| 206 |
attach.add_argument("--index-dir", required=True, help="Path to a persisted vector-index directory")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
attach.add_argument("--overlay", required=True, help="Path to graphify-out/entity-overlays.jsonl")
|
| 208 |
attach.add_argument("--node-id", required=True, help="Graph node id, e.g. skill:my-skill")
|
| 209 |
attach.add_argument("--type", required=True, dest="entity_type", help="Entity type")
|
|
@@ -221,19 +357,54 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 221 |
attach.add_argument("--top-k", type=int, default=20)
|
| 222 |
attach.add_argument("--min-score", type=float)
|
| 223 |
attach.add_argument("--min-final-weight", type=float, default=_DEFAULT_MIN_FINAL_WEIGHT)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
attach.add_argument("--dry-run", action="store_true", help="Print the overlay record without writing")
|
| 225 |
attach.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
| 226 |
args = parser.parse_args(argv)
|
| 227 |
if args.command == "calibrate":
|
| 228 |
from ctx.core.graph.resolve_graph import load_graph # noqa: PLC0415
|
| 229 |
|
| 230 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
summary = calibrate_attach_defaults(graph)
|
| 232 |
if args.json:
|
| 233 |
print(json.dumps(asdict(summary), indent=2))
|
| 234 |
else:
|
| 235 |
print(render_calibration_markdown(summary), end="")
|
| 236 |
return 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
if args.command == "attach":
|
| 238 |
try:
|
| 239 |
result = attach_entity(
|
|
@@ -256,6 +427,16 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 256 |
dry_run=args.dry_run,
|
| 257 |
embedding_backend=args.embedding_backend,
|
| 258 |
embedding_model=args.embedding_model,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
)
|
| 260 |
except Exception as exc: # noqa: BLE001 - CLI reports concise errors.
|
| 261 |
print(f"error: {exc}", file=sys.stderr)
|
|
@@ -331,6 +512,49 @@ def _resolve_attach_vector(
|
|
| 331 |
return embedder.embed([text]), resolved_model_id, _content_hash(text)
|
| 332 |
|
| 333 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
def _parse_vector_json(vector_json: str) -> np.ndarray:
|
| 335 |
try:
|
| 336 |
payload = json.loads(vector_json)
|
|
|
|
| 9 |
import json
|
| 10 |
from math import ceil
|
| 11 |
from pathlib import Path
|
| 12 |
+
import re
|
| 13 |
import sys
|
| 14 |
from typing import Any, Iterable
|
| 15 |
|
|
|
|
| 18 |
|
| 19 |
from ctx.core.graph.edge_scoring import type_affinity_score
|
| 20 |
from ctx.core.graph.entity_overlays import upsert_overlay_record
|
| 21 |
+
from ctx.core.graph.graph_packs import GRAPH_PACK_MANIFEST, write_overlay_pack
|
| 22 |
+
from ctx.core.graph.vector_index import (
|
| 23 |
+
MergedVectorIndex,
|
| 24 |
+
load_vector_index,
|
| 25 |
+
upsert_numpy_flat_index_entry,
|
| 26 |
+
)
|
| 27 |
|
| 28 |
_PERCENTILES = (50, 60, 75, 90, 95)
|
| 29 |
_DEFAULT_MIN_SEMANTIC_SCORE = 0.80
|
|
|
|
| 130 |
return "\n".join(lines) + "\n"
|
| 131 |
|
| 132 |
|
| 133 |
+
def validate_vector_index_set(
|
| 134 |
+
*,
|
| 135 |
+
index_dir: Path,
|
| 136 |
+
delta_index_dirs: list[Path] | None = None,
|
| 137 |
+
) -> dict[str, Any]:
|
| 138 |
+
"""Validate a base vector index plus optional local delta indexes."""
|
| 139 |
+
base_meta = _read_index_meta(index_dir)
|
| 140 |
+
model_id = str(base_meta["model_id"])
|
| 141 |
+
base_index = load_vector_index(
|
| 142 |
+
index_dir,
|
| 143 |
+
expected_model_id=model_id,
|
| 144 |
+
expected_content_fingerprint=str(base_meta["content_fingerprint"]),
|
| 145 |
+
)
|
| 146 |
+
if base_index is None:
|
| 147 |
+
raise ValueError(f"base vector index is unreadable or stale at {index_dir}")
|
| 148 |
+
indexes = [base_index]
|
| 149 |
+
index_reports: list[dict[str, Any]] = [_index_report(index_dir, base_index, "base")]
|
| 150 |
+
for delta_index_dir in delta_index_dirs or []:
|
| 151 |
+
delta_meta = _read_index_meta(delta_index_dir)
|
| 152 |
+
delta_index = load_vector_index(
|
| 153 |
+
delta_index_dir,
|
| 154 |
+
expected_model_id=model_id,
|
| 155 |
+
expected_content_fingerprint=str(delta_meta["content_fingerprint"]),
|
| 156 |
+
)
|
| 157 |
+
if delta_index is None:
|
| 158 |
+
raise ValueError(f"delta vector index is unreadable or stale at {delta_index_dir}")
|
| 159 |
+
indexes.append(delta_index)
|
| 160 |
+
index_reports.append(_index_report(delta_index_dir, delta_index, "delta"))
|
| 161 |
+
MergedVectorIndex(indexes)
|
| 162 |
+
return {
|
| 163 |
+
"ok": True,
|
| 164 |
+
"model_id": model_id,
|
| 165 |
+
"dim": base_index.meta.dim,
|
| 166 |
+
"index_count": len(indexes),
|
| 167 |
+
"node_count": sum(index.meta.node_count for index in indexes),
|
| 168 |
+
"indexes": index_reports,
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _index_report(index_dir: Path, index: Any, role: str) -> dict[str, Any]:
|
| 173 |
+
return {
|
| 174 |
+
"role": role,
|
| 175 |
+
"path": str(index_dir),
|
| 176 |
+
"index_kind": index.meta.index_kind,
|
| 177 |
+
"node_count": index.meta.node_count,
|
| 178 |
+
"content_fingerprint": index.meta.content_fingerprint,
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
|
| 182 |
def attach_entity(
|
| 183 |
*,
|
| 184 |
index_dir: Path,
|
|
|
|
| 196 |
dry_run: bool = False,
|
| 197 |
embedding_backend: str = "sentence-transformers",
|
| 198 |
embedding_model: str | None = None,
|
| 199 |
+
pack_root: Path | None = None,
|
| 200 |
+
base_export_id: str | None = None,
|
| 201 |
+
parent_export_id: str | None = None,
|
| 202 |
+
config_hash: str | None = None,
|
| 203 |
+
delta_index_dirs: list[Path] | None = None,
|
| 204 |
+
delta_index_write_dir: Path | None = None,
|
| 205 |
) -> dict[str, Any]:
|
| 206 |
"""Attach one new/updated entity to an existing semantic vector index."""
|
| 207 |
meta = _read_index_meta(index_dir)
|
|
|
|
| 223 |
"vector index metadata mismatch or index files are unreadable "
|
| 224 |
f"for model {resolved_model_id!r}"
|
| 225 |
)
|
| 226 |
+
indexes = [index]
|
| 227 |
+
for delta_index_dir in delta_index_dirs or []:
|
| 228 |
+
delta_meta = _read_index_meta(delta_index_dir)
|
| 229 |
+
delta_index = load_vector_index(
|
| 230 |
+
delta_index_dir,
|
| 231 |
+
expected_model_id=resolved_model_id,
|
| 232 |
+
expected_content_fingerprint=str(delta_meta["content_fingerprint"]),
|
| 233 |
+
)
|
| 234 |
+
if delta_index is None:
|
| 235 |
+
raise ValueError(
|
| 236 |
+
"delta vector index metadata mismatch or index files are unreadable "
|
| 237 |
+
f"at {delta_index_dir}"
|
| 238 |
+
)
|
| 239 |
+
indexes.append(delta_index)
|
| 240 |
+
query_index = MergedVectorIndex(indexes) if len(indexes) > 1 else index
|
| 241 |
|
| 242 |
+
neighbors = query_index.query(
|
| 243 |
vector,
|
| 244 |
top_k=top_k,
|
| 245 |
min_score=min_score,
|
|
|
|
| 266 |
],
|
| 267 |
)
|
| 268 |
status = "dry-run" if dry_run else upsert_overlay_record(overlay_path, record)
|
| 269 |
+
result = {"status": status, "record": record}
|
| 270 |
+
if pack_root is not None and not dry_run:
|
| 271 |
+
result["overlay_pack"] = _write_attach_pack(
|
| 272 |
+
pack_root=pack_root,
|
| 273 |
+
record=record,
|
| 274 |
+
base_export_id=base_export_id,
|
| 275 |
+
parent_export_id=parent_export_id,
|
| 276 |
+
config_hash=config_hash,
|
| 277 |
+
)
|
| 278 |
+
if delta_index_write_dir is not None and not dry_run:
|
| 279 |
+
try:
|
| 280 |
+
delta_index = upsert_numpy_flat_index_entry(
|
| 281 |
+
delta_index_write_dir,
|
| 282 |
+
model_id=resolved_model_id,
|
| 283 |
+
node_id=node_id,
|
| 284 |
+
content_hash=content_hash,
|
| 285 |
+
vector=vector,
|
| 286 |
+
)
|
| 287 |
+
result["delta_index"] = {
|
| 288 |
+
"status": "upserted",
|
| 289 |
+
"path": str(delta_index_write_dir),
|
| 290 |
+
"node_count": delta_index.meta.node_count,
|
| 291 |
+
"content_fingerprint": delta_index.meta.content_fingerprint,
|
| 292 |
+
}
|
| 293 |
+
except Exception as exc: # noqa: BLE001 - delta index is derived data.
|
| 294 |
+
result["delta_index"] = {
|
| 295 |
+
"status": "skipped",
|
| 296 |
+
"path": str(delta_index_write_dir),
|
| 297 |
+
"error": str(exc),
|
| 298 |
+
}
|
| 299 |
+
return result
|
| 300 |
|
| 301 |
|
| 302 |
def main(argv: list[str] | None = None) -> int:
|
|
|
|
| 305 |
description="Incremental graph attach utilities.",
|
| 306 |
)
|
| 307 |
sub = parser.add_subparsers(dest="command", required=True)
|
| 308 |
+
calibrate = sub.add_parser(
|
| 309 |
+
"calibrate",
|
| 310 |
+
help="Calibrate attach defaults from graph.json or graph packs",
|
| 311 |
+
)
|
| 312 |
+
calibrate_source = calibrate.add_mutually_exclusive_group(required=True)
|
| 313 |
+
calibrate_source.add_argument("--graph", help="Path to graphify-out/graph.json")
|
| 314 |
+
calibrate_source.add_argument(
|
| 315 |
+
"--graph-dir",
|
| 316 |
+
help="Path to graphify-out; supports active graph packs without graph.json",
|
| 317 |
+
)
|
| 318 |
calibrate.add_argument("--json", action="store_true", help="Emit JSON instead of Markdown")
|
| 319 |
+
validate_indexes = sub.add_parser(
|
| 320 |
+
"validate-indexes",
|
| 321 |
+
help="Validate a base vector index plus optional local delta indexes",
|
| 322 |
+
)
|
| 323 |
+
validate_indexes.add_argument("--index-dir", required=True, help="Path to base vector-index")
|
| 324 |
+
validate_indexes.add_argument(
|
| 325 |
+
"--delta-index-dir",
|
| 326 |
+
action="append",
|
| 327 |
+
default=[],
|
| 328 |
+
help="Additional local vector-index directory; repeatable",
|
| 329 |
+
)
|
| 330 |
+
validate_indexes.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
| 331 |
attach = sub.add_parser("attach", help="Attach one entity through the semantic vector index")
|
| 332 |
attach.add_argument("--index-dir", required=True, help="Path to a persisted vector-index directory")
|
| 333 |
+
attach.add_argument(
|
| 334 |
+
"--delta-index-dir",
|
| 335 |
+
action="append",
|
| 336 |
+
default=[],
|
| 337 |
+
help="Additional local vector-index directory; repeatable for base+delta queries",
|
| 338 |
+
)
|
| 339 |
+
attach.add_argument(
|
| 340 |
+
"--delta-index-write-dir",
|
| 341 |
+
help="Optional local vector-index directory to upsert this entity after attach",
|
| 342 |
+
)
|
| 343 |
attach.add_argument("--overlay", required=True, help="Path to graphify-out/entity-overlays.jsonl")
|
| 344 |
attach.add_argument("--node-id", required=True, help="Graph node id, e.g. skill:my-skill")
|
| 345 |
attach.add_argument("--type", required=True, dest="entity_type", help="Entity type")
|
|
|
|
| 357 |
attach.add_argument("--top-k", type=int, default=20)
|
| 358 |
attach.add_argument("--min-score", type=float)
|
| 359 |
attach.add_argument("--min-final-weight", type=float, default=_DEFAULT_MIN_FINAL_WEIGHT)
|
| 360 |
+
attach.add_argument(
|
| 361 |
+
"--pack-root",
|
| 362 |
+
help="Optional graph packs directory; writes an immutable overlay pack for this attach",
|
| 363 |
+
)
|
| 364 |
+
attach.add_argument("--base-export-id", help="Base graph export id for --pack-root")
|
| 365 |
+
attach.add_argument(
|
| 366 |
+
"--parent-export-id",
|
| 367 |
+
help="Parent graph export id for --pack-root; defaults to --base-export-id",
|
| 368 |
+
)
|
| 369 |
+
attach.add_argument("--config-hash", help="Graph config hash for --pack-root")
|
| 370 |
attach.add_argument("--dry-run", action="store_true", help="Print the overlay record without writing")
|
| 371 |
attach.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
| 372 |
args = parser.parse_args(argv)
|
| 373 |
if args.command == "calibrate":
|
| 374 |
from ctx.core.graph.resolve_graph import load_graph # noqa: PLC0415
|
| 375 |
|
| 376 |
+
graph_path = (
|
| 377 |
+
Path(args.graph)
|
| 378 |
+
if args.graph
|
| 379 |
+
else Path(args.graph_dir) / "graph.json"
|
| 380 |
+
)
|
| 381 |
+
graph = load_graph(graph_path)
|
| 382 |
summary = calibrate_attach_defaults(graph)
|
| 383 |
if args.json:
|
| 384 |
print(json.dumps(asdict(summary), indent=2))
|
| 385 |
else:
|
| 386 |
print(render_calibration_markdown(summary), end="")
|
| 387 |
return 0
|
| 388 |
+
if args.command == "validate-indexes":
|
| 389 |
+
try:
|
| 390 |
+
result = validate_vector_index_set(
|
| 391 |
+
index_dir=Path(args.index_dir),
|
| 392 |
+
delta_index_dirs=[Path(path) for path in args.delta_index_dir or []],
|
| 393 |
+
)
|
| 394 |
+
except Exception as exc: # noqa: BLE001 - CLI reports concise validation errors.
|
| 395 |
+
if args.json:
|
| 396 |
+
print(json.dumps({"ok": False, "error": str(exc)}, indent=2, sort_keys=True))
|
| 397 |
+
else:
|
| 398 |
+
print(f"error: {exc}", file=sys.stderr)
|
| 399 |
+
return 1
|
| 400 |
+
if args.json:
|
| 401 |
+
print(json.dumps(result, indent=2, sort_keys=True))
|
| 402 |
+
else:
|
| 403 |
+
print(
|
| 404 |
+
"validated vector indexes: "
|
| 405 |
+
f"{result['index_count']} indexes / {result['node_count']} nodes"
|
| 406 |
+
)
|
| 407 |
+
return 0
|
| 408 |
if args.command == "attach":
|
| 409 |
try:
|
| 410 |
result = attach_entity(
|
|
|
|
| 427 |
dry_run=args.dry_run,
|
| 428 |
embedding_backend=args.embedding_backend,
|
| 429 |
embedding_model=args.embedding_model,
|
| 430 |
+
pack_root=Path(args.pack_root) if args.pack_root else None,
|
| 431 |
+
base_export_id=args.base_export_id,
|
| 432 |
+
parent_export_id=args.parent_export_id,
|
| 433 |
+
config_hash=args.config_hash,
|
| 434 |
+
delta_index_dirs=[Path(path) for path in args.delta_index_dir or []],
|
| 435 |
+
delta_index_write_dir=(
|
| 436 |
+
Path(args.delta_index_write_dir)
|
| 437 |
+
if args.delta_index_write_dir
|
| 438 |
+
else None
|
| 439 |
+
),
|
| 440 |
)
|
| 441 |
except Exception as exc: # noqa: BLE001 - CLI reports concise errors.
|
| 442 |
print(f"error: {exc}", file=sys.stderr)
|
|
|
|
| 512 |
return embedder.embed([text]), resolved_model_id, _content_hash(text)
|
| 513 |
|
| 514 |
|
| 515 |
+
def _write_attach_pack(
|
| 516 |
+
*,
|
| 517 |
+
pack_root: Path,
|
| 518 |
+
record: dict[str, Any],
|
| 519 |
+
base_export_id: str | None,
|
| 520 |
+
parent_export_id: str | None,
|
| 521 |
+
config_hash: str | None,
|
| 522 |
+
) -> dict[str, str]:
|
| 523 |
+
if not base_export_id:
|
| 524 |
+
raise ValueError("--base-export-id is required when --pack-root is used")
|
| 525 |
+
if not config_hash:
|
| 526 |
+
raise ValueError("--config-hash is required when --pack-root is used")
|
| 527 |
+
pack_id = _attach_pack_id(record)
|
| 528 |
+
pack_dir = pack_root / pack_id
|
| 529 |
+
manifest_path = pack_dir / GRAPH_PACK_MANIFEST
|
| 530 |
+
if manifest_path.exists():
|
| 531 |
+
return {"status": "unchanged", "pack_id": pack_id, "path": str(pack_dir)}
|
| 532 |
+
|
| 533 |
+
created_at = record.get("created_at")
|
| 534 |
+
write_overlay_pack(
|
| 535 |
+
pack_dir=pack_dir,
|
| 536 |
+
pack_id=pack_id,
|
| 537 |
+
base_export_id=base_export_id,
|
| 538 |
+
parent_export_id=parent_export_id or base_export_id,
|
| 539 |
+
config_hash=config_hash,
|
| 540 |
+
model_id=str(record["model_id"]),
|
| 541 |
+
nodes=list(record.get("nodes") or []),
|
| 542 |
+
edges=list(record.get("edges") or []),
|
| 543 |
+
tombstones=[{"node_id": str(record["node_id"]), "source": "incremental-attach"}],
|
| 544 |
+
created_at=str(created_at) if created_at else None,
|
| 545 |
+
)
|
| 546 |
+
return {"status": "inserted", "pack_id": pack_id, "path": str(pack_dir)}
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def _attach_pack_id(record: dict[str, Any]) -> str:
|
| 550 |
+
node_id = str(record.get("node_id") or "entity")
|
| 551 |
+
content_hash = str(record.get("content_hash") or _content_hash(json.dumps(record, sort_keys=True)))
|
| 552 |
+
safe_node = re.sub(r"[^A-Za-z0-9._-]+", "-", node_id).strip(".-_").lower()
|
| 553 |
+
if not safe_node:
|
| 554 |
+
safe_node = "entity"
|
| 555 |
+
return f"overlay-{safe_node}-{content_hash[:16]}"
|
| 556 |
+
|
| 557 |
+
|
| 558 |
def _parse_vector_json(vector_json: str) -> np.ndarray:
|
| 559 |
try:
|
| 560 |
payload = json.loads(vector_json)
|
src/ctx/core/graph/incremental_shadow.py
CHANGED
|
@@ -144,7 +144,12 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 144 |
description="Shadow-validate incremental ANN graph attach.",
|
| 145 |
)
|
| 146 |
parser.add_argument("--index-dir", required=True)
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
parser.add_argument("--sample-size", type=int, default=100)
|
| 149 |
parser.add_argument("--seed", type=int, default=42)
|
| 150 |
parser.add_argument("--node", action="append", default=[])
|
|
@@ -156,7 +161,10 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 156 |
parser.add_argument("--no-fail", action="store_true")
|
| 157 |
args = parser.parse_args(argv)
|
| 158 |
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
| 160 |
report = run_shadow_validation(
|
| 161 |
index_dir=Path(args.index_dir),
|
| 162 |
graph=graph,
|
|
|
|
| 144 |
description="Shadow-validate incremental ANN graph attach.",
|
| 145 |
)
|
| 146 |
parser.add_argument("--index-dir", required=True)
|
| 147 |
+
graph_source = parser.add_mutually_exclusive_group()
|
| 148 |
+
graph_source.add_argument("--graph", help="Optional graphify-out/graph.json baseline")
|
| 149 |
+
graph_source.add_argument(
|
| 150 |
+
"--graph-dir",
|
| 151 |
+
help="Optional graphify-out directory; supports active packs without graph.json",
|
| 152 |
+
)
|
| 153 |
parser.add_argument("--sample-size", type=int, default=100)
|
| 154 |
parser.add_argument("--seed", type=int, default=42)
|
| 155 |
parser.add_argument("--node", action="append", default=[])
|
|
|
|
| 161 |
parser.add_argument("--no-fail", action="store_true")
|
| 162 |
args = parser.parse_args(argv)
|
| 163 |
|
| 164 |
+
graph_path = Path(args.graph) if args.graph else None
|
| 165 |
+
if args.graph_dir:
|
| 166 |
+
graph_path = Path(args.graph_dir) / "graph.json"
|
| 167 |
+
graph = load_graph(graph_path) if graph_path is not None else None
|
| 168 |
report = run_shadow_validation(
|
| 169 |
index_dir=Path(args.index_dir),
|
| 170 |
graph=graph,
|
src/ctx/core/graph/resolve_graph.py
CHANGED
|
@@ -275,20 +275,60 @@ def _authoritative_overlay_nodes(payload: Mapping[str, Any]) -> set[str]:
|
|
| 275 |
return node_ids
|
| 276 |
|
| 277 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
def load_graph(
|
| 279 |
path: Path | None = None,
|
| 280 |
*,
|
| 281 |
apply_runtime_filter: bool = True,
|
| 282 |
) -> nx.Graph:
|
| 283 |
-
"""Load the knowledge graph from graph.json.
|
| 284 |
|
| 285 |
Returns an empty graph on any parse or schema error rather than crashing.
|
| 286 |
Callers that *require* a populated graph (e.g. CLI main) should check
|
| 287 |
``G.number_of_nodes() == 0`` and handle accordingly.
|
| 288 |
"""
|
| 289 |
graph_path = path if path is not None else GRAPH_PATH
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
if not graph_path.exists():
|
| 291 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
return nx.Graph()
|
| 293 |
try:
|
| 294 |
with open(graph_path, encoding="utf-8") as f:
|
|
|
|
| 275 |
return node_ids
|
| 276 |
|
| 277 |
|
| 278 |
+
def _load_graph_packs(
|
| 279 |
+
graph_path: Path,
|
| 280 |
+
*,
|
| 281 |
+
apply_runtime_filter: bool,
|
| 282 |
+
) -> nx.Graph | None:
|
| 283 |
+
"""Load active graph packs beside ``graph.json`` when present."""
|
| 284 |
+
packs_dir = graph_path.parent / "packs"
|
| 285 |
+
if not packs_dir.is_dir():
|
| 286 |
+
return None
|
| 287 |
+
try:
|
| 288 |
+
from ctx.core.graph.graph_packs import ( # noqa: PLC0415
|
| 289 |
+
GraphPackManifestError,
|
| 290 |
+
load_merged_pack_graph,
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
graph = load_merged_pack_graph(packs_dir)
|
| 294 |
+
except GraphPackManifestError as exc:
|
| 295 |
+
logger.warning("graph packs are invalid (%s); returning empty graph", exc)
|
| 296 |
+
return nx.Graph()
|
| 297 |
+
if graph.number_of_nodes() == 0:
|
| 298 |
+
return None
|
| 299 |
+
graph.graph.setdefault("ctx_graph_path", str(graph_path))
|
| 300 |
+
graph.graph["ctx_graph_pack_source"] = "packs"
|
| 301 |
+
graph.graph["ctx_graph_pack_fallback"] = not graph_path.exists()
|
| 302 |
+
graph = _apply_entity_overlays(graph, graph_path)
|
| 303 |
+
if apply_runtime_filter:
|
| 304 |
+
return _filter_runtime_edges(graph, _configured_semantic_min_cosine())
|
| 305 |
+
return graph
|
| 306 |
+
|
| 307 |
+
|
| 308 |
def load_graph(
|
| 309 |
path: Path | None = None,
|
| 310 |
*,
|
| 311 |
apply_runtime_filter: bool = True,
|
| 312 |
) -> nx.Graph:
|
| 313 |
+
"""Load the knowledge graph from active packs or legacy graph.json.
|
| 314 |
|
| 315 |
Returns an empty graph on any parse or schema error rather than crashing.
|
| 316 |
Callers that *require* a populated graph (e.g. CLI main) should check
|
| 317 |
``G.number_of_nodes() == 0`` and handle accordingly.
|
| 318 |
"""
|
| 319 |
graph_path = path if path is not None else GRAPH_PATH
|
| 320 |
+
packed = _load_graph_packs(
|
| 321 |
+
graph_path,
|
| 322 |
+
apply_runtime_filter=apply_runtime_filter,
|
| 323 |
+
)
|
| 324 |
+
if packed is not None:
|
| 325 |
+
return packed
|
| 326 |
if not graph_path.exists():
|
| 327 |
+
message = "graph.json not found at %s; returning empty graph"
|
| 328 |
+
if os.environ.get("CTX_ALLOW_MISSING_GRAPH") == "1":
|
| 329 |
+
logger.debug(message, graph_path)
|
| 330 |
+
else:
|
| 331 |
+
logger.warning(message, graph_path)
|
| 332 |
return nx.Graph()
|
| 333 |
try:
|
| 334 |
with open(graph_path, encoding="utf-8") as f:
|
src/ctx/core/graph/vector_index.py
CHANGED
|
@@ -165,6 +165,66 @@ class HnswlibVectorIndex(NumpyFlatVectorIndex):
|
|
| 165 |
atomic_write_json(meta_path, asdict(self.meta))
|
| 166 |
|
| 167 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
def build_vector_index(
|
| 169 |
*,
|
| 170 |
kind: str,
|
|
@@ -253,6 +313,83 @@ def load_vector_index(
|
|
| 253 |
return None
|
| 254 |
|
| 255 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
def content_fingerprint(node_ids: list[str], content_hashes: list[str]) -> str:
|
| 257 |
payload = "\n".join(
|
| 258 |
f"{node_id}\t{content_hash}"
|
|
@@ -380,6 +517,15 @@ def _validate_inputs(
|
|
| 380 |
raise ValueError("vectors row count must match node_ids")
|
| 381 |
|
| 382 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 383 |
def _normalize(vectors: np.ndarray) -> np.ndarray:
|
| 384 |
matrix = np.asarray(vectors, dtype=np.float32)
|
| 385 |
if matrix.ndim != 2:
|
|
|
|
| 165 |
atomic_write_json(meta_path, asdict(self.meta))
|
| 166 |
|
| 167 |
|
| 168 |
+
class MergedVectorIndex:
|
| 169 |
+
"""Query several compatible vector indexes as one logical index.
|
| 170 |
+
|
| 171 |
+
This is the base+delta primitive: a release can ship an immutable base
|
| 172 |
+
vector index while local entity upserts append a small delta index. Query
|
| 173 |
+
callers get one merged top-k result without rebuilding the base.
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
def __init__(self, indexes: list[NumpyFlatVectorIndex]) -> None:
|
| 177 |
+
if not indexes:
|
| 178 |
+
raise ValueError("at least one vector index is required")
|
| 179 |
+
first = indexes[0].meta
|
| 180 |
+
for index in indexes[1:]:
|
| 181 |
+
if (
|
| 182 |
+
index.meta.metric != first.metric
|
| 183 |
+
or index.meta.model_id != first.model_id
|
| 184 |
+
or index.meta.dim != first.dim
|
| 185 |
+
or index.meta.normalized != first.normalized
|
| 186 |
+
):
|
| 187 |
+
raise ValueError("vector indexes are incompatible")
|
| 188 |
+
self.meta = first
|
| 189 |
+
self.indexes = list(indexes)
|
| 190 |
+
|
| 191 |
+
def query(
|
| 192 |
+
self,
|
| 193 |
+
vectors: np.ndarray,
|
| 194 |
+
*,
|
| 195 |
+
top_k: int,
|
| 196 |
+
min_score: float,
|
| 197 |
+
exclude_node_ids: set[str] | None = None,
|
| 198 |
+
) -> list[list[Neighbor]]:
|
| 199 |
+
queries = _normalize_query_vectors(vectors, expected_dim=self.meta.dim)
|
| 200 |
+
if top_k <= 0:
|
| 201 |
+
return [[] for _ in range(len(queries))]
|
| 202 |
+
merged_rows = [dict[str, float]() for _ in range(len(queries))]
|
| 203 |
+
for index in self.indexes:
|
| 204 |
+
rows = index.query(
|
| 205 |
+
queries,
|
| 206 |
+
top_k=top_k,
|
| 207 |
+
min_score=min_score,
|
| 208 |
+
exclude_node_ids=exclude_node_ids,
|
| 209 |
+
)
|
| 210 |
+
for row_index, neighbors in enumerate(rows):
|
| 211 |
+
merged = merged_rows[row_index]
|
| 212 |
+
for neighbor in neighbors:
|
| 213 |
+
previous = merged.get(neighbor.node_id)
|
| 214 |
+
if previous is None or neighbor.score > previous:
|
| 215 |
+
merged[neighbor.node_id] = neighbor.score
|
| 216 |
+
return [
|
| 217 |
+
[
|
| 218 |
+
Neighbor(node_id, score)
|
| 219 |
+
for node_id, score in sorted(
|
| 220 |
+
row.items(),
|
| 221 |
+
key=lambda item: (-item[1], item[0]),
|
| 222 |
+
)[:top_k]
|
| 223 |
+
]
|
| 224 |
+
for row in merged_rows
|
| 225 |
+
]
|
| 226 |
+
|
| 227 |
+
|
| 228 |
def build_vector_index(
|
| 229 |
*,
|
| 230 |
kind: str,
|
|
|
|
| 313 |
return None
|
| 314 |
|
| 315 |
|
| 316 |
+
def upsert_numpy_flat_index_entry(
|
| 317 |
+
cache_dir: Path,
|
| 318 |
+
*,
|
| 319 |
+
model_id: str,
|
| 320 |
+
node_id: str,
|
| 321 |
+
content_hash: str,
|
| 322 |
+
vector: np.ndarray,
|
| 323 |
+
) -> NumpyFlatVectorIndex:
|
| 324 |
+
"""Create or update one row in a small portable delta vector index."""
|
| 325 |
+
if not model_id:
|
| 326 |
+
raise ValueError("model_id must be non-empty")
|
| 327 |
+
if not node_id:
|
| 328 |
+
raise ValueError("node_id must be non-empty")
|
| 329 |
+
if not content_hash:
|
| 330 |
+
raise ValueError("content_hash must be non-empty")
|
| 331 |
+
vector_row = _single_vector_row(vector)
|
| 332 |
+
cache_dir = Path(cache_dir)
|
| 333 |
+
upsert_lock = cache_dir / ".vector-index-upsert"
|
| 334 |
+
with file_lock(upsert_lock):
|
| 335 |
+
existing = _load_existing_delta_index(cache_dir, model_id=model_id)
|
| 336 |
+
if existing is None:
|
| 337 |
+
node_ids: list[str] = []
|
| 338 |
+
content_hashes: list[str] = []
|
| 339 |
+
vectors = np.empty((0, vector_row.shape[1]), dtype=np.float32)
|
| 340 |
+
else:
|
| 341 |
+
if existing.meta.dim != int(vector_row.shape[1]):
|
| 342 |
+
raise ValueError(
|
| 343 |
+
f"vector dim {vector_row.shape[1]} does not match existing "
|
| 344 |
+
f"index dim {existing.meta.dim}"
|
| 345 |
+
)
|
| 346 |
+
node_ids = list(existing.node_ids)
|
| 347 |
+
content_hashes = list(existing.content_hashes)
|
| 348 |
+
vectors = np.asarray(existing.vectors, dtype=np.float32).copy()
|
| 349 |
+
|
| 350 |
+
if node_id in node_ids:
|
| 351 |
+
row_index = node_ids.index(node_id)
|
| 352 |
+
content_hashes[row_index] = content_hash
|
| 353 |
+
vectors[row_index] = vector_row[0]
|
| 354 |
+
else:
|
| 355 |
+
node_ids.append(node_id)
|
| 356 |
+
content_hashes.append(content_hash)
|
| 357 |
+
vectors = np.vstack([vectors, vector_row])
|
| 358 |
+
|
| 359 |
+
index = build_vector_index(
|
| 360 |
+
kind="numpy-flat",
|
| 361 |
+
model_id=model_id,
|
| 362 |
+
node_ids=node_ids,
|
| 363 |
+
content_hashes=content_hashes,
|
| 364 |
+
vectors=vectors,
|
| 365 |
+
)
|
| 366 |
+
index.save(cache_dir)
|
| 367 |
+
return index
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def _load_existing_delta_index(
|
| 371 |
+
cache_dir: Path,
|
| 372 |
+
*,
|
| 373 |
+
model_id: str,
|
| 374 |
+
) -> NumpyFlatVectorIndex | None:
|
| 375 |
+
meta_path = cache_dir / _META_NAME
|
| 376 |
+
if not meta_path.is_file():
|
| 377 |
+
return None
|
| 378 |
+
try:
|
| 379 |
+
meta_raw = json.loads(meta_path.read_text(encoding="utf-8"))
|
| 380 |
+
meta = VectorIndexMeta(**meta_raw)
|
| 381 |
+
except (OSError, TypeError, ValueError, json.JSONDecodeError) as exc:
|
| 382 |
+
raise ValueError(f"existing vector index metadata is unreadable: {exc}") from exc
|
| 383 |
+
index = load_vector_index(
|
| 384 |
+
cache_dir,
|
| 385 |
+
expected_model_id=model_id,
|
| 386 |
+
expected_content_fingerprint=meta.content_fingerprint,
|
| 387 |
+
)
|
| 388 |
+
if index is None:
|
| 389 |
+
raise ValueError("existing vector index is incompatible or unreadable")
|
| 390 |
+
return index
|
| 391 |
+
|
| 392 |
+
|
| 393 |
def content_fingerprint(node_ids: list[str], content_hashes: list[str]) -> str:
|
| 394 |
payload = "\n".join(
|
| 395 |
f"{node_id}\t{content_hash}"
|
|
|
|
| 517 |
raise ValueError("vectors row count must match node_ids")
|
| 518 |
|
| 519 |
|
| 520 |
+
def _single_vector_row(vector: np.ndarray) -> np.ndarray:
|
| 521 |
+
row = np.asarray(vector, dtype=np.float32)
|
| 522 |
+
if row.ndim == 1:
|
| 523 |
+
row = row.reshape(1, -1)
|
| 524 |
+
if row.ndim != 2 or row.shape[0] != 1 or row.shape[1] <= 0:
|
| 525 |
+
raise ValueError("vector must be a single non-empty row")
|
| 526 |
+
return row
|
| 527 |
+
|
| 528 |
+
|
| 529 |
def _normalize(vectors: np.ndarray) -> np.ndarray:
|
| 530 |
matrix = np.asarray(vectors, dtype=np.float32)
|
| 531 |
if matrix.ndim != 2:
|
src/ctx/core/quality/dedup_check.py
CHANGED
|
@@ -47,6 +47,9 @@ from dataclasses import dataclass, field
|
|
| 47 |
from pathlib import Path
|
| 48 |
from typing import TYPE_CHECKING, Iterable
|
| 49 |
|
|
|
|
|
|
|
|
|
|
| 50 |
if TYPE_CHECKING:
|
| 51 |
import numpy as np
|
| 52 |
|
|
@@ -206,6 +209,11 @@ def _read_frontmatter(path: Path) -> dict:
|
|
| 206 |
text = path.read_text(encoding="utf-8", errors="replace")
|
| 207 |
except OSError:
|
| 208 |
return {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
if not text.startswith("---"):
|
| 210 |
return {}
|
| 211 |
try:
|
|
@@ -246,6 +254,10 @@ def discover_entities(wiki_dir: Path) -> list[EntityRef]:
|
|
| 246 |
the report. The returned list is sorted by ``node_id`` for
|
| 247 |
deterministic output.
|
| 248 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
entities: list[EntityRef] = []
|
| 250 |
type_dirs = {
|
| 251 |
"skill": wiki_dir / "entities" / "skills",
|
|
@@ -278,6 +290,69 @@ def discover_entities(wiki_dir: Path) -> list[EntityRef]:
|
|
| 278 |
return entities
|
| 279 |
|
| 280 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
# ── Embedding alignment ───────────────────────────────────────────────
|
| 282 |
|
| 283 |
|
|
|
|
| 47 |
from pathlib import Path
|
| 48 |
from typing import TYPE_CHECKING, Iterable
|
| 49 |
|
| 50 |
+
from ctx.core.entity_types import ENTITY_TYPE_FOR_SUBJECT_TYPE, mcp_shard
|
| 51 |
+
from ctx.core.wiki.wiki_packs import load_merged_wiki_pages
|
| 52 |
+
|
| 53 |
if TYPE_CHECKING:
|
| 54 |
import numpy as np
|
| 55 |
|
|
|
|
| 209 |
text = path.read_text(encoding="utf-8", errors="replace")
|
| 210 |
except OSError:
|
| 211 |
return {}
|
| 212 |
+
return _frontmatter_from_text(text)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def _frontmatter_from_text(text: str) -> dict:
|
| 216 |
+
"""Tiny YAML-ish frontmatter parser (matches graphify's tolerance)."""
|
| 217 |
if not text.startswith("---"):
|
| 218 |
return {}
|
| 219 |
try:
|
|
|
|
| 254 |
the report. The returned list is sorted by ``node_id`` for
|
| 255 |
deterministic output.
|
| 256 |
"""
|
| 257 |
+
packed = _discover_pack_entities(wiki_dir)
|
| 258 |
+
if packed is not None:
|
| 259 |
+
return packed
|
| 260 |
+
|
| 261 |
entities: list[EntityRef] = []
|
| 262 |
type_dirs = {
|
| 263 |
"skill": wiki_dir / "entities" / "skills",
|
|
|
|
| 290 |
return entities
|
| 291 |
|
| 292 |
|
| 293 |
+
def _discover_pack_entities(wiki_dir: Path) -> list[EntityRef] | None:
|
| 294 |
+
packs_dir = wiki_dir / "wiki-packs"
|
| 295 |
+
if not packs_dir.is_dir():
|
| 296 |
+
return None
|
| 297 |
+
entities: list[EntityRef] = []
|
| 298 |
+
for relpath, text in sorted(load_merged_wiki_pages(packs_dir).items()):
|
| 299 |
+
parsed = _pack_entity_type_and_slug(relpath)
|
| 300 |
+
if parsed is None:
|
| 301 |
+
continue
|
| 302 |
+
entity_type, slug = parsed
|
| 303 |
+
fm = _frontmatter_from_text(text)
|
| 304 |
+
entities.append(_entity_ref_from_frontmatter(
|
| 305 |
+
entity_type=entity_type,
|
| 306 |
+
slug=slug,
|
| 307 |
+
path=wiki_dir / relpath,
|
| 308 |
+
fm=fm,
|
| 309 |
+
))
|
| 310 |
+
entities.sort(key=lambda e: e.node_id)
|
| 311 |
+
return entities
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def _pack_entity_type_and_slug(relpath: str) -> tuple[str, str] | None:
|
| 315 |
+
path = Path(relpath)
|
| 316 |
+
parts = path.parts
|
| 317 |
+
if len(parts) < 3 or parts[0] != "entities" or path.suffix != ".md":
|
| 318 |
+
return None
|
| 319 |
+
entity_type = ENTITY_TYPE_FOR_SUBJECT_TYPE.get(parts[1])
|
| 320 |
+
if entity_type not in {"skill", "agent", "mcp-server"}:
|
| 321 |
+
return None
|
| 322 |
+
slug = path.stem
|
| 323 |
+
if entity_type == "mcp-server":
|
| 324 |
+
if len(parts) != 4 or parts[2] != mcp_shard(slug):
|
| 325 |
+
return None
|
| 326 |
+
elif len(parts) != 3:
|
| 327 |
+
return None
|
| 328 |
+
return entity_type, slug
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def _entity_ref_from_frontmatter(
|
| 332 |
+
*,
|
| 333 |
+
entity_type: str,
|
| 334 |
+
slug: str,
|
| 335 |
+
path: Path,
|
| 336 |
+
fm: dict,
|
| 337 |
+
) -> EntityRef:
|
| 338 |
+
desc = fm.get("description", "")
|
| 339 |
+
if isinstance(desc, list):
|
| 340 |
+
desc = " ".join(str(x) for x in desc)
|
| 341 |
+
desc = str(desc).strip()[:250]
|
| 342 |
+
tags = fm.get("tags", [])
|
| 343 |
+
if not isinstance(tags, list):
|
| 344 |
+
tags = []
|
| 345 |
+
tags_t = tuple(str(t) for t in tags if t)
|
| 346 |
+
return EntityRef(
|
| 347 |
+
node_id=f"{entity_type}:{slug}",
|
| 348 |
+
type=entity_type,
|
| 349 |
+
slug=slug,
|
| 350 |
+
path=path,
|
| 351 |
+
description=desc,
|
| 352 |
+
tags=tags_t,
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
# ── Embedding alignment ───────────────────────────────────────────────
|
| 357 |
|
| 358 |
|
src/ctx/core/quality/skillspector_audit.py
ADDED
|
@@ -0,0 +1,888 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Batch SkillSpector audit support for shipped ctx skill wiki artifacts.
|
| 2 |
+
|
| 3 |
+
This module intentionally keeps SkillSpector as an optional external runtime.
|
| 4 |
+
ctx supports Python 3.11, while SkillSpector currently requires Python 3.12+.
|
| 5 |
+
Run this file under a SkillSpector-enabled interpreter, for example:
|
| 6 |
+
|
| 7 |
+
uv run --no-project --python 3.12 \
|
| 8 |
+
--with git+https://github.com/NVIDIA/skillspector \
|
| 9 |
+
python src/ctx/core/quality/skillspector_audit.py audit-tar \
|
| 10 |
+
--wiki-tar graph/wiki-graph.tar.gz \
|
| 11 |
+
--out graph/skillspector-audit.jsonl.gz
|
| 12 |
+
|
| 13 |
+
The audit is a ctx-run check using NVIDIA's Apache-2.0 SkillSpector tool. It
|
| 14 |
+
must not be represented as NVIDIA endorsement, certification, or signature.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import concurrent.futures
|
| 21 |
+
import gzip
|
| 22 |
+
import hashlib
|
| 23 |
+
import json
|
| 24 |
+
import os
|
| 25 |
+
import shutil
|
| 26 |
+
import tarfile
|
| 27 |
+
import tempfile
|
| 28 |
+
import time
|
| 29 |
+
from dataclasses import asdict, dataclass
|
| 30 |
+
from datetime import UTC, datetime
|
| 31 |
+
from pathlib import Path
|
| 32 |
+
from typing import Any, IO, Iterable, TextIO, cast
|
| 33 |
+
|
| 34 |
+
SKILLSPECTOR_REPO_URL = "https://github.com/NVIDIA/SkillSpector"
|
| 35 |
+
AUDIT_SCHEMA_VERSION = 1
|
| 36 |
+
STAMP_BEGIN = "<!-- ctx-skillspector:begin -->"
|
| 37 |
+
STAMP_END = "<!-- ctx-skillspector:end -->"
|
| 38 |
+
DEFAULT_AUDIT_MEMBER = "security/skillspector-audit.jsonl.gz"
|
| 39 |
+
MAX_PYTHON_TAR_STAMP_MB = 64
|
| 40 |
+
|
| 41 |
+
_SAFE_ENV_KEYS = {
|
| 42 |
+
"APPDATA",
|
| 43 |
+
"COMSPEC",
|
| 44 |
+
"HOME",
|
| 45 |
+
"LANG",
|
| 46 |
+
"LC_ALL",
|
| 47 |
+
"PATH",
|
| 48 |
+
"PATHEXT",
|
| 49 |
+
"REQUESTS_CA_BUNDLE",
|
| 50 |
+
"SSL_CERT_FILE",
|
| 51 |
+
"SYSTEMROOT",
|
| 52 |
+
"TEMP",
|
| 53 |
+
"TMP",
|
| 54 |
+
"TMPDIR",
|
| 55 |
+
"USERPROFILE",
|
| 56 |
+
"VIRTUAL_ENV",
|
| 57 |
+
"WINDIR",
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@dataclass(frozen=True)
|
| 62 |
+
class SkillSpectorAuditRecord:
|
| 63 |
+
"""Compact persisted audit result for one converted skill body."""
|
| 64 |
+
|
| 65 |
+
schema_version: int
|
| 66 |
+
slug: str
|
| 67 |
+
status: str
|
| 68 |
+
risk_score: int | None
|
| 69 |
+
risk_severity: str | None
|
| 70 |
+
recommendation: str | None
|
| 71 |
+
issues: int
|
| 72 |
+
components: int
|
| 73 |
+
content_sha256: str | None
|
| 74 |
+
scanned_at: str
|
| 75 |
+
scanner: str
|
| 76 |
+
scanner_repo: str
|
| 77 |
+
scanner_version: str | None
|
| 78 |
+
mode: str
|
| 79 |
+
llm_requested: bool
|
| 80 |
+
elapsed_seconds: float | None = None
|
| 81 |
+
error: str | None = None
|
| 82 |
+
issue_rules: tuple[str, ...] = ()
|
| 83 |
+
|
| 84 |
+
def to_json(self) -> dict[str, object]:
|
| 85 |
+
payload = asdict(self)
|
| 86 |
+
payload["issue_rules"] = list(self.issue_rules)
|
| 87 |
+
return payload
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _safe_tar_name(name: str) -> str | None:
|
| 91 |
+
normalized = name.replace("\\", "/")
|
| 92 |
+
while normalized.startswith("./"):
|
| 93 |
+
normalized = normalized[2:]
|
| 94 |
+
normalized = normalized.rstrip("/")
|
| 95 |
+
if not normalized:
|
| 96 |
+
return None
|
| 97 |
+
parts = normalized.split("/")
|
| 98 |
+
first = parts[0]
|
| 99 |
+
if (
|
| 100 |
+
normalized.startswith("/")
|
| 101 |
+
or (len(first) == 2 and first[1] == ":")
|
| 102 |
+
or any(part in {"", ".", ".."} for part in parts)
|
| 103 |
+
):
|
| 104 |
+
return None
|
| 105 |
+
return normalized
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _converted_slug(name: str) -> str | None:
|
| 109 |
+
safe = _safe_tar_name(name)
|
| 110 |
+
if safe is None or not safe.startswith("converted/"):
|
| 111 |
+
return None
|
| 112 |
+
parts = safe.split("/")
|
| 113 |
+
if len(parts) < 3:
|
| 114 |
+
return None
|
| 115 |
+
slug = parts[1]
|
| 116 |
+
if not slug or slug in {".", ".."}:
|
| 117 |
+
return None
|
| 118 |
+
return slug
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _entity_skill_slug(name: str) -> str | None:
|
| 122 |
+
safe = _safe_tar_name(name)
|
| 123 |
+
if safe is None or not safe.startswith("entities/skills/") or not safe.endswith(".md"):
|
| 124 |
+
return None
|
| 125 |
+
slug = safe.removeprefix("entities/skills/").removesuffix(".md")
|
| 126 |
+
if "/" in slug or "\\" in slug or not slug:
|
| 127 |
+
return None
|
| 128 |
+
return slug
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _copy_stream(src: IO[bytes], dst: IO[bytes], chunk_size: int = 1024 * 1024) -> None:
|
| 132 |
+
while True:
|
| 133 |
+
chunk = src.read(chunk_size)
|
| 134 |
+
if not chunk:
|
| 135 |
+
return
|
| 136 |
+
dst.write(chunk)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _write_jsonl_gz(path: Path, records: Iterable[SkillSpectorAuditRecord], *, append: bool) -> None:
|
| 140 |
+
mode = "at" if append and path.exists() else "wt"
|
| 141 |
+
with cast(TextIO, gzip.open(path, mode, encoding="utf-8", newline="\n")) as f:
|
| 142 |
+
for record in records:
|
| 143 |
+
f.write(json.dumps(record.to_json(), sort_keys=True, separators=(",", ":")))
|
| 144 |
+
f.write("\n")
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _optional_int(value: object) -> int | None:
|
| 148 |
+
if value is None:
|
| 149 |
+
return None
|
| 150 |
+
return int(str(value))
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _int_value(value: object, default: int) -> int:
|
| 154 |
+
if value is None:
|
| 155 |
+
return default
|
| 156 |
+
return int(str(value))
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _optional_float(value: object) -> float | None:
|
| 160 |
+
if value is None:
|
| 161 |
+
return None
|
| 162 |
+
return float(str(value))
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def load_audit_records(path: Path) -> dict[str, SkillSpectorAuditRecord]:
|
| 166 |
+
records: dict[str, SkillSpectorAuditRecord] = {}
|
| 167 |
+
if not path.exists():
|
| 168 |
+
return records
|
| 169 |
+
with gzip.open(path, "rt", encoding="utf-8") as f:
|
| 170 |
+
for line_number, line in enumerate(f, 1):
|
| 171 |
+
stripped = line.strip()
|
| 172 |
+
if not stripped:
|
| 173 |
+
continue
|
| 174 |
+
try:
|
| 175 |
+
payload = json.loads(stripped)
|
| 176 |
+
except json.JSONDecodeError as exc:
|
| 177 |
+
raise ValueError(f"invalid audit JSON at {path}:{line_number}: {exc}") from exc
|
| 178 |
+
records[str(payload["slug"])] = SkillSpectorAuditRecord(
|
| 179 |
+
schema_version=int(payload.get("schema_version") or AUDIT_SCHEMA_VERSION),
|
| 180 |
+
slug=str(payload["slug"]),
|
| 181 |
+
status=str(payload.get("status") or "error"),
|
| 182 |
+
risk_score=(
|
| 183 |
+
int(payload["risk_score"]) if payload.get("risk_score") is not None else None
|
| 184 |
+
),
|
| 185 |
+
risk_severity=(
|
| 186 |
+
str(payload["risk_severity"])
|
| 187 |
+
if payload.get("risk_severity") is not None
|
| 188 |
+
else None
|
| 189 |
+
),
|
| 190 |
+
recommendation=(
|
| 191 |
+
str(payload["recommendation"])
|
| 192 |
+
if payload.get("recommendation") is not None
|
| 193 |
+
else None
|
| 194 |
+
),
|
| 195 |
+
issues=int(payload.get("issues") or 0),
|
| 196 |
+
components=int(payload.get("components") or 0),
|
| 197 |
+
content_sha256=(
|
| 198 |
+
str(payload["content_sha256"])
|
| 199 |
+
if payload.get("content_sha256") is not None
|
| 200 |
+
else None
|
| 201 |
+
),
|
| 202 |
+
scanned_at=str(payload.get("scanned_at") or ""),
|
| 203 |
+
scanner=str(payload.get("scanner") or "NVIDIA SkillSpector"),
|
| 204 |
+
scanner_repo=str(payload.get("scanner_repo") or SKILLSPECTOR_REPO_URL),
|
| 205 |
+
scanner_version=(
|
| 206 |
+
str(payload["scanner_version"])
|
| 207 |
+
if payload.get("scanner_version") is not None
|
| 208 |
+
else None
|
| 209 |
+
),
|
| 210 |
+
mode=str(payload.get("mode") or "static-no-llm"),
|
| 211 |
+
llm_requested=bool(payload.get("llm_requested")),
|
| 212 |
+
elapsed_seconds=(
|
| 213 |
+
float(payload["elapsed_seconds"])
|
| 214 |
+
if payload.get("elapsed_seconds") is not None
|
| 215 |
+
else None
|
| 216 |
+
),
|
| 217 |
+
error=str(payload["error"]) if payload.get("error") else None,
|
| 218 |
+
issue_rules=tuple(str(rule) for rule in payload.get("issue_rules") or ()),
|
| 219 |
+
)
|
| 220 |
+
return records
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def _skill_content_hash(skill_dir: Path) -> str:
|
| 224 |
+
digest = hashlib.sha256()
|
| 225 |
+
for path in sorted(p for p in skill_dir.rglob("*") if p.is_file()):
|
| 226 |
+
relative = path.relative_to(skill_dir).as_posix()
|
| 227 |
+
digest.update(relative.encode("utf-8"))
|
| 228 |
+
digest.update(b"\0")
|
| 229 |
+
with path.open("rb") as f:
|
| 230 |
+
for chunk in iter(lambda: f.read(1024 * 1024), b""):
|
| 231 |
+
digest.update(chunk)
|
| 232 |
+
digest.update(b"\0")
|
| 233 |
+
return digest.hexdigest()
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _sanitize_worker_env() -> None:
|
| 237 |
+
safe = {key: value for key, value in os.environ.items() if key.upper() in _SAFE_ENV_KEYS}
|
| 238 |
+
os.environ.clear()
|
| 239 |
+
os.environ.update(safe)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def _record_from_report(
|
| 243 |
+
slug: str,
|
| 244 |
+
report: dict[str, Any],
|
| 245 |
+
*,
|
| 246 |
+
content_sha256: str | None,
|
| 247 |
+
elapsed_seconds: float | None,
|
| 248 |
+
) -> SkillSpectorAuditRecord:
|
| 249 |
+
risk = report.get("risk_assessment") if isinstance(report, dict) else {}
|
| 250 |
+
metadata = report.get("metadata") if isinstance(report, dict) else {}
|
| 251 |
+
issues = report.get("issues") if isinstance(report, dict) else []
|
| 252 |
+
components = report.get("components") if isinstance(report, dict) else []
|
| 253 |
+
score = risk.get("score") if isinstance(risk, dict) else None
|
| 254 |
+
severity = risk.get("severity") if isinstance(risk, dict) else None
|
| 255 |
+
recommendation = risk.get("recommendation") if isinstance(risk, dict) else None
|
| 256 |
+
issue_rules = []
|
| 257 |
+
if isinstance(issues, list):
|
| 258 |
+
for issue in issues:
|
| 259 |
+
if not isinstance(issue, dict):
|
| 260 |
+
continue
|
| 261 |
+
rule = issue.get("rule_id") or issue.get("id")
|
| 262 |
+
if rule:
|
| 263 |
+
issue_rules.append(str(rule))
|
| 264 |
+
status = "passed"
|
| 265 |
+
if isinstance(issues, list) and issues:
|
| 266 |
+
status = "findings"
|
| 267 |
+
if isinstance(score, int | float) and score > 50:
|
| 268 |
+
status = "blocked"
|
| 269 |
+
scanned_at = ""
|
| 270 |
+
skill = report.get("skill") if isinstance(report, dict) else {}
|
| 271 |
+
if isinstance(skill, dict) and skill.get("scanned_at"):
|
| 272 |
+
scanned_at = str(skill["scanned_at"])
|
| 273 |
+
if not scanned_at:
|
| 274 |
+
scanned_at = datetime.now(UTC).isoformat()
|
| 275 |
+
return SkillSpectorAuditRecord(
|
| 276 |
+
schema_version=AUDIT_SCHEMA_VERSION,
|
| 277 |
+
slug=slug,
|
| 278 |
+
status=status,
|
| 279 |
+
risk_score=int(score) if score is not None else None,
|
| 280 |
+
risk_severity=str(severity) if severity is not None else None,
|
| 281 |
+
recommendation=str(recommendation) if recommendation is not None else None,
|
| 282 |
+
issues=len(issues) if isinstance(issues, list) else 0,
|
| 283 |
+
components=len(components) if isinstance(components, list) else 0,
|
| 284 |
+
content_sha256=content_sha256,
|
| 285 |
+
scanned_at=scanned_at,
|
| 286 |
+
scanner="NVIDIA SkillSpector",
|
| 287 |
+
scanner_repo=SKILLSPECTOR_REPO_URL,
|
| 288 |
+
scanner_version=(
|
| 289 |
+
str(metadata["skillspector_version"])
|
| 290 |
+
if isinstance(metadata, dict) and metadata.get("skillspector_version")
|
| 291 |
+
else None
|
| 292 |
+
),
|
| 293 |
+
mode="static-no-llm",
|
| 294 |
+
llm_requested=bool(metadata.get("llm_requested")) if isinstance(metadata, dict) else False,
|
| 295 |
+
elapsed_seconds=elapsed_seconds,
|
| 296 |
+
issue_rules=tuple(sorted(set(issue_rules))),
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def _error_record(slug: str, message: str, *, elapsed_seconds: float | None = None) -> dict[str, object]:
|
| 301 |
+
return SkillSpectorAuditRecord(
|
| 302 |
+
schema_version=AUDIT_SCHEMA_VERSION,
|
| 303 |
+
slug=slug,
|
| 304 |
+
status="error",
|
| 305 |
+
risk_score=None,
|
| 306 |
+
risk_severity=None,
|
| 307 |
+
recommendation=None,
|
| 308 |
+
issues=0,
|
| 309 |
+
components=0,
|
| 310 |
+
content_sha256=None,
|
| 311 |
+
scanned_at=datetime.now(UTC).isoformat(),
|
| 312 |
+
scanner="NVIDIA SkillSpector",
|
| 313 |
+
scanner_repo=SKILLSPECTOR_REPO_URL,
|
| 314 |
+
scanner_version=None,
|
| 315 |
+
mode="static-no-llm",
|
| 316 |
+
llm_requested=False,
|
| 317 |
+
elapsed_seconds=elapsed_seconds,
|
| 318 |
+
error=message,
|
| 319 |
+
).to_json()
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def _no_body_record(slug: str) -> SkillSpectorAuditRecord:
|
| 323 |
+
return SkillSpectorAuditRecord(
|
| 324 |
+
schema_version=AUDIT_SCHEMA_VERSION,
|
| 325 |
+
slug=slug,
|
| 326 |
+
status="not_scanned_no_body",
|
| 327 |
+
risk_score=None,
|
| 328 |
+
risk_severity=None,
|
| 329 |
+
recommendation=None,
|
| 330 |
+
issues=0,
|
| 331 |
+
components=0,
|
| 332 |
+
content_sha256=None,
|
| 333 |
+
scanned_at=datetime.now(UTC).isoformat(),
|
| 334 |
+
scanner="NVIDIA SkillSpector",
|
| 335 |
+
scanner_repo=SKILLSPECTOR_REPO_URL,
|
| 336 |
+
scanner_version=None,
|
| 337 |
+
mode="not-run-no-body",
|
| 338 |
+
llm_requested=False,
|
| 339 |
+
error="No converted SKILL.md body is shipped for this skill entity.",
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def _scan_skill_dir(skill_dir_str: str) -> dict[str, object]:
|
| 344 |
+
skill_dir = Path(skill_dir_str)
|
| 345 |
+
slug = skill_dir.name
|
| 346 |
+
started = time.perf_counter()
|
| 347 |
+
try:
|
| 348 |
+
from skillspector.graph import graph # type: ignore[import-not-found]
|
| 349 |
+
|
| 350 |
+
content_sha256 = _skill_content_hash(skill_dir)
|
| 351 |
+
result = graph.invoke(
|
| 352 |
+
{
|
| 353 |
+
"input_path": str(skill_dir),
|
| 354 |
+
"output_format": "json",
|
| 355 |
+
"use_llm": False,
|
| 356 |
+
}
|
| 357 |
+
)
|
| 358 |
+
report_body = result.get("report_body") if isinstance(result, dict) else None
|
| 359 |
+
report = json.loads(str(report_body or "{}"))
|
| 360 |
+
record = _record_from_report(
|
| 361 |
+
slug,
|
| 362 |
+
report,
|
| 363 |
+
content_sha256=content_sha256,
|
| 364 |
+
elapsed_seconds=round(time.perf_counter() - started, 3),
|
| 365 |
+
)
|
| 366 |
+
return record.to_json()
|
| 367 |
+
except Exception as exc: # noqa: BLE001 - scanner failures become audit records.
|
| 368 |
+
return _error_record(slug, str(exc), elapsed_seconds=round(time.perf_counter() - started, 3))
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def _extract_member(member: tarfile.TarInfo, tf: tarfile.TarFile, dest_root: Path) -> None:
|
| 372 |
+
safe = _safe_tar_name(member.name)
|
| 373 |
+
if safe is None:
|
| 374 |
+
raise ValueError(f"unsafe tar member: {member.name!r}")
|
| 375 |
+
parts = safe.split("/")
|
| 376 |
+
relative = Path(*parts[2:])
|
| 377 |
+
dest = dest_root / parts[1] / relative
|
| 378 |
+
if not str(dest.resolve()).startswith(str(dest_root.resolve())):
|
| 379 |
+
raise ValueError(f"unsafe extraction target: {member.name!r}")
|
| 380 |
+
if member.isdir():
|
| 381 |
+
dest.mkdir(parents=True, exist_ok=True)
|
| 382 |
+
return
|
| 383 |
+
if not member.isfile():
|
| 384 |
+
return
|
| 385 |
+
src = tf.extractfile(member)
|
| 386 |
+
if src is None:
|
| 387 |
+
return
|
| 388 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 389 |
+
with src, dest.open("wb") as out:
|
| 390 |
+
_copy_stream(src, out)
|
| 391 |
+
try:
|
| 392 |
+
# Some upstream archives carry restrictive modes. Preserve executable
|
| 393 |
+
# bits where present, but force owner read/write so the isolated
|
| 394 |
+
# SkillSpector worker can inspect the extracted skill body.
|
| 395 |
+
dest.chmod((member.mode & 0o777) | 0o600)
|
| 396 |
+
except OSError:
|
| 397 |
+
pass
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def _completed_record_from_payload(payload: dict[str, object]) -> SkillSpectorAuditRecord:
|
| 401 |
+
issue_rules = payload.get("issue_rules")
|
| 402 |
+
if not isinstance(issue_rules, list | tuple):
|
| 403 |
+
issue_rules = ()
|
| 404 |
+
return SkillSpectorAuditRecord(
|
| 405 |
+
schema_version=_int_value(payload.get("schema_version"), AUDIT_SCHEMA_VERSION),
|
| 406 |
+
slug=str(payload["slug"]),
|
| 407 |
+
status=str(payload.get("status") or "error"),
|
| 408 |
+
risk_score=_optional_int(payload.get("risk_score")),
|
| 409 |
+
risk_severity=str(payload["risk_severity"]) if payload.get("risk_severity") else None,
|
| 410 |
+
recommendation=str(payload["recommendation"]) if payload.get("recommendation") else None,
|
| 411 |
+
issues=_int_value(payload.get("issues"), 0),
|
| 412 |
+
components=_int_value(payload.get("components"), 0),
|
| 413 |
+
content_sha256=str(payload["content_sha256"]) if payload.get("content_sha256") else None,
|
| 414 |
+
scanned_at=str(payload.get("scanned_at") or datetime.now(UTC).isoformat()),
|
| 415 |
+
scanner=str(payload.get("scanner") or "NVIDIA SkillSpector"),
|
| 416 |
+
scanner_repo=str(payload.get("scanner_repo") or SKILLSPECTOR_REPO_URL),
|
| 417 |
+
scanner_version=str(payload["scanner_version"]) if payload.get("scanner_version") else None,
|
| 418 |
+
mode=str(payload.get("mode") or "static-no-llm"),
|
| 419 |
+
llm_requested=bool(payload.get("llm_requested")),
|
| 420 |
+
elapsed_seconds=(
|
| 421 |
+
_optional_float(payload.get("elapsed_seconds"))
|
| 422 |
+
),
|
| 423 |
+
error=str(payload["error"]) if payload.get("error") else None,
|
| 424 |
+
issue_rules=tuple(str(rule) for rule in issue_rules),
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def audit_tar(
|
| 429 |
+
wiki_tar: Path,
|
| 430 |
+
out: Path,
|
| 431 |
+
*,
|
| 432 |
+
workers: int,
|
| 433 |
+
limit: int | None = None,
|
| 434 |
+
resume: bool = True,
|
| 435 |
+
temp_dir: Path | None = None,
|
| 436 |
+
progress_every: int = 1000,
|
| 437 |
+
) -> dict[str, int]:
|
| 438 |
+
"""Stream converted skill bodies from ``wiki_tar`` and write compact audit records."""
|
| 439 |
+
completed = load_audit_records(out) if resume else {}
|
| 440 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 441 |
+
append = resume and out.exists()
|
| 442 |
+
submitted = 0
|
| 443 |
+
completed_count = 0
|
| 444 |
+
skipped = 0
|
| 445 |
+
errors = 0
|
| 446 |
+
pending: dict[concurrent.futures.Future[dict[str, object]], Path] = {}
|
| 447 |
+
max_pending = max(workers * 2, 1)
|
| 448 |
+
closed_slugs: set[str] = set()
|
| 449 |
+
|
| 450 |
+
def drain_one() -> None:
|
| 451 |
+
nonlocal completed_count, errors, append
|
| 452 |
+
done, _ = concurrent.futures.wait(
|
| 453 |
+
pending,
|
| 454 |
+
return_when=concurrent.futures.FIRST_COMPLETED,
|
| 455 |
+
)
|
| 456 |
+
for future in done:
|
| 457 |
+
skill_dir = pending.pop(future)
|
| 458 |
+
try:
|
| 459 |
+
payload = future.result()
|
| 460 |
+
record = _completed_record_from_payload(payload)
|
| 461 |
+
except Exception as exc: # noqa: BLE001
|
| 462 |
+
record = _completed_record_from_payload(_error_record(skill_dir.name, str(exc)))
|
| 463 |
+
errors += 1
|
| 464 |
+
else:
|
| 465 |
+
if record.status == "error":
|
| 466 |
+
errors += 1
|
| 467 |
+
_write_jsonl_gz(out, [record], append=append)
|
| 468 |
+
append = True
|
| 469 |
+
completed_count += 1
|
| 470 |
+
if progress_every > 0 and completed_count % progress_every == 0:
|
| 471 |
+
print(
|
| 472 |
+
json.dumps(
|
| 473 |
+
{
|
| 474 |
+
"event": "progress",
|
| 475 |
+
"completed": completed_count,
|
| 476 |
+
"errors": errors,
|
| 477 |
+
"submitted": submitted,
|
| 478 |
+
},
|
| 479 |
+
sort_keys=True,
|
| 480 |
+
),
|
| 481 |
+
flush=True,
|
| 482 |
+
)
|
| 483 |
+
shutil.rmtree(skill_dir, ignore_errors=True)
|
| 484 |
+
|
| 485 |
+
with tempfile.TemporaryDirectory(prefix="ctx-skillspector-audit-", dir=temp_dir) as work:
|
| 486 |
+
work_root = Path(work)
|
| 487 |
+
current_slug: str | None = None
|
| 488 |
+
current_root: Path | None = None
|
| 489 |
+
with concurrent.futures.ProcessPoolExecutor(
|
| 490 |
+
max_workers=max(workers, 1),
|
| 491 |
+
initializer=_sanitize_worker_env,
|
| 492 |
+
) as pool:
|
| 493 |
+
with tarfile.open(wiki_tar, "r:gz") as tf:
|
| 494 |
+
for member in tf:
|
| 495 |
+
slug = _converted_slug(member.name)
|
| 496 |
+
if slug is None:
|
| 497 |
+
continue
|
| 498 |
+
if current_slug is not None and slug != current_slug:
|
| 499 |
+
if current_root is not None and (current_root / "SKILL.md").exists():
|
| 500 |
+
pending[pool.submit(_scan_skill_dir, str(current_root))] = current_root
|
| 501 |
+
submitted += 1
|
| 502 |
+
if limit is not None and submitted >= limit:
|
| 503 |
+
break
|
| 504 |
+
while len(pending) >= max_pending:
|
| 505 |
+
drain_one()
|
| 506 |
+
closed_slugs.add(current_slug)
|
| 507 |
+
current_slug = None
|
| 508 |
+
current_root = None
|
| 509 |
+
if slug in completed:
|
| 510 |
+
skipped += 1 if member.name.endswith("/SKILL.md") else 0
|
| 511 |
+
continue
|
| 512 |
+
if slug in closed_slugs:
|
| 513 |
+
raise ValueError(
|
| 514 |
+
f"tar is not grouped by converted skill; slug reopened: {slug}"
|
| 515 |
+
)
|
| 516 |
+
if current_slug is None:
|
| 517 |
+
current_slug = slug
|
| 518 |
+
current_root = work_root / slug
|
| 519 |
+
_extract_member(member, tf, work_root)
|
| 520 |
+
else:
|
| 521 |
+
if current_slug is not None and current_root is not None:
|
| 522 |
+
if current_root.exists() and (current_root / "SKILL.md").exists():
|
| 523 |
+
if limit is None or submitted < limit:
|
| 524 |
+
pending[pool.submit(_scan_skill_dir, str(current_root))] = current_root
|
| 525 |
+
submitted += 1
|
| 526 |
+
while pending:
|
| 527 |
+
drain_one()
|
| 528 |
+
|
| 529 |
+
return {
|
| 530 |
+
"submitted": submitted,
|
| 531 |
+
"completed": completed_count,
|
| 532 |
+
"skipped": len(completed),
|
| 533 |
+
"errors": errors,
|
| 534 |
+
}
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def _quote_yaml(value: str) -> str:
|
| 538 |
+
return json.dumps(value, ensure_ascii=False)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def _stamp_block(record: SkillSpectorAuditRecord) -> str:
|
| 542 |
+
score = "unknown" if record.risk_score is None else str(record.risk_score)
|
| 543 |
+
severity = record.risk_severity or "UNKNOWN"
|
| 544 |
+
recommendation = record.recommendation or "UNKNOWN"
|
| 545 |
+
version = record.scanner_version or "unknown"
|
| 546 |
+
if record.status == "not_scanned_no_body":
|
| 547 |
+
return (
|
| 548 |
+
f"{STAMP_BEGIN}\n"
|
| 549 |
+
f"> Security check: not scanned by "
|
| 550 |
+
f"[NVIDIA SkillSpector]({record.scanner_repo}) because this generated "
|
| 551 |
+
f"skill entity has no converted `SKILL.md` body in the shipped wiki. "
|
| 552 |
+
f"This is a ctx coverage marker, not an NVIDIA endorsement or "
|
| 553 |
+
f"certification.\n"
|
| 554 |
+
f"{STAMP_END}\n"
|
| 555 |
+
)
|
| 556 |
+
if record.status == "error":
|
| 557 |
+
return (
|
| 558 |
+
f"{STAMP_BEGIN}\n"
|
| 559 |
+
f"> Security check: attempted with "
|
| 560 |
+
f"[NVIDIA SkillSpector]({record.scanner_repo}) ({record.mode}) but "
|
| 561 |
+
f"the scan errored: {record.error or 'unknown error'}. This is a "
|
| 562 |
+
f"ctx-run tool check, not an NVIDIA endorsement or certification.\n"
|
| 563 |
+
f"{STAMP_END}\n"
|
| 564 |
+
)
|
| 565 |
+
return (
|
| 566 |
+
f"{STAMP_BEGIN}\n"
|
| 567 |
+
f"> Security check: checked with "
|
| 568 |
+
f"[NVIDIA SkillSpector]({record.scanner_repo}) v{version} "
|
| 569 |
+
f"({record.mode}). Result: **{record.status}**; risk {severity}/{score}; "
|
| 570 |
+
f"recommendation {recommendation}; findings {record.issues}; "
|
| 571 |
+
f"components {record.components}. This is a ctx-run tool check, not an "
|
| 572 |
+
f"NVIDIA endorsement or certification.\n"
|
| 573 |
+
f"{STAMP_END}\n"
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
def stamp_entity_text(text: str, record: SkillSpectorAuditRecord) -> str:
|
| 578 |
+
"""Return entity markdown stamped with compact SkillSpector metadata."""
|
| 579 |
+
stripped = _remove_stamp_block(text)
|
| 580 |
+
body = stripped
|
| 581 |
+
frontmatter = ""
|
| 582 |
+
if stripped.startswith("---\n"):
|
| 583 |
+
end = stripped.find("\n---\n", 4)
|
| 584 |
+
if end != -1:
|
| 585 |
+
frontmatter = stripped[4:end]
|
| 586 |
+
body = stripped[end + 5 :]
|
| 587 |
+
lines = [
|
| 588 |
+
line
|
| 589 |
+
for line in frontmatter.splitlines()
|
| 590 |
+
if not line.startswith("skillspector_")
|
| 591 |
+
]
|
| 592 |
+
lines.extend(
|
| 593 |
+
[
|
| 594 |
+
"skillspector_checked: true",
|
| 595 |
+
f"skillspector_status: {_quote_yaml(record.status)}",
|
| 596 |
+
f"skillspector_risk_score: {record.risk_score if record.risk_score is not None else 'null'}",
|
| 597 |
+
f"skillspector_risk_severity: {_quote_yaml(record.risk_severity or 'UNKNOWN')}",
|
| 598 |
+
f"skillspector_issues: {record.issues}",
|
| 599 |
+
f"skillspector_components: {record.components}",
|
| 600 |
+
f"skillspector_version: {_quote_yaml(record.scanner_version or 'unknown')}",
|
| 601 |
+
f"skillspector_mode: {_quote_yaml(record.mode)}",
|
| 602 |
+
f"skillspector_repo: {_quote_yaml(record.scanner_repo)}",
|
| 603 |
+
f"skillspector_checked_at: {_quote_yaml(record.scanned_at)}",
|
| 604 |
+
f"skillspector_note: {_quote_yaml('ctx-run SkillSpector check; not NVIDIA endorsement')}",
|
| 605 |
+
]
|
| 606 |
+
)
|
| 607 |
+
stamped = "---\n" + "\n".join(lines).rstrip() + "\n---\n"
|
| 608 |
+
return stamped + "\n" + _stamp_block(record) + "\n" + body.lstrip()
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def _remove_stamp_block(text: str) -> str:
|
| 612 |
+
start = text.find(STAMP_BEGIN)
|
| 613 |
+
if start == -1:
|
| 614 |
+
return text
|
| 615 |
+
end = text.find(STAMP_END, start)
|
| 616 |
+
if end == -1:
|
| 617 |
+
return text[:start].rstrip() + "\n"
|
| 618 |
+
return (text[:start] + text[end + len(STAMP_END) :]).lstrip("\n")
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
def _add_bytes(tf: tarfile.TarFile, template: tarfile.TarInfo, payload: bytes) -> None:
|
| 622 |
+
info = tarfile.TarInfo(template.name)
|
| 623 |
+
info.size = len(payload)
|
| 624 |
+
info.mode = template.mode
|
| 625 |
+
info.mtime = template.mtime
|
| 626 |
+
info.uid = template.uid
|
| 627 |
+
info.gid = template.gid
|
| 628 |
+
info.uname = template.uname
|
| 629 |
+
info.gname = template.gname
|
| 630 |
+
tf.addfile(info, fileobj=_BytesReader(payload))
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
class _BytesReader:
|
| 634 |
+
def __init__(self, payload: bytes) -> None:
|
| 635 |
+
self._payload = payload
|
| 636 |
+
self._offset = 0
|
| 637 |
+
|
| 638 |
+
def read(self, size: int = -1) -> bytes:
|
| 639 |
+
if size is None or size < 0:
|
| 640 |
+
size = len(self._payload) - self._offset
|
| 641 |
+
end = min(self._offset + size, len(self._payload))
|
| 642 |
+
chunk = self._payload[self._offset : end]
|
| 643 |
+
self._offset = end
|
| 644 |
+
return chunk
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def _atomic_write_bytes(path: Path, payload: bytes) -> None:
|
| 648 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 649 |
+
tmp = path.with_name(f"{path.name}.tmp")
|
| 650 |
+
tmp.write_bytes(payload)
|
| 651 |
+
os.replace(tmp, path)
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
def _atomic_write_text(path: Path, text: str) -> None:
|
| 655 |
+
_atomic_write_bytes(path, text.encode("utf-8"))
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
def stamp_directory(
|
| 659 |
+
wiki_dir: Path,
|
| 660 |
+
audit: Path,
|
| 661 |
+
*,
|
| 662 |
+
audit_member: str = DEFAULT_AUDIT_MEMBER,
|
| 663 |
+
) -> dict[str, int]:
|
| 664 |
+
"""Stamp an extracted wiki directory.
|
| 665 |
+
|
| 666 |
+
This is the release path for the full ctx wiki. It touches only skill entity
|
| 667 |
+
pages that have audit records, then the existing native tar repack flow can
|
| 668 |
+
refresh ``graph/wiki-graph.tar.gz`` quickly.
|
| 669 |
+
"""
|
| 670 |
+
records = load_audit_records(audit)
|
| 671 |
+
stamped = 0
|
| 672 |
+
missing = 0
|
| 673 |
+
entities_dir = wiki_dir / "entities" / "skills"
|
| 674 |
+
for slug, record in records.items():
|
| 675 |
+
path = entities_dir / f"{slug}.md"
|
| 676 |
+
if not path.exists():
|
| 677 |
+
missing += 1
|
| 678 |
+
continue
|
| 679 |
+
text = path.read_text(encoding="utf-8")
|
| 680 |
+
_atomic_write_text(path, stamp_entity_text(text, record))
|
| 681 |
+
stamped += 1
|
| 682 |
+
audit_path = wiki_dir / Path(*audit_member.split("/"))
|
| 683 |
+
_atomic_write_bytes(audit_path, audit.read_bytes())
|
| 684 |
+
return {"stamped": stamped, "missing": missing, "audit_records": len(records)}
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
def stamp_tar(
|
| 688 |
+
wiki_tar: Path,
|
| 689 |
+
audit: Path,
|
| 690 |
+
out: Path,
|
| 691 |
+
*,
|
| 692 |
+
audit_member: str = DEFAULT_AUDIT_MEMBER,
|
| 693 |
+
allow_large_python_repack: bool = False,
|
| 694 |
+
) -> dict[str, int]:
|
| 695 |
+
tar_mb = wiki_tar.stat().st_size / (1024 * 1024)
|
| 696 |
+
if not allow_large_python_repack and tar_mb > MAX_PYTHON_TAR_STAMP_MB:
|
| 697 |
+
raise ValueError(
|
| 698 |
+
"stamp-tar uses Python gzip tar rewriting and is intended for small artifacts. "
|
| 699 |
+
"For the release wiki, extract the wiki, run stamp-dir, then use the native "
|
| 700 |
+
f"tar repack flow. Refusing to rewrite {tar_mb:.1f} MiB without "
|
| 701 |
+
"--allow-large-python-repack."
|
| 702 |
+
)
|
| 703 |
+
records = load_audit_records(audit)
|
| 704 |
+
stamped = 0
|
| 705 |
+
copied = 0
|
| 706 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 707 |
+
with tarfile.open(wiki_tar, "r:gz") as src_tf, tarfile.open(out, "w:gz") as dst_tf:
|
| 708 |
+
for member in src_tf:
|
| 709 |
+
slug = _entity_skill_slug(member.name)
|
| 710 |
+
if slug is not None and slug in records and member.isfile():
|
| 711 |
+
f = src_tf.extractfile(member)
|
| 712 |
+
if f is None:
|
| 713 |
+
continue
|
| 714 |
+
with f:
|
| 715 |
+
text = f.read().decode("utf-8")
|
| 716 |
+
payload = stamp_entity_text(text, records[slug]).encode("utf-8")
|
| 717 |
+
_add_bytes(dst_tf, member, payload)
|
| 718 |
+
stamped += 1
|
| 719 |
+
continue
|
| 720 |
+
dst_tf.addfile(member, src_tf.extractfile(member) if member.isfile() else None)
|
| 721 |
+
copied += 1
|
| 722 |
+
audit_payload = audit.read_bytes()
|
| 723 |
+
info = tarfile.TarInfo(audit_member)
|
| 724 |
+
info.size = len(audit_payload)
|
| 725 |
+
info.mode = 0o644
|
| 726 |
+
info.mtime = int(time.time())
|
| 727 |
+
dst_tf.addfile(info, fileobj=_BytesReader(audit_payload))
|
| 728 |
+
return {"stamped": stamped, "copied": copied, "audit_records": len(records)}
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
def summarize_audit(path: Path) -> dict[str, object]:
|
| 732 |
+
records = load_audit_records(path)
|
| 733 |
+
by_status: dict[str, int] = {}
|
| 734 |
+
by_severity: dict[str, int] = {}
|
| 735 |
+
max_score = 0
|
| 736 |
+
for record in records.values():
|
| 737 |
+
by_status[record.status] = by_status.get(record.status, 0) + 1
|
| 738 |
+
severity = record.risk_severity or "UNKNOWN"
|
| 739 |
+
by_severity[severity] = by_severity.get(severity, 0) + 1
|
| 740 |
+
if record.risk_score is not None:
|
| 741 |
+
max_score = max(max_score, record.risk_score)
|
| 742 |
+
return {
|
| 743 |
+
"records": len(records),
|
| 744 |
+
"by_status": dict(sorted(by_status.items())),
|
| 745 |
+
"by_severity": dict(sorted(by_severity.items())),
|
| 746 |
+
"max_score": max_score,
|
| 747 |
+
"scanner_repo": SKILLSPECTOR_REPO_URL,
|
| 748 |
+
}
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
def cover_entity_pages(wiki_tar: Path, audit: Path) -> dict[str, int]:
|
| 752 |
+
"""Append honest coverage records for skill entities without converted bodies."""
|
| 753 |
+
records = load_audit_records(audit)
|
| 754 |
+
entity_slugs: set[str] = set()
|
| 755 |
+
converted_slugs: set[str] = set()
|
| 756 |
+
with tarfile.open(wiki_tar, "r:gz") as tf:
|
| 757 |
+
for member in tf:
|
| 758 |
+
safe_name = _safe_tar_name(member.name)
|
| 759 |
+
if safe_name is None:
|
| 760 |
+
continue
|
| 761 |
+
entity_slug = _entity_skill_slug(safe_name)
|
| 762 |
+
if entity_slug is not None:
|
| 763 |
+
entity_slugs.add(entity_slug)
|
| 764 |
+
converted_slug = _converted_slug(safe_name)
|
| 765 |
+
if converted_slug is not None and safe_name.endswith("/SKILL.md"):
|
| 766 |
+
converted_slugs.add(converted_slug)
|
| 767 |
+
missing_body = sorted(entity_slugs - converted_slugs)
|
| 768 |
+
to_append = [
|
| 769 |
+
_no_body_record(slug)
|
| 770 |
+
for slug in missing_body
|
| 771 |
+
if slug not in records
|
| 772 |
+
]
|
| 773 |
+
if to_append:
|
| 774 |
+
_write_jsonl_gz(audit, to_append, append=True)
|
| 775 |
+
return {
|
| 776 |
+
"entity_pages": len(entity_slugs),
|
| 777 |
+
"converted_bodies": len(converted_slugs),
|
| 778 |
+
"missing_bodies": len(missing_body),
|
| 779 |
+
"appended": len(to_append),
|
| 780 |
+
}
|
| 781 |
+
|
| 782 |
+
|
| 783 |
+
def _audit_tar_command(args: argparse.Namespace) -> int:
|
| 784 |
+
stats = audit_tar(
|
| 785 |
+
Path(args.wiki_tar),
|
| 786 |
+
Path(args.out),
|
| 787 |
+
workers=args.workers,
|
| 788 |
+
limit=args.limit,
|
| 789 |
+
resume=not args.no_resume,
|
| 790 |
+
temp_dir=Path(args.temp_dir) if args.temp_dir else None,
|
| 791 |
+
progress_every=args.progress_every,
|
| 792 |
+
)
|
| 793 |
+
print(json.dumps(stats, sort_keys=True))
|
| 794 |
+
return 1 if stats["errors"] else 0
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
def _stamp_tar_command(args: argparse.Namespace) -> int:
|
| 798 |
+
try:
|
| 799 |
+
stats = stamp_tar(
|
| 800 |
+
Path(args.wiki_tar),
|
| 801 |
+
Path(args.audit),
|
| 802 |
+
Path(args.out),
|
| 803 |
+
allow_large_python_repack=args.allow_large_python_repack,
|
| 804 |
+
)
|
| 805 |
+
except ValueError as exc:
|
| 806 |
+
print(f"error: {exc}")
|
| 807 |
+
return 2
|
| 808 |
+
print(json.dumps(stats, sort_keys=True))
|
| 809 |
+
return 0
|
| 810 |
+
|
| 811 |
+
|
| 812 |
+
def _stamp_dir_command(args: argparse.Namespace) -> int:
|
| 813 |
+
stats = stamp_directory(Path(args.wiki_dir), Path(args.audit))
|
| 814 |
+
print(json.dumps(stats, sort_keys=True))
|
| 815 |
+
return 0
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
def _summary_command(args: argparse.Namespace) -> int:
|
| 819 |
+
print(json.dumps(summarize_audit(Path(args.audit)), indent=2, sort_keys=True))
|
| 820 |
+
return 0
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
def _cover_entities_command(args: argparse.Namespace) -> int:
|
| 824 |
+
stats = cover_entity_pages(Path(args.wiki_tar), Path(args.audit))
|
| 825 |
+
print(json.dumps(stats, sort_keys=True))
|
| 826 |
+
return 0
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
def build_parser() -> argparse.ArgumentParser:
|
| 830 |
+
parser = argparse.ArgumentParser(description="Audit/stamp ctx skill wiki artifacts with SkillSpector.")
|
| 831 |
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
| 832 |
+
|
| 833 |
+
audit_parser = subparsers.add_parser("audit-tar", help="Scan converted skill bodies from a wiki tarball.")
|
| 834 |
+
audit_parser.add_argument("--wiki-tar", required=True, help="Path to graph/wiki-graph.tar.gz.")
|
| 835 |
+
audit_parser.add_argument("--out", required=True, help="Audit JSONL gzip output path.")
|
| 836 |
+
audit_parser.add_argument("--workers", type=int, default=max((os.cpu_count() or 2) // 2, 1))
|
| 837 |
+
audit_parser.add_argument("--limit", type=int, default=None, help="Optional pilot limit.")
|
| 838 |
+
audit_parser.add_argument("--no-resume", action="store_true", help="Ignore existing output.")
|
| 839 |
+
audit_parser.add_argument("--temp-dir", default=None, help="Optional parent temp directory.")
|
| 840 |
+
audit_parser.add_argument(
|
| 841 |
+
"--progress-every",
|
| 842 |
+
type=int,
|
| 843 |
+
default=1000,
|
| 844 |
+
help="Print a JSON progress line every N completed scans; 0 disables.",
|
| 845 |
+
)
|
| 846 |
+
audit_parser.set_defaults(func=_audit_tar_command)
|
| 847 |
+
|
| 848 |
+
stamp_parser = subparsers.add_parser("stamp-tar", help="Stamp skill entity pages using an audit file.")
|
| 849 |
+
stamp_parser.add_argument("--wiki-tar", required=True)
|
| 850 |
+
stamp_parser.add_argument("--audit", required=True)
|
| 851 |
+
stamp_parser.add_argument("--out", required=True)
|
| 852 |
+
stamp_parser.add_argument(
|
| 853 |
+
"--allow-large-python-repack",
|
| 854 |
+
action="store_true",
|
| 855 |
+
help="Allow slow Python gzip rewriting for large tarballs.",
|
| 856 |
+
)
|
| 857 |
+
stamp_parser.set_defaults(func=_stamp_tar_command)
|
| 858 |
+
|
| 859 |
+
stamp_dir_parser = subparsers.add_parser(
|
| 860 |
+
"stamp-dir",
|
| 861 |
+
help="Stamp skill entity pages in an extracted wiki directory.",
|
| 862 |
+
)
|
| 863 |
+
stamp_dir_parser.add_argument("--wiki-dir", required=True)
|
| 864 |
+
stamp_dir_parser.add_argument("--audit", required=True)
|
| 865 |
+
stamp_dir_parser.set_defaults(func=_stamp_dir_command)
|
| 866 |
+
|
| 867 |
+
summary_parser = subparsers.add_parser("summary", help="Summarize audit JSONL gzip.")
|
| 868 |
+
summary_parser.add_argument("--audit", required=True)
|
| 869 |
+
summary_parser.set_defaults(func=_summary_command)
|
| 870 |
+
|
| 871 |
+
cover_parser = subparsers.add_parser(
|
| 872 |
+
"cover-entities",
|
| 873 |
+
help="Append no-body coverage records for skill entity pages without SKILL.md bodies.",
|
| 874 |
+
)
|
| 875 |
+
cover_parser.add_argument("--wiki-tar", required=True)
|
| 876 |
+
cover_parser.add_argument("--audit", required=True)
|
| 877 |
+
cover_parser.set_defaults(func=_cover_entities_command)
|
| 878 |
+
return parser
|
| 879 |
+
|
| 880 |
+
|
| 881 |
+
def main(argv: list[str] | None = None) -> int:
|
| 882 |
+
parser = build_parser()
|
| 883 |
+
args = parser.parse_args(argv)
|
| 884 |
+
return int(args.func(args))
|
| 885 |
+
|
| 886 |
+
|
| 887 |
+
if __name__ == "__main__":
|
| 888 |
+
raise SystemExit(main())
|
src/ctx/core/quality/skillspector_monitor.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dashboard helpers for ctx-run SkillSpector audit records."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import re
|
| 7 |
+
import sqlite3
|
| 8 |
+
from collections import Counter
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
from ctx.core.quality.skillspector_audit import (
|
| 13 |
+
SkillSpectorAuditRecord,
|
| 14 |
+
load_audit_records,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
STATUS_ORDER = {
|
| 19 |
+
"blocked": 0,
|
| 20 |
+
"findings": 1,
|
| 21 |
+
"not_scanned_no_body": 2,
|
| 22 |
+
"error": 3,
|
| 23 |
+
"missing": 4,
|
| 24 |
+
"passed": 5,
|
| 25 |
+
}
|
| 26 |
+
SEVERITY_ORDER = {
|
| 27 |
+
"CRITICAL": 0,
|
| 28 |
+
"HIGH": 1,
|
| 29 |
+
"MEDIUM": 2,
|
| 30 |
+
"LOW": 3,
|
| 31 |
+
"UNKNOWN": 4,
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def load_skill_metadata_from_dashboard_index(
|
| 36 |
+
index_path: Path | None,
|
| 37 |
+
) -> dict[str, dict[str, Any]]:
|
| 38 |
+
"""Load skill tags/title/description from the cached dashboard graph index."""
|
| 39 |
+
if index_path is None or not index_path.is_file():
|
| 40 |
+
return {}
|
| 41 |
+
try:
|
| 42 |
+
conn = sqlite3.connect(f"file:{index_path.as_posix()}?mode=ro", uri=True)
|
| 43 |
+
except sqlite3.Error:
|
| 44 |
+
return {}
|
| 45 |
+
conn.row_factory = sqlite3.Row
|
| 46 |
+
try:
|
| 47 |
+
rows = conn.execute(
|
| 48 |
+
"SELECT id,label,tags,description,quality_score,usage_score,degree "
|
| 49 |
+
"FROM nodes WHERE type='skill'"
|
| 50 |
+
).fetchall()
|
| 51 |
+
except sqlite3.Error:
|
| 52 |
+
return {}
|
| 53 |
+
finally:
|
| 54 |
+
conn.close()
|
| 55 |
+
|
| 56 |
+
metadata: dict[str, dict[str, Any]] = {}
|
| 57 |
+
for row in rows:
|
| 58 |
+
node_id = str(row["id"] or "")
|
| 59 |
+
slug = node_id.split(":", 1)[1] if ":" in node_id else node_id
|
| 60 |
+
if not slug:
|
| 61 |
+
continue
|
| 62 |
+
try:
|
| 63 |
+
raw_tags = json.loads(str(row["tags"] or "[]"))
|
| 64 |
+
except json.JSONDecodeError:
|
| 65 |
+
raw_tags = []
|
| 66 |
+
tags = [str(tag) for tag in raw_tags if isinstance(tag, str)]
|
| 67 |
+
metadata[slug] = {
|
| 68 |
+
"title": str(row["label"] or slug),
|
| 69 |
+
"tags": tags,
|
| 70 |
+
"description": str(row["description"] or ""),
|
| 71 |
+
"quality_score": row["quality_score"],
|
| 72 |
+
"usage_score": row["usage_score"],
|
| 73 |
+
"degree": int(row["degree"] or 0),
|
| 74 |
+
}
|
| 75 |
+
return metadata
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def load_skill_families_from_communities(
|
| 79 |
+
communities_path: Path | None,
|
| 80 |
+
) -> dict[str, dict[str, str]]:
|
| 81 |
+
"""Load graph community labels as skill family metadata."""
|
| 82 |
+
if communities_path is None or not communities_path.is_file():
|
| 83 |
+
return {}
|
| 84 |
+
try:
|
| 85 |
+
payload = json.loads(communities_path.read_text(encoding="utf-8"))
|
| 86 |
+
except (OSError, json.JSONDecodeError):
|
| 87 |
+
return {}
|
| 88 |
+
communities = payload.get("communities") if isinstance(payload, dict) else None
|
| 89 |
+
if not isinstance(communities, dict):
|
| 90 |
+
return {}
|
| 91 |
+
|
| 92 |
+
families: dict[str, dict[str, str]] = {}
|
| 93 |
+
for raw_id, raw_info in communities.items():
|
| 94 |
+
if not isinstance(raw_info, dict):
|
| 95 |
+
continue
|
| 96 |
+
label = str(raw_info.get("label") or f"community {raw_id}")
|
| 97 |
+
members = raw_info.get("members")
|
| 98 |
+
if not isinstance(members, list):
|
| 99 |
+
continue
|
| 100 |
+
for member in members:
|
| 101 |
+
node_id = str(member)
|
| 102 |
+
if not node_id.startswith("skill:"):
|
| 103 |
+
continue
|
| 104 |
+
slug = node_id.split(":", 1)[1]
|
| 105 |
+
families[slug] = {
|
| 106 |
+
"family": label,
|
| 107 |
+
"family_id": str(raw_id),
|
| 108 |
+
}
|
| 109 |
+
return families
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def load_skillspector_audit_records(path: Path) -> dict[str, SkillSpectorAuditRecord]:
|
| 113 |
+
"""Load SkillSpector audit records from gzip, returning empty when absent."""
|
| 114 |
+
return load_audit_records(path)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def build_skillspector_audit_payload(
|
| 118 |
+
records: dict[str, SkillSpectorAuditRecord],
|
| 119 |
+
*,
|
| 120 |
+
metadata_by_slug: dict[str, dict[str, Any]] | None = None,
|
| 121 |
+
families_by_slug: dict[str, dict[str, str]] | None = None,
|
| 122 |
+
query: str = "",
|
| 123 |
+
status: str = "",
|
| 124 |
+
severity: str = "",
|
| 125 |
+
tag: str = "",
|
| 126 |
+
family: str = "",
|
| 127 |
+
limit: int = 100,
|
| 128 |
+
) -> dict[str, Any]:
|
| 129 |
+
"""Return filterable dashboard payload for SkillSpector records."""
|
| 130 |
+
metadata_by_slug = metadata_by_slug or {}
|
| 131 |
+
families_by_slug = families_by_slug or {}
|
| 132 |
+
all_rows = [
|
| 133 |
+
_row_from_record(
|
| 134 |
+
record,
|
| 135 |
+
metadata_by_slug.get(slug, {}),
|
| 136 |
+
families_by_slug.get(slug, {}),
|
| 137 |
+
)
|
| 138 |
+
for slug, record in records.items()
|
| 139 |
+
]
|
| 140 |
+
all_rows.sort(key=_row_sort_key)
|
| 141 |
+
|
| 142 |
+
filtered = [
|
| 143 |
+
row for row in all_rows
|
| 144 |
+
if _row_matches(row, query=query, status=status, severity=severity, tag=tag, family=family)
|
| 145 |
+
]
|
| 146 |
+
capped_limit = max(1, min(int(limit), 500))
|
| 147 |
+
status_counts = Counter(str(row["status"]) for row in all_rows)
|
| 148 |
+
severity_counts = Counter(str(row["risk_severity"]) for row in all_rows)
|
| 149 |
+
tag_counts = Counter(
|
| 150 |
+
tag_value
|
| 151 |
+
for row in all_rows
|
| 152 |
+
for tag_value in row.get("tags", [])
|
| 153 |
+
)
|
| 154 |
+
family_counts = Counter(
|
| 155 |
+
str(row["family"])
|
| 156 |
+
for row in all_rows
|
| 157 |
+
if row.get("family")
|
| 158 |
+
)
|
| 159 |
+
return {
|
| 160 |
+
"summary": {
|
| 161 |
+
"total": len(all_rows),
|
| 162 |
+
"visible": len(filtered),
|
| 163 |
+
"returned": min(len(filtered), capped_limit),
|
| 164 |
+
"problematic": sum(
|
| 165 |
+
count for status_name, count in status_counts.items()
|
| 166 |
+
if status_name != "passed"
|
| 167 |
+
),
|
| 168 |
+
"statuses": dict(sorted(status_counts.items(), key=lambda item: _status_rank(item[0]))),
|
| 169 |
+
"severities": dict(sorted(severity_counts.items(), key=lambda item: _severity_rank(item[0]))),
|
| 170 |
+
},
|
| 171 |
+
"filters": {
|
| 172 |
+
"query": query,
|
| 173 |
+
"status": status,
|
| 174 |
+
"severity": severity,
|
| 175 |
+
"tag": tag,
|
| 176 |
+
"family": family,
|
| 177 |
+
"limit": capped_limit,
|
| 178 |
+
"statuses": _counter_options(status_counts, rank=_status_rank),
|
| 179 |
+
"severities": _counter_options(severity_counts, rank=_severity_rank),
|
| 180 |
+
"tags": _counter_options(tag_counts, limit=100),
|
| 181 |
+
"families": _counter_options(family_counts, limit=100),
|
| 182 |
+
},
|
| 183 |
+
"records": filtered[:capped_limit],
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _row_from_record(
|
| 188 |
+
record: SkillSpectorAuditRecord,
|
| 189 |
+
metadata: dict[str, Any],
|
| 190 |
+
family: dict[str, str],
|
| 191 |
+
) -> dict[str, Any]:
|
| 192 |
+
severity = str(record.risk_severity or "UNKNOWN").upper()
|
| 193 |
+
tags = [str(tag) for tag in metadata.get("tags") or [] if str(tag).strip()]
|
| 194 |
+
return {
|
| 195 |
+
"slug": record.slug,
|
| 196 |
+
"title": str(metadata.get("title") or record.slug),
|
| 197 |
+
"description": str(metadata.get("description") or ""),
|
| 198 |
+
"tags": tags,
|
| 199 |
+
"family": family.get("family", ""),
|
| 200 |
+
"family_id": family.get("family_id", ""),
|
| 201 |
+
"status": str(record.status or "error"),
|
| 202 |
+
"risk_score": record.risk_score,
|
| 203 |
+
"risk_severity": severity,
|
| 204 |
+
"recommendation": record.recommendation or "",
|
| 205 |
+
"issues": record.issues,
|
| 206 |
+
"components": record.components,
|
| 207 |
+
"issue_rules": list(record.issue_rules),
|
| 208 |
+
"content_sha256": record.content_sha256 or "",
|
| 209 |
+
"scanned_at": record.scanned_at,
|
| 210 |
+
"scanner_version": record.scanner_version or "",
|
| 211 |
+
"mode": record.mode,
|
| 212 |
+
"error": record.error or "",
|
| 213 |
+
"quality_score": metadata.get("quality_score"),
|
| 214 |
+
"usage_score": metadata.get("usage_score"),
|
| 215 |
+
"degree": metadata.get("degree", 0),
|
| 216 |
+
"href": f"/wiki/{record.slug}?type=skill",
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _row_matches(
|
| 221 |
+
row: dict[str, Any],
|
| 222 |
+
*,
|
| 223 |
+
query: str,
|
| 224 |
+
status: str,
|
| 225 |
+
severity: str,
|
| 226 |
+
tag: str,
|
| 227 |
+
family: str,
|
| 228 |
+
) -> bool:
|
| 229 |
+
status_filter = status.strip().lower()
|
| 230 |
+
if status_filter and status_filter != "all" and str(row["status"]).lower() != status_filter:
|
| 231 |
+
return False
|
| 232 |
+
severity_filter = severity.strip().upper()
|
| 233 |
+
if severity_filter and severity_filter != "ALL" and str(row["risk_severity"]).upper() != severity_filter:
|
| 234 |
+
return False
|
| 235 |
+
tag_filter = tag.strip().lower()
|
| 236 |
+
if tag_filter:
|
| 237 |
+
tags = [str(value).lower() for value in row.get("tags", [])]
|
| 238 |
+
if not any(tag_filter in value for value in tags):
|
| 239 |
+
return False
|
| 240 |
+
family_filter = family.strip().lower()
|
| 241 |
+
if family_filter:
|
| 242 |
+
family_values = {
|
| 243 |
+
str(row.get("family") or "").lower(),
|
| 244 |
+
str(row.get("family_id") or "").lower(),
|
| 245 |
+
}
|
| 246 |
+
if family_filter not in family_values:
|
| 247 |
+
return False
|
| 248 |
+
terms = [term for term in re.split(r"\s+", query.lower().strip()) if term]
|
| 249 |
+
if not terms:
|
| 250 |
+
return True
|
| 251 |
+
haystack = " ".join([
|
| 252 |
+
str(row.get("slug") or ""),
|
| 253 |
+
str(row.get("title") or ""),
|
| 254 |
+
str(row.get("description") or ""),
|
| 255 |
+
str(row.get("family") or ""),
|
| 256 |
+
str(row.get("status") or ""),
|
| 257 |
+
str(row.get("risk_severity") or ""),
|
| 258 |
+
str(row.get("recommendation") or ""),
|
| 259 |
+
str(row.get("error") or ""),
|
| 260 |
+
" ".join(str(tag_value) for tag_value in row.get("tags", [])),
|
| 261 |
+
" ".join(str(rule) for rule in row.get("issue_rules", [])),
|
| 262 |
+
]).lower()
|
| 263 |
+
return all(term in haystack for term in terms)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def _row_sort_key(row: dict[str, Any]) -> tuple[int, int, int, str]:
|
| 267 |
+
risk_score = row.get("risk_score")
|
| 268 |
+
try:
|
| 269 |
+
risk_value = int(risk_score) if risk_score is not None else -1
|
| 270 |
+
except (TypeError, ValueError):
|
| 271 |
+
risk_value = -1
|
| 272 |
+
return (
|
| 273 |
+
_status_rank(str(row.get("status") or "")),
|
| 274 |
+
_severity_rank(str(row.get("risk_severity") or "")),
|
| 275 |
+
-risk_value,
|
| 276 |
+
str(row.get("slug") or "").lower(),
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def _status_rank(value: str) -> int:
|
| 281 |
+
return STATUS_ORDER.get(value.lower(), 99)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def _severity_rank(value: str) -> int:
|
| 285 |
+
return SEVERITY_ORDER.get(value.upper(), 99)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def _counter_options(
|
| 289 |
+
counter: Counter[str],
|
| 290 |
+
*,
|
| 291 |
+
rank: Any | None = None,
|
| 292 |
+
limit: int | None = None,
|
| 293 |
+
) -> list[dict[str, Any]]:
|
| 294 |
+
def sort_key(item: tuple[str, int]) -> tuple[Any, int, str]:
|
| 295 |
+
label, count = item
|
| 296 |
+
return (rank(label) if rank else label.lower(), -count, label.lower())
|
| 297 |
+
|
| 298 |
+
items = sorted(counter.items(), key=sort_key)
|
| 299 |
+
if limit is not None:
|
| 300 |
+
items = items[:limit]
|
| 301 |
+
return [{"value": label, "count": count} for label, count in items]
|
src/ctx/core/quality/skillspector_remediation.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Plan remediation/removal from ctx SkillSpector audit records.
|
| 2 |
+
|
| 3 |
+
This module is intentionally non-destructive. It converts the persisted
|
| 4 |
+
SkillSpector audit into a reviewable action plan so the later graph/wiki rewrite
|
| 5 |
+
can remove exactly the intended skill entities with provenance.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
from collections import Counter
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
+
from datetime import UTC, datetime
|
| 14 |
+
import json
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
from ctx.core.quality.skillspector_audit import (
|
| 19 |
+
SKILLSPECTOR_REPO_URL,
|
| 20 |
+
SkillSpectorAuditRecord,
|
| 21 |
+
load_audit_records,
|
| 22 |
+
)
|
| 23 |
+
from ctx.utils._fs_utils import atomic_write_json, atomic_write_text
|
| 24 |
+
|
| 25 |
+
PLAN_SCHEMA_VERSION = 1
|
| 26 |
+
|
| 27 |
+
REMOVE_STATUSES = frozenset({"blocked", "not_scanned_no_body"})
|
| 28 |
+
REVIEW_STATUSES = frozenset({"findings"})
|
| 29 |
+
KEEP_STATUSES = frozenset({"passed"})
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@dataclass(frozen=True)
|
| 33 |
+
class RemediationDecision:
|
| 34 |
+
slug: str
|
| 35 |
+
action: str
|
| 36 |
+
reason: str
|
| 37 |
+
status: str
|
| 38 |
+
risk_severity: str
|
| 39 |
+
risk_score: int | None
|
| 40 |
+
issues: int
|
| 41 |
+
issue_rules: tuple[str, ...]
|
| 42 |
+
recommendation: str | None
|
| 43 |
+
|
| 44 |
+
def to_json(self) -> dict[str, Any]:
|
| 45 |
+
return {
|
| 46 |
+
"slug": self.slug,
|
| 47 |
+
"action": self.action,
|
| 48 |
+
"reason": self.reason,
|
| 49 |
+
"status": self.status,
|
| 50 |
+
"risk_severity": self.risk_severity,
|
| 51 |
+
"risk_score": self.risk_score,
|
| 52 |
+
"issues": self.issues,
|
| 53 |
+
"issue_rules": list(self.issue_rules),
|
| 54 |
+
"recommendation": self.recommendation,
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def decide_record(record: SkillSpectorAuditRecord) -> RemediationDecision:
|
| 59 |
+
"""Return the deterministic first-pass action for one audit record."""
|
| 60 |
+
severity = record.risk_severity or "UNKNOWN"
|
| 61 |
+
if record.status in REMOVE_STATUSES:
|
| 62 |
+
if record.status == "not_scanned_no_body":
|
| 63 |
+
action = "remove"
|
| 64 |
+
reason = "skill entity has no converted SKILL.md body to scan or install"
|
| 65 |
+
else:
|
| 66 |
+
action = "remove"
|
| 67 |
+
reason = f"SkillSpector blocked the skill with {severity} risk"
|
| 68 |
+
elif record.status in REVIEW_STATUSES:
|
| 69 |
+
action = "remove"
|
| 70 |
+
reason = (
|
| 71 |
+
"SkillSpector finding remains unresolved; remove until remediated "
|
| 72 |
+
"and rescanned cleanly"
|
| 73 |
+
)
|
| 74 |
+
elif record.status in KEEP_STATUSES:
|
| 75 |
+
action = "keep"
|
| 76 |
+
reason = "SkillSpector passed"
|
| 77 |
+
else:
|
| 78 |
+
action = "review_unknown"
|
| 79 |
+
reason = f"unrecognized SkillSpector status: {record.status}"
|
| 80 |
+
|
| 81 |
+
return RemediationDecision(
|
| 82 |
+
slug=record.slug,
|
| 83 |
+
action=action,
|
| 84 |
+
reason=reason,
|
| 85 |
+
status=record.status,
|
| 86 |
+
risk_severity=severity,
|
| 87 |
+
risk_score=record.risk_score,
|
| 88 |
+
issues=record.issues,
|
| 89 |
+
issue_rules=record.issue_rules,
|
| 90 |
+
recommendation=record.recommendation,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def build_remediation_plan(
|
| 95 |
+
records: dict[str, SkillSpectorAuditRecord],
|
| 96 |
+
*,
|
| 97 |
+
audit_path: Path | None = None,
|
| 98 |
+
generated_at: str | None = None,
|
| 99 |
+
) -> dict[str, Any]:
|
| 100 |
+
"""Build a stable JSON remediation plan from loaded audit records."""
|
| 101 |
+
decisions = [decide_record(record) for record in records.values()]
|
| 102 |
+
decisions.sort(key=lambda decision: (decision.action, decision.slug))
|
| 103 |
+
|
| 104 |
+
status_counts = Counter(record.status for record in records.values())
|
| 105 |
+
severity_counts = Counter(record.risk_severity or "UNKNOWN" for record in records.values())
|
| 106 |
+
action_counts = Counter(decision.action for decision in decisions)
|
| 107 |
+
rule_counts = Counter(rule for record in records.values() for rule in record.issue_rules)
|
| 108 |
+
|
| 109 |
+
return {
|
| 110 |
+
"schema_version": PLAN_SCHEMA_VERSION,
|
| 111 |
+
"generated_at": generated_at or datetime.now(UTC).isoformat(),
|
| 112 |
+
"audit_path": str(audit_path) if audit_path is not None else None,
|
| 113 |
+
"scanner_repo": SKILLSPECTOR_REPO_URL,
|
| 114 |
+
"summary": {
|
| 115 |
+
"total": len(records),
|
| 116 |
+
"actions": dict(sorted(action_counts.items())),
|
| 117 |
+
"statuses": dict(sorted(status_counts.items())),
|
| 118 |
+
"severities": dict(sorted(severity_counts.items())),
|
| 119 |
+
"top_issue_rules": [
|
| 120 |
+
{"rule": rule, "count": count} for rule, count in rule_counts.most_common(25)
|
| 121 |
+
],
|
| 122 |
+
},
|
| 123 |
+
"remove_slugs": [
|
| 124 |
+
decision.slug for decision in decisions if decision.action == "remove"
|
| 125 |
+
],
|
| 126 |
+
"review_slugs": [
|
| 127 |
+
decision.slug
|
| 128 |
+
for decision in decisions
|
| 129 |
+
if decision.action in {"review_remediate", "review_unknown"}
|
| 130 |
+
],
|
| 131 |
+
"decisions": [decision.to_json() for decision in decisions],
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def render_markdown_plan(plan: dict[str, Any]) -> str:
|
| 136 |
+
"""Render a compact human-readable remediation report."""
|
| 137 |
+
summary = plan["summary"]
|
| 138 |
+
lines = [
|
| 139 |
+
"# SkillSpector Remediation Plan",
|
| 140 |
+
"",
|
| 141 |
+
f"- Generated: `{plan['generated_at']}`",
|
| 142 |
+
f"- Audit: `{plan.get('audit_path') or 'unknown'}`",
|
| 143 |
+
f"- Total records: **{summary['total']:,}**",
|
| 144 |
+
"",
|
| 145 |
+
"## Actions",
|
| 146 |
+
"",
|
| 147 |
+
]
|
| 148 |
+
for action, count in summary["actions"].items():
|
| 149 |
+
lines.append(f"- `{action}`: **{count:,}**")
|
| 150 |
+
lines.extend(["", "## Statuses", ""])
|
| 151 |
+
for status, count in summary["statuses"].items():
|
| 152 |
+
lines.append(f"- `{status}`: **{count:,}**")
|
| 153 |
+
lines.extend(["", "## Top Issue Rules", ""])
|
| 154 |
+
for item in summary["top_issue_rules"][:15]:
|
| 155 |
+
lines.append(f"- `{item['rule']}`: **{item['count']:,}**")
|
| 156 |
+
lines.extend(["", "## Removal Scope", ""])
|
| 157 |
+
lines.append(
|
| 158 |
+
"Remove actions include records SkillSpector blocked, records without a "
|
| 159 |
+
"converted `SKILL.md` body, and every non-passing finding record. A "
|
| 160 |
+
"finding can return only after the skill is remediated and rescanned "
|
| 161 |
+
"cleanly.",
|
| 162 |
+
)
|
| 163 |
+
return "\n".join(lines) + "\n"
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def _write_plan(path: Path, plan: dict[str, Any], *, output_format: str) -> None:
|
| 167 |
+
if output_format == "json":
|
| 168 |
+
atomic_write_json(path, plan, indent=2)
|
| 169 |
+
elif output_format == "md":
|
| 170 |
+
atomic_write_text(path, render_markdown_plan(plan), encoding="utf-8")
|
| 171 |
+
else:
|
| 172 |
+
raise ValueError(f"unsupported output format: {output_format}")
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def main(argv: list[str] | None = None) -> int:
|
| 176 |
+
parser = argparse.ArgumentParser(
|
| 177 |
+
description="Create a non-destructive SkillSpector remediation/removal plan.",
|
| 178 |
+
)
|
| 179 |
+
parser.add_argument(
|
| 180 |
+
"--audit",
|
| 181 |
+
type=Path,
|
| 182 |
+
default=Path("graph/skillspector-audit.jsonl.gz"),
|
| 183 |
+
help="SkillSpector audit JSONL gzip path",
|
| 184 |
+
)
|
| 185 |
+
parser.add_argument(
|
| 186 |
+
"--out",
|
| 187 |
+
type=Path,
|
| 188 |
+
default=None,
|
| 189 |
+
help="Optional output path. Defaults to stdout.",
|
| 190 |
+
)
|
| 191 |
+
parser.add_argument(
|
| 192 |
+
"--format",
|
| 193 |
+
choices=("json", "md"),
|
| 194 |
+
default="json",
|
| 195 |
+
help="Plan output format",
|
| 196 |
+
)
|
| 197 |
+
args = parser.parse_args(argv)
|
| 198 |
+
|
| 199 |
+
records = load_audit_records(args.audit)
|
| 200 |
+
plan = build_remediation_plan(records, audit_path=args.audit)
|
| 201 |
+
|
| 202 |
+
if args.out is None:
|
| 203 |
+
if args.format == "json":
|
| 204 |
+
print(json.dumps(plan, indent=2, sort_keys=True))
|
| 205 |
+
else:
|
| 206 |
+
print(render_markdown_plan(plan), end="")
|
| 207 |
+
return 0
|
| 208 |
+
|
| 209 |
+
_write_plan(args.out, plan, output_format=args.format)
|
| 210 |
+
print(f"wrote SkillSpector remediation plan: {args.out}")
|
| 211 |
+
return 0
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
if __name__ == "__main__":
|
| 215 |
+
raise SystemExit(main())
|
src/ctx/core/quality/skillspector_service.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reusable SkillSpector service for ctx skill intake/install gates.
|
| 2 |
+
|
| 3 |
+
SkillSpector stays optional and external because ctx supports Python 3.11 while
|
| 4 |
+
SkillSpector currently requires Python 3.12+. This module is the ctx-wide
|
| 5 |
+
adapter used by CLI, dashboard, and host-specific integrations.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import re
|
| 14 |
+
import shutil
|
| 15 |
+
import subprocess
|
| 16 |
+
import tempfile
|
| 17 |
+
from dataclasses import asdict, dataclass
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Sequence
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass(frozen=True)
|
| 23 |
+
class SkillSpectorResult:
|
| 24 |
+
"""Result from a best-effort SkillSpector scan."""
|
| 25 |
+
|
| 26 |
+
status: str # passed | findings | missing | error | skipped
|
| 27 |
+
command: list[str]
|
| 28 |
+
exit_code: int | None
|
| 29 |
+
output: str
|
| 30 |
+
|
| 31 |
+
@property
|
| 32 |
+
def passed(self) -> bool:
|
| 33 |
+
return self.status == "passed"
|
| 34 |
+
|
| 35 |
+
def to_json(self) -> dict[str, object]:
|
| 36 |
+
return asdict(self)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
_SAFE_ENV_KEYS = {
|
| 40 |
+
"APPDATA",
|
| 41 |
+
"COMSPEC",
|
| 42 |
+
"HOME",
|
| 43 |
+
"LANG",
|
| 44 |
+
"LC_ALL",
|
| 45 |
+
"PATH",
|
| 46 |
+
"PATHEXT",
|
| 47 |
+
"REQUESTS_CA_BUNDLE",
|
| 48 |
+
"SSL_CERT_FILE",
|
| 49 |
+
"SYSTEMROOT",
|
| 50 |
+
"TEMP",
|
| 51 |
+
"TMP",
|
| 52 |
+
"TMPDIR",
|
| 53 |
+
"USERPROFILE",
|
| 54 |
+
"VIRTUAL_ENV",
|
| 55 |
+
"WINDIR",
|
| 56 |
+
}
|
| 57 |
+
_ANSI_CSI_RE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
|
| 58 |
+
_ANSI_OSC_RE = re.compile(r"\x1b\][^\x07]*(?:\x07|\x1b\\)")
|
| 59 |
+
_SECRET_ASSIGNMENT_RE = re.compile(
|
| 60 |
+
r"(?i)\b((?:[A-Z0-9_]*"
|
| 61 |
+
r"(?:API[_-]?KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)"
|
| 62 |
+
r"[A-Z0-9_]*|HF_TOKEN|GITHUB_TOKEN|OPENAI_API_KEY)"
|
| 63 |
+
r"\s*[:=]\s*)([^\s]+)"
|
| 64 |
+
)
|
| 65 |
+
_KNOWN_TOKEN_RE = re.compile(
|
| 66 |
+
r"\b(?:gh[pousr]_[A-Za-z0-9_]{20,}|hf_[A-Za-z0-9]{20,}|"
|
| 67 |
+
r"sk-[A-Za-z0-9_-]{20,})\b"
|
| 68 |
+
)
|
| 69 |
+
_MAX_OUTPUT_CHARS = 20_000
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def skill_scan_target(source_path: Path) -> Path:
|
| 73 |
+
"""Return the path SkillSpector should scan for a candidate skill."""
|
| 74 |
+
if source_path.is_file() and source_path.name.lower() == "skill.md":
|
| 75 |
+
return source_path.parent
|
| 76 |
+
return source_path
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _resolve_command(
|
| 80 |
+
command: Sequence[str] | None = None,
|
| 81 |
+
binary: str | None = None,
|
| 82 |
+
) -> list[str] | None:
|
| 83 |
+
if command:
|
| 84 |
+
return [str(part) for part in command]
|
| 85 |
+
configured = binary or os.environ.get("CTX_SKILLSPECTOR_BIN") or "skillspector"
|
| 86 |
+
if os.sep in configured or (os.altsep and os.altsep in configured):
|
| 87 |
+
return [configured] if Path(configured).exists() else None
|
| 88 |
+
found = shutil.which(configured)
|
| 89 |
+
return [found] if found else None
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _scanner_env(*, use_llm: bool) -> dict[str, str] | None:
|
| 93 |
+
if use_llm:
|
| 94 |
+
return None
|
| 95 |
+
safe: dict[str, str] = {}
|
| 96 |
+
for key, value in os.environ.items():
|
| 97 |
+
if key.upper() in _SAFE_ENV_KEYS:
|
| 98 |
+
safe[key] = value
|
| 99 |
+
return safe
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _stringify_output(value: str | bytes | None) -> str:
|
| 103 |
+
if value is None:
|
| 104 |
+
return ""
|
| 105 |
+
if isinstance(value, bytes):
|
| 106 |
+
return value.decode("utf-8", errors="replace")
|
| 107 |
+
return value
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _sanitize_output(output: str) -> str:
|
| 111 |
+
clean = _ANSI_OSC_RE.sub("", output)
|
| 112 |
+
clean = _ANSI_CSI_RE.sub("", clean)
|
| 113 |
+
clean = _SECRET_ASSIGNMENT_RE.sub(r"\1[REDACTED]", clean)
|
| 114 |
+
clean = _KNOWN_TOKEN_RE.sub("[REDACTED]", clean)
|
| 115 |
+
if len(clean) > _MAX_OUTPUT_CHARS:
|
| 116 |
+
clean = clean[:_MAX_OUTPUT_CHARS] + "\n[truncated SkillSpector output]"
|
| 117 |
+
return clean
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def run_skillspector_scan(
|
| 121 |
+
target: Path,
|
| 122 |
+
*,
|
| 123 |
+
command: Sequence[str] | None = None,
|
| 124 |
+
binary: str | None = None,
|
| 125 |
+
use_llm: bool = False,
|
| 126 |
+
timeout_seconds: int = 120,
|
| 127 |
+
) -> SkillSpectorResult:
|
| 128 |
+
"""Run SkillSpector against ``target`` and return captured output."""
|
| 129 |
+
resolved = _resolve_command(command=command, binary=binary)
|
| 130 |
+
if resolved is None:
|
| 131 |
+
return SkillSpectorResult(
|
| 132 |
+
status="missing",
|
| 133 |
+
command=[binary or os.environ.get("CTX_SKILLSPECTOR_BIN") or "skillspector"],
|
| 134 |
+
exit_code=None,
|
| 135 |
+
output=(
|
| 136 |
+
"SkillSpector is not installed or not on PATH. Install it, or set "
|
| 137 |
+
"CTX_SKILLSPECTOR_BIN to the scanner executable."
|
| 138 |
+
),
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
scan_command = [
|
| 142 |
+
*resolved,
|
| 143 |
+
"scan",
|
| 144 |
+
str(target),
|
| 145 |
+
"--format",
|
| 146 |
+
"terminal",
|
| 147 |
+
]
|
| 148 |
+
if not use_llm:
|
| 149 |
+
scan_command.append("--no-llm")
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
completed = subprocess.run(
|
| 153 |
+
scan_command,
|
| 154 |
+
capture_output=True,
|
| 155 |
+
text=True,
|
| 156 |
+
env=_scanner_env(use_llm=use_llm),
|
| 157 |
+
timeout=max(timeout_seconds, 1),
|
| 158 |
+
check=False,
|
| 159 |
+
)
|
| 160 |
+
except subprocess.TimeoutExpired as exc:
|
| 161 |
+
output = _stringify_output(exc.stdout) + _stringify_output(exc.stderr)
|
| 162 |
+
return SkillSpectorResult(
|
| 163 |
+
status="error",
|
| 164 |
+
command=scan_command,
|
| 165 |
+
exit_code=None,
|
| 166 |
+
output=(
|
| 167 |
+
_sanitize_output(output.strip())
|
| 168 |
+
or f"SkillSpector timed out after {timeout_seconds}s."
|
| 169 |
+
),
|
| 170 |
+
)
|
| 171 |
+
except OSError as exc:
|
| 172 |
+
return SkillSpectorResult(
|
| 173 |
+
status="error",
|
| 174 |
+
command=scan_command,
|
| 175 |
+
exit_code=None,
|
| 176 |
+
output=f"SkillSpector failed to start: {exc}",
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
output = "\n".join(
|
| 180 |
+
part.strip()
|
| 181 |
+
for part in (completed.stdout, completed.stderr)
|
| 182 |
+
if part and part.strip()
|
| 183 |
+
)
|
| 184 |
+
output = _sanitize_output(output)
|
| 185 |
+
if completed.returncode == 0:
|
| 186 |
+
status = "passed"
|
| 187 |
+
elif completed.returncode == 1:
|
| 188 |
+
status = "findings"
|
| 189 |
+
else:
|
| 190 |
+
status = "error"
|
| 191 |
+
return SkillSpectorResult(
|
| 192 |
+
status=status,
|
| 193 |
+
command=scan_command,
|
| 194 |
+
exit_code=completed.returncode,
|
| 195 |
+
output=output,
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def run_skillspector_scan_text(
|
| 200 |
+
slug: str,
|
| 201 |
+
markdown_text: str,
|
| 202 |
+
*,
|
| 203 |
+
command: Sequence[str] | None = None,
|
| 204 |
+
binary: str | None = None,
|
| 205 |
+
use_llm: bool = False,
|
| 206 |
+
timeout_seconds: int = 120,
|
| 207 |
+
) -> SkillSpectorResult:
|
| 208 |
+
"""Run SkillSpector against an in-memory skill body."""
|
| 209 |
+
safe_slug = re.sub(r"[^a-zA-Z0-9_.+-]+", "-", slug).strip("-") or "skill"
|
| 210 |
+
with tempfile.TemporaryDirectory(prefix="ctx-skillspector-") as temp_root:
|
| 211 |
+
skill_dir = Path(temp_root) / safe_slug
|
| 212 |
+
skill_dir.mkdir(parents=True, exist_ok=True)
|
| 213 |
+
(skill_dir / "SKILL.md").write_text(markdown_text, encoding="utf-8")
|
| 214 |
+
return run_skillspector_scan(
|
| 215 |
+
skill_dir,
|
| 216 |
+
command=command,
|
| 217 |
+
binary=binary,
|
| 218 |
+
use_llm=use_llm,
|
| 219 |
+
timeout_seconds=timeout_seconds,
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def render_scan_report(result: SkillSpectorResult) -> str:
|
| 224 |
+
"""Return a concise user-facing report for a scan result."""
|
| 225 |
+
lines = [
|
| 226 |
+
f"SkillSpector: {result.status}",
|
| 227 |
+
"Command: " + " ".join(result.command),
|
| 228 |
+
]
|
| 229 |
+
if result.output:
|
| 230 |
+
lines.extend(["", result.output])
|
| 231 |
+
return "\n".join(lines)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def main(argv: list[str] | None = None) -> int:
|
| 235 |
+
parser = argparse.ArgumentParser(description="Run ctx's SkillSpector service gate on a skill path.")
|
| 236 |
+
parser.add_argument("target", help="Skill directory or SKILL.md path to scan")
|
| 237 |
+
parser.add_argument("--optional", action="store_true", help="Return 0 even when the scan does not pass")
|
| 238 |
+
parser.add_argument("--use-llm", action="store_true", help="Allow SkillSpector LLM analysis")
|
| 239 |
+
parser.add_argument("--skillspector-bin", default=None, help="SkillSpector executable path/name")
|
| 240 |
+
parser.add_argument("--timeout", type=int, default=120, help="SkillSpector timeout in seconds")
|
| 241 |
+
parser.add_argument("--json", action="store_true", help="Print machine-readable JSON")
|
| 242 |
+
args = parser.parse_args(argv)
|
| 243 |
+
|
| 244 |
+
target = skill_scan_target(Path(args.target).expanduser())
|
| 245 |
+
result = run_skillspector_scan(
|
| 246 |
+
target,
|
| 247 |
+
binary=args.skillspector_bin,
|
| 248 |
+
use_llm=args.use_llm,
|
| 249 |
+
timeout_seconds=args.timeout,
|
| 250 |
+
)
|
| 251 |
+
if args.json:
|
| 252 |
+
print(json.dumps(result.to_json(), indent=2, sort_keys=True))
|
| 253 |
+
else:
|
| 254 |
+
print(render_scan_report(result))
|
| 255 |
+
return 0 if result.passed or args.optional else 1
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
if __name__ == "__main__":
|
| 259 |
+
raise SystemExit(main())
|
src/ctx/core/resolve/resolve_skills.py
CHANGED
|
@@ -21,6 +21,7 @@ from datetime import datetime, timezone
|
|
| 21 |
from pathlib import Path
|
| 22 |
from typing import Any
|
| 23 |
|
|
|
|
| 24 |
from ctx.core.wiki.wiki_utils import parse_frontmatter as _parse_fm
|
| 25 |
|
| 26 |
# Graph-walk augmentation. Lazy-imported so the module still works when the
|
|
@@ -89,19 +90,17 @@ def discover_available_skills(skills_dir: str) -> dict[str, dict]:
|
|
| 89 |
def read_wiki_overrides(wiki_path: str) -> dict[str, dict]:
|
| 90 |
"""Read entity pages from the wiki for always_load/never_load overrides."""
|
| 91 |
overrides: dict[str, dict[str, Any]] = {}
|
| 92 |
-
entities_dir = Path(wiki_path) / "entities" / "skills"
|
| 93 |
|
| 94 |
-
|
|
|
|
| 95 |
return overrides
|
| 96 |
|
| 97 |
-
for
|
| 98 |
try:
|
| 99 |
-
content = page.read_text(encoding="utf-8", errors="replace")
|
| 100 |
meta = _parse_fm(content)
|
| 101 |
if not meta:
|
| 102 |
continue
|
| 103 |
|
| 104 |
-
skill_name = page.stem
|
| 105 |
use_count_val = int(str(meta.get("use_count", "0")))
|
| 106 |
overrides[skill_name] = {
|
| 107 |
"always_load": str(meta.get("always_load", "false")).lower() == "true",
|
|
@@ -111,12 +110,40 @@ def read_wiki_overrides(wiki_path: str) -> dict[str, dict]:
|
|
| 111 |
"status": str(meta.get("status", "unknown")),
|
| 112 |
}
|
| 113 |
except Exception as exc:
|
| 114 |
-
print(f"Warning: wiki override parse error for {
|
| 115 |
continue
|
| 116 |
|
| 117 |
return overrides
|
| 118 |
|
| 119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
# Stack-to-skill mapping lives in ``stack_skill_map`` as the single
|
| 121 |
# source of truth shared with ``usage_tracker.SIGNAL_SKILL_MAP``.
|
| 122 |
# Pre-P2.4 each module had its own copy; the usage_tracker one was a
|
|
|
|
| 21 |
from pathlib import Path
|
| 22 |
from typing import Any
|
| 23 |
|
| 24 |
+
from ctx.core.wiki.wiki_packs import load_merged_wiki_pages
|
| 25 |
from ctx.core.wiki.wiki_utils import parse_frontmatter as _parse_fm
|
| 26 |
|
| 27 |
# Graph-walk augmentation. Lazy-imported so the module still works when the
|
|
|
|
| 90 |
def read_wiki_overrides(wiki_path: str) -> dict[str, dict]:
|
| 91 |
"""Read entity pages from the wiki for always_load/never_load overrides."""
|
| 92 |
overrides: dict[str, dict[str, Any]] = {}
|
|
|
|
| 93 |
|
| 94 |
+
pages = _iter_skill_override_pages(Path(wiki_path))
|
| 95 |
+
if not pages:
|
| 96 |
return overrides
|
| 97 |
|
| 98 |
+
for skill_name, content in pages:
|
| 99 |
try:
|
|
|
|
| 100 |
meta = _parse_fm(content)
|
| 101 |
if not meta:
|
| 102 |
continue
|
| 103 |
|
|
|
|
| 104 |
use_count_val = int(str(meta.get("use_count", "0")))
|
| 105 |
overrides[skill_name] = {
|
| 106 |
"always_load": str(meta.get("always_load", "false")).lower() == "true",
|
|
|
|
| 110 |
"status": str(meta.get("status", "unknown")),
|
| 111 |
}
|
| 112 |
except Exception as exc:
|
| 113 |
+
print(f"Warning: wiki override parse error for {skill_name}: {exc}", file=sys.stderr)
|
| 114 |
continue
|
| 115 |
|
| 116 |
return overrides
|
| 117 |
|
| 118 |
|
| 119 |
+
def _iter_skill_override_pages(wiki: Path) -> list[tuple[str, str]]:
|
| 120 |
+
packs_dir = wiki / "wiki-packs"
|
| 121 |
+
if packs_dir.is_dir():
|
| 122 |
+
rows: list[tuple[str, str]] = []
|
| 123 |
+
for relpath, content in sorted(load_merged_wiki_pages(packs_dir).items()):
|
| 124 |
+
path = Path(relpath)
|
| 125 |
+
if (
|
| 126 |
+
len(path.parts) == 3
|
| 127 |
+
and path.parts[0] == "entities"
|
| 128 |
+
and path.parts[1] == "skills"
|
| 129 |
+
and path.suffix == ".md"
|
| 130 |
+
):
|
| 131 |
+
rows.append((path.stem, content))
|
| 132 |
+
return rows
|
| 133 |
+
|
| 134 |
+
entities_dir = wiki / "entities" / "skills"
|
| 135 |
+
if not entities_dir.exists():
|
| 136 |
+
return []
|
| 137 |
+
|
| 138 |
+
rows = []
|
| 139 |
+
for page in entities_dir.glob("*.md"):
|
| 140 |
+
try:
|
| 141 |
+
rows.append((page.stem, page.read_text(encoding="utf-8", errors="replace")))
|
| 142 |
+
except OSError as exc:
|
| 143 |
+
print(f"Warning: wiki override read error for {page.stem}: {exc}", file=sys.stderr)
|
| 144 |
+
return rows
|
| 145 |
+
|
| 146 |
+
|
| 147 |
# Stack-to-skill mapping lives in ``stack_skill_map`` as the single
|
| 148 |
# source of truth shared with ``usage_tracker.SIGNAL_SKILL_MAP``.
|
| 149 |
# Pre-P2.4 each module had its own copy; the usage_tracker one was a
|
src/ctx/core/wiki/pack_compaction.py
ADDED
|
@@ -0,0 +1,654 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Coordinated graph/wiki pack compaction.
|
| 2 |
+
|
| 3 |
+
This module stages a new immutable graph base pack and matching wiki base pack
|
| 4 |
+
from the active base+overlay sets. Promotion remains a separate step so callers
|
| 5 |
+
can validate both staged artifacts before replacing the active packs.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
import shutil
|
| 13 |
+
import sys
|
| 14 |
+
from collections.abc import Iterable
|
| 15 |
+
from dataclasses import dataclass
|
| 16 |
+
from datetime import UTC, datetime
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
from ctx.core.graph.graph_packs import (
|
| 20 |
+
GraphPackEntry,
|
| 21 |
+
GraphPackManifest,
|
| 22 |
+
GraphPackManifestError,
|
| 23 |
+
GraphPackPromotion,
|
| 24 |
+
compact_graph_packs,
|
| 25 |
+
discover_pack_manifests,
|
| 26 |
+
load_merged_pack_graph,
|
| 27 |
+
promote_graph_pack_set,
|
| 28 |
+
)
|
| 29 |
+
from ctx.core.graph.graph_store import ensure_graph_store
|
| 30 |
+
from ctx.core.wiki.wiki_packs import (
|
| 31 |
+
WikiPackEntry,
|
| 32 |
+
WikiPackManifest,
|
| 33 |
+
WikiPackManifestError,
|
| 34 |
+
WikiPackPromotion,
|
| 35 |
+
compact_wiki_packs,
|
| 36 |
+
discover_wiki_pack_manifests,
|
| 37 |
+
load_merged_wiki_pages,
|
| 38 |
+
promote_wiki_pack_set,
|
| 39 |
+
)
|
| 40 |
+
from ctx.core.wiki.pack_validation import (
|
| 41 |
+
PACK_COMPACTION_MANIFEST,
|
| 42 |
+
PACK_COMPACTION_SCHEMA_VERSION,
|
| 43 |
+
validate_graph_wiki_consistency,
|
| 44 |
+
validate_pack_compaction_manifest,
|
| 45 |
+
)
|
| 46 |
+
from ctx.utils._fs_utils import atomic_write_text
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class PackCompactionError(ValueError):
|
| 50 |
+
"""Raised when coordinated graph/wiki pack compaction cannot be staged."""
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@dataclass(frozen=True)
|
| 54 |
+
class PackCompactionResult:
|
| 55 |
+
"""Staged graph/wiki compaction result."""
|
| 56 |
+
|
| 57 |
+
wiki_path: Path
|
| 58 |
+
staging_dir: Path
|
| 59 |
+
graph_packs_dir: Path
|
| 60 |
+
wiki_packs_dir: Path
|
| 61 |
+
staged_graph_packs_dir: Path
|
| 62 |
+
staged_wiki_packs_dir: Path
|
| 63 |
+
manifest_path: Path
|
| 64 |
+
graph_manifest: GraphPackManifest
|
| 65 |
+
wiki_manifest: WikiPackManifest
|
| 66 |
+
|
| 67 |
+
def to_mapping(self) -> dict[str, object]:
|
| 68 |
+
"""Return deterministic JSON-serialisable compaction metadata."""
|
| 69 |
+
return {
|
| 70 |
+
"schema_version": PACK_COMPACTION_SCHEMA_VERSION,
|
| 71 |
+
"operation": "pack-compaction-stage",
|
| 72 |
+
"wiki_path": str(self.wiki_path),
|
| 73 |
+
"staging_dir": str(self.staging_dir),
|
| 74 |
+
"graph_packs_dir": str(self.graph_packs_dir),
|
| 75 |
+
"wiki_packs_dir": str(self.wiki_packs_dir),
|
| 76 |
+
"staged_graph_packs_dir": str(self.staged_graph_packs_dir),
|
| 77 |
+
"staged_wiki_packs_dir": str(self.staged_wiki_packs_dir),
|
| 78 |
+
"manifest_path": str(self.manifest_path),
|
| 79 |
+
"base_export_id": self.graph_manifest.base_export_id,
|
| 80 |
+
"graph": self.graph_manifest.to_mapping(),
|
| 81 |
+
"wiki": self.wiki_manifest.to_mapping(),
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@dataclass(frozen=True)
|
| 86 |
+
class PackPromotionResult:
|
| 87 |
+
"""Coordinated graph/wiki pack promotion result."""
|
| 88 |
+
|
| 89 |
+
wiki_path: Path
|
| 90 |
+
graph: GraphPackPromotion
|
| 91 |
+
wiki: WikiPackPromotion
|
| 92 |
+
graph_store: dict[str, bool | int] | None = None
|
| 93 |
+
|
| 94 |
+
def to_mapping(self) -> dict[str, object]:
|
| 95 |
+
"""Return deterministic JSON-serialisable promotion metadata."""
|
| 96 |
+
return {
|
| 97 |
+
"wiki_path": str(self.wiki_path),
|
| 98 |
+
"graph": self.graph.to_mapping(),
|
| 99 |
+
"wiki": self.wiki.to_mapping(),
|
| 100 |
+
"graph_store": self.graph_store,
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def pack_compaction_status(
|
| 105 |
+
*,
|
| 106 |
+
wiki_path: Path,
|
| 107 |
+
overlay_threshold: int | None = None,
|
| 108 |
+
validate: bool = True,
|
| 109 |
+
) -> dict[str, object]:
|
| 110 |
+
"""Return read-only operational status for active graph/wiki pack sets."""
|
| 111 |
+
threshold = _normalise_overlay_threshold(
|
| 112 |
+
overlay_threshold if overlay_threshold is not None else _default_overlay_threshold()
|
| 113 |
+
)
|
| 114 |
+
wiki_root = Path(wiki_path)
|
| 115 |
+
graph_packs_dir = wiki_root / "graphify-out" / "packs"
|
| 116 |
+
wiki_packs_dir = wiki_root / "wiki-packs"
|
| 117 |
+
try:
|
| 118 |
+
graph_entries = discover_pack_manifests(graph_packs_dir)
|
| 119 |
+
wiki_entries = discover_wiki_pack_manifests(wiki_packs_dir)
|
| 120 |
+
except (GraphPackManifestError, WikiPackManifestError) as exc:
|
| 121 |
+
raise PackCompactionError(str(exc)) from exc
|
| 122 |
+
|
| 123 |
+
graph_overlays = _overlay_count(graph_entries)
|
| 124 |
+
wiki_overlays = _overlay_count(wiki_entries)
|
| 125 |
+
max_overlays = max(graph_overlays, wiki_overlays)
|
| 126 |
+
validation_result: dict[str, object] | None = None
|
| 127 |
+
if validate and graph_entries and wiki_entries:
|
| 128 |
+
validation_result = validate_pack_sets(
|
| 129 |
+
graph_packs_dir=graph_packs_dir,
|
| 130 |
+
wiki_packs_dir=wiki_packs_dir,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
graph_base_export_id = (
|
| 134 |
+
graph_entries[0].manifest.base_export_id if graph_entries else None
|
| 135 |
+
)
|
| 136 |
+
wiki_base_export_id = (
|
| 137 |
+
wiki_entries[0].manifest.base_export_id if wiki_entries else None
|
| 138 |
+
)
|
| 139 |
+
base_export_id = (
|
| 140 |
+
graph_base_export_id
|
| 141 |
+
if graph_base_export_id == wiki_base_export_id
|
| 142 |
+
else None
|
| 143 |
+
)
|
| 144 |
+
can_compact_now = bool(
|
| 145 |
+
graph_entries
|
| 146 |
+
and wiki_entries
|
| 147 |
+
and graph_overlays > 0
|
| 148 |
+
and wiki_overlays > 0
|
| 149 |
+
and base_export_id is not None
|
| 150 |
+
)
|
| 151 |
+
return {
|
| 152 |
+
"wiki_path": str(wiki_root),
|
| 153 |
+
"graph_packs_dir": str(graph_packs_dir),
|
| 154 |
+
"wiki_packs_dir": str(wiki_packs_dir),
|
| 155 |
+
"base_export_id": base_export_id,
|
| 156 |
+
"graph_base_export_id": graph_base_export_id,
|
| 157 |
+
"wiki_base_export_id": wiki_base_export_id,
|
| 158 |
+
"graph_pack_ids": [entry.manifest.pack_id for entry in graph_entries],
|
| 159 |
+
"wiki_pack_ids": [entry.manifest.pack_id for entry in wiki_entries],
|
| 160 |
+
"graph_pack_count": len(graph_entries),
|
| 161 |
+
"wiki_pack_count": len(wiki_entries),
|
| 162 |
+
"graph_overlay_count": graph_overlays,
|
| 163 |
+
"wiki_overlay_count": wiki_overlays,
|
| 164 |
+
"max_overlay_count": max_overlays,
|
| 165 |
+
"overlay_threshold": threshold,
|
| 166 |
+
"needs_compaction": max_overlays >= threshold,
|
| 167 |
+
"can_compact_now": can_compact_now,
|
| 168 |
+
"validation": validation_result,
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def compact_active_pack_sets(
|
| 173 |
+
*,
|
| 174 |
+
wiki_path: Path,
|
| 175 |
+
base_export_id: str,
|
| 176 |
+
staging_dir: Path | None = None,
|
| 177 |
+
graph_config_hash: str | None = None,
|
| 178 |
+
graph_model_id: str | None = None,
|
| 179 |
+
created_at: str | None = None,
|
| 180 |
+
) -> PackCompactionResult:
|
| 181 |
+
"""Stage matching compacted graph and wiki base packs.
|
| 182 |
+
|
| 183 |
+
The active pack directories are not mutated. Staged roots are validated
|
| 184 |
+
before returning so a successful result is promotable by construction.
|
| 185 |
+
"""
|
| 186 |
+
if not base_export_id.strip():
|
| 187 |
+
raise PackCompactionError("base_export_id must be non-empty")
|
| 188 |
+
wiki_root = Path(wiki_path)
|
| 189 |
+
graph_packs_dir = wiki_root / "graphify-out" / "packs"
|
| 190 |
+
wiki_packs_dir = wiki_root / "wiki-packs"
|
| 191 |
+
stage_root = Path(staging_dir) if staging_dir is not None else (
|
| 192 |
+
wiki_root / "graphify-out" / "pack-compaction-staging" / _pack_id(base_export_id)
|
| 193 |
+
)
|
| 194 |
+
if stage_root.exists():
|
| 195 |
+
raise PackCompactionError(f"staging directory already exists: {stage_root}")
|
| 196 |
+
|
| 197 |
+
staged_graph_packs_dir = stage_root / "graph-packs"
|
| 198 |
+
staged_wiki_packs_dir = stage_root / "wiki-packs"
|
| 199 |
+
manifest_path = stage_root / PACK_COMPACTION_MANIFEST
|
| 200 |
+
pack_id = _pack_id(base_export_id)
|
| 201 |
+
try:
|
| 202 |
+
graph_manifest = compact_graph_packs(
|
| 203 |
+
packs_dir=graph_packs_dir,
|
| 204 |
+
compacted_pack_dir=staged_graph_packs_dir / pack_id,
|
| 205 |
+
base_export_id=base_export_id,
|
| 206 |
+
config_hash=graph_config_hash,
|
| 207 |
+
model_id=graph_model_id,
|
| 208 |
+
created_at=created_at,
|
| 209 |
+
)
|
| 210 |
+
wiki_manifest = compact_wiki_packs(
|
| 211 |
+
packs_dir=wiki_packs_dir,
|
| 212 |
+
compacted_pack_dir=staged_wiki_packs_dir / pack_id,
|
| 213 |
+
base_export_id=base_export_id,
|
| 214 |
+
created_at=created_at,
|
| 215 |
+
)
|
| 216 |
+
result = PackCompactionResult(
|
| 217 |
+
wiki_path=wiki_root,
|
| 218 |
+
staging_dir=stage_root,
|
| 219 |
+
graph_packs_dir=graph_packs_dir,
|
| 220 |
+
wiki_packs_dir=wiki_packs_dir,
|
| 221 |
+
staged_graph_packs_dir=staged_graph_packs_dir,
|
| 222 |
+
staged_wiki_packs_dir=staged_wiki_packs_dir,
|
| 223 |
+
manifest_path=manifest_path,
|
| 224 |
+
graph_manifest=graph_manifest,
|
| 225 |
+
wiki_manifest=wiki_manifest,
|
| 226 |
+
)
|
| 227 |
+
_write_compaction_manifest(result, created_at=created_at)
|
| 228 |
+
_validate_staged_pack_roots(staged_graph_packs_dir, staged_wiki_packs_dir)
|
| 229 |
+
except (GraphPackManifestError, WikiPackManifestError, PackCompactionError, OSError) as exc:
|
| 230 |
+
shutil.rmtree(stage_root, ignore_errors=True)
|
| 231 |
+
raise PackCompactionError(str(exc)) from exc
|
| 232 |
+
|
| 233 |
+
return result
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def promote_staged_pack_sets(
|
| 237 |
+
*,
|
| 238 |
+
wiki_path: Path,
|
| 239 |
+
staged_graph_packs_dir: Path,
|
| 240 |
+
staged_wiki_packs_dir: Path,
|
| 241 |
+
graph_backup_packs_dir: Path | None = None,
|
| 242 |
+
wiki_backup_packs_dir: Path | None = None,
|
| 243 |
+
refresh_graph_store: bool = True,
|
| 244 |
+
graph_store_db_path: Path | None = None,
|
| 245 |
+
) -> PackPromotionResult:
|
| 246 |
+
"""Promote staged graph/wiki pack sets into the active wiki.
|
| 247 |
+
|
| 248 |
+
Both staged roots are validated before any active directory is touched. If
|
| 249 |
+
graph promotion succeeds but wiki promotion fails, the previous graph pack
|
| 250 |
+
directory is restored from the graph backup.
|
| 251 |
+
"""
|
| 252 |
+
wiki_root = Path(wiki_path)
|
| 253 |
+
graph_stage = Path(staged_graph_packs_dir)
|
| 254 |
+
wiki_stage = Path(staged_wiki_packs_dir)
|
| 255 |
+
active_graph_packs = wiki_root / "graphify-out" / "packs"
|
| 256 |
+
active_wiki_packs = wiki_root / "wiki-packs"
|
| 257 |
+
_validate_staged_pack_roots(graph_stage, wiki_stage)
|
| 258 |
+
|
| 259 |
+
graph_result: GraphPackPromotion | None = None
|
| 260 |
+
try:
|
| 261 |
+
graph_result = promote_graph_pack_set(
|
| 262 |
+
staged_packs_dir=graph_stage,
|
| 263 |
+
active_packs_dir=active_graph_packs,
|
| 264 |
+
backup_packs_dir=Path(graph_backup_packs_dir) if graph_backup_packs_dir else None,
|
| 265 |
+
)
|
| 266 |
+
wiki_result = promote_wiki_pack_set(
|
| 267 |
+
staged_packs_dir=wiki_stage,
|
| 268 |
+
active_packs_dir=active_wiki_packs,
|
| 269 |
+
backup_packs_dir=Path(wiki_backup_packs_dir) if wiki_backup_packs_dir else None,
|
| 270 |
+
)
|
| 271 |
+
except (GraphPackManifestError, WikiPackManifestError, OSError) as exc:
|
| 272 |
+
if graph_result is not None:
|
| 273 |
+
_restore_graph_packs_after_partial_promotion(graph_result)
|
| 274 |
+
raise PackCompactionError(str(exc)) from exc
|
| 275 |
+
|
| 276 |
+
graph_store = None
|
| 277 |
+
if refresh_graph_store:
|
| 278 |
+
try:
|
| 279 |
+
graph_store = ensure_graph_store(
|
| 280 |
+
wiki_root / "graphify-out",
|
| 281 |
+
Path(graph_store_db_path) if graph_store_db_path else _default_graph_store_db(wiki_root),
|
| 282 |
+
)
|
| 283 |
+
except (OSError, ValueError) as exc:
|
| 284 |
+
raise PackCompactionError(f"graph store refresh failed: {exc}") from exc
|
| 285 |
+
|
| 286 |
+
return PackPromotionResult(
|
| 287 |
+
wiki_path=wiki_root,
|
| 288 |
+
graph=graph_result,
|
| 289 |
+
wiki=wiki_result,
|
| 290 |
+
graph_store=graph_store,
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def validate_pack_sets(
|
| 295 |
+
*,
|
| 296 |
+
graph_packs_dir: Path,
|
| 297 |
+
wiki_packs_dir: Path,
|
| 298 |
+
require_compaction_manifest: bool = False,
|
| 299 |
+
) -> dict[str, object]:
|
| 300 |
+
"""Validate merged graph/wiki packs without staging or promotion."""
|
| 301 |
+
graph_dir = Path(graph_packs_dir)
|
| 302 |
+
wiki_dir = Path(wiki_packs_dir)
|
| 303 |
+
try:
|
| 304 |
+
if require_compaction_manifest:
|
| 305 |
+
validate_pack_compaction_manifest(
|
| 306 |
+
staged_graph_packs_dir=graph_dir,
|
| 307 |
+
staged_wiki_packs_dir=wiki_dir,
|
| 308 |
+
)
|
| 309 |
+
graph = load_merged_pack_graph(graph_dir)
|
| 310 |
+
pages = load_merged_wiki_pages(wiki_dir)
|
| 311 |
+
except (GraphPackManifestError, WikiPackManifestError, ValueError) as exc:
|
| 312 |
+
raise PackCompactionError(str(exc)) from exc
|
| 313 |
+
|
| 314 |
+
errors: list[str] = []
|
| 315 |
+
if graph.number_of_nodes() == 0:
|
| 316 |
+
errors.append("graph packs do not contain a graph")
|
| 317 |
+
if not pages:
|
| 318 |
+
errors.append("wiki packs do not contain pages")
|
| 319 |
+
consistency = validate_graph_wiki_consistency(graph, pages)
|
| 320 |
+
errors.extend(consistency.errors())
|
| 321 |
+
if errors:
|
| 322 |
+
raise PackCompactionError("graph/wiki pack validation failed: " + "; ".join(errors))
|
| 323 |
+
|
| 324 |
+
pack_ids = graph.graph.get("ctx_pack_ids", [])
|
| 325 |
+
return {
|
| 326 |
+
"graph_packs_dir": str(graph_dir),
|
| 327 |
+
"wiki_packs_dir": str(wiki_dir),
|
| 328 |
+
"graph_nodes": graph.number_of_nodes(),
|
| 329 |
+
"graph_edges": graph.number_of_edges(),
|
| 330 |
+
"wiki_pages": len(pages),
|
| 331 |
+
"graph_pack_ids": pack_ids if isinstance(pack_ids, list) else [],
|
| 332 |
+
"base_export_id": graph.graph.get("ctx_pack_base_export_id"),
|
| 333 |
+
"missing_wiki_pages": len(consistency.missing_wiki_pages),
|
| 334 |
+
"orphan_wiki_pages": len(consistency.orphan_wiki_pages),
|
| 335 |
+
"stale_wiki_links": len(consistency.stale_wiki_links),
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def main(argv: list[str] | None = None) -> int:
|
| 340 |
+
"""CLI for staging coordinated graph/wiki pack compaction."""
|
| 341 |
+
parser = argparse.ArgumentParser(
|
| 342 |
+
prog="python -m ctx.core.wiki.pack_compaction",
|
| 343 |
+
description="Stage compacted ctx graph and LLM-wiki base packs.",
|
| 344 |
+
)
|
| 345 |
+
sub = parser.add_subparsers(dest="command", required=True)
|
| 346 |
+
status = sub.add_parser(
|
| 347 |
+
"status",
|
| 348 |
+
help="Report active graph/wiki overlay counts and compaction readiness.",
|
| 349 |
+
)
|
| 350 |
+
status.add_argument("--wiki-path", required=True, help="Path to the ctx wiki root")
|
| 351 |
+
status.add_argument(
|
| 352 |
+
"--overlay-threshold",
|
| 353 |
+
type=int,
|
| 354 |
+
help="Override graph.pack_compaction.overlay_threshold for this check",
|
| 355 |
+
)
|
| 356 |
+
status.add_argument(
|
| 357 |
+
"--no-validate",
|
| 358 |
+
action="store_true",
|
| 359 |
+
help="Skip merged graph/wiki validation and report counts only",
|
| 360 |
+
)
|
| 361 |
+
status.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
| 362 |
+
compact = sub.add_parser(
|
| 363 |
+
"compact",
|
| 364 |
+
help="Stage compacted graph/wiki base packs without mutating active packs.",
|
| 365 |
+
)
|
| 366 |
+
compact.add_argument("--wiki-path", required=True, help="Path to the ctx wiki root")
|
| 367 |
+
compact.add_argument("--base-export-id", required=True, help="New compacted export id")
|
| 368 |
+
compact.add_argument("--staging-dir", help="Destination staging root")
|
| 369 |
+
compact.add_argument("--graph-config-hash", help="Override graph config hash")
|
| 370 |
+
compact.add_argument("--graph-model-id", help="Override graph model id")
|
| 371 |
+
compact.add_argument("--created-at", help="Optional created_at value for staged manifests")
|
| 372 |
+
compact.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
| 373 |
+
compact_promote = sub.add_parser(
|
| 374 |
+
"compact-promote",
|
| 375 |
+
help="Stage, validate, promote, and refresh graph store in one operation.",
|
| 376 |
+
)
|
| 377 |
+
compact_promote.add_argument("--wiki-path", required=True, help="Path to the ctx wiki root")
|
| 378 |
+
compact_promote.add_argument("--base-export-id", required=True, help="New compacted export id")
|
| 379 |
+
compact_promote.add_argument("--staging-dir", help="Destination staging root")
|
| 380 |
+
compact_promote.add_argument("--graph-config-hash", help="Override graph config hash")
|
| 381 |
+
compact_promote.add_argument("--graph-model-id", help="Override graph model id")
|
| 382 |
+
compact_promote.add_argument("--created-at", help="Optional created_at value for staged manifests")
|
| 383 |
+
compact_promote.add_argument("--graph-backup-packs-dir", help="Optional graph backup directory")
|
| 384 |
+
compact_promote.add_argument("--wiki-backup-packs-dir", help="Optional wiki backup directory")
|
| 385 |
+
compact_promote.add_argument("--graph-store-db", help="Optional SQLite graph store path")
|
| 386 |
+
compact_promote.add_argument(
|
| 387 |
+
"--no-graph-store-refresh",
|
| 388 |
+
action="store_true",
|
| 389 |
+
help="Skip SQLite graph store refresh after pack promotion",
|
| 390 |
+
)
|
| 391 |
+
compact_promote.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
| 392 |
+
promote = sub.add_parser(
|
| 393 |
+
"promote",
|
| 394 |
+
help="Promote validated staged graph/wiki packs into the active wiki.",
|
| 395 |
+
)
|
| 396 |
+
promote.add_argument("--wiki-path", required=True, help="Path to the ctx wiki root")
|
| 397 |
+
promote.add_argument(
|
| 398 |
+
"--staged-graph-packs-dir",
|
| 399 |
+
required=True,
|
| 400 |
+
help="Validated staged graph packs root",
|
| 401 |
+
)
|
| 402 |
+
promote.add_argument(
|
| 403 |
+
"--staged-wiki-packs-dir",
|
| 404 |
+
required=True,
|
| 405 |
+
help="Validated staged wiki packs root",
|
| 406 |
+
)
|
| 407 |
+
promote.add_argument("--graph-backup-packs-dir", help="Optional graph backup directory")
|
| 408 |
+
promote.add_argument("--wiki-backup-packs-dir", help="Optional wiki backup directory")
|
| 409 |
+
promote.add_argument("--graph-store-db", help="Optional SQLite graph store path")
|
| 410 |
+
promote.add_argument(
|
| 411 |
+
"--no-graph-store-refresh",
|
| 412 |
+
action="store_true",
|
| 413 |
+
help="Skip SQLite graph store refresh after pack promotion",
|
| 414 |
+
)
|
| 415 |
+
promote.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
| 416 |
+
validate = sub.add_parser(
|
| 417 |
+
"validate",
|
| 418 |
+
help="Validate active or staged graph/wiki packs without mutating them.",
|
| 419 |
+
)
|
| 420 |
+
validate.add_argument("--wiki-path", help="Path to the ctx wiki root for active packs")
|
| 421 |
+
validate.add_argument("--staged-graph-packs-dir", help="Staged graph packs root")
|
| 422 |
+
validate.add_argument("--staged-wiki-packs-dir", help="Staged wiki packs root")
|
| 423 |
+
validate.add_argument(
|
| 424 |
+
"--require-compaction-manifest",
|
| 425 |
+
action="store_true",
|
| 426 |
+
help="Require and validate pack-compaction-manifest.json beside staged roots",
|
| 427 |
+
)
|
| 428 |
+
validate.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
| 429 |
+
args = parser.parse_args(argv)
|
| 430 |
+
|
| 431 |
+
if args.command == "status":
|
| 432 |
+
try:
|
| 433 |
+
status_result = pack_compaction_status(
|
| 434 |
+
wiki_path=Path(args.wiki_path),
|
| 435 |
+
overlay_threshold=args.overlay_threshold,
|
| 436 |
+
validate=not args.no_validate,
|
| 437 |
+
)
|
| 438 |
+
except PackCompactionError as exc:
|
| 439 |
+
print(f"error: {exc}", file=sys.stderr)
|
| 440 |
+
return 1
|
| 441 |
+
if args.json:
|
| 442 |
+
print(json.dumps(status_result, indent=2, sort_keys=True))
|
| 443 |
+
else:
|
| 444 |
+
state = "recommended" if status_result["needs_compaction"] else "not needed"
|
| 445 |
+
print(
|
| 446 |
+
"graph/wiki pack compaction status: "
|
| 447 |
+
f"{status_result['max_overlay_count']} overlays "
|
| 448 |
+
f"(threshold {status_result['overlay_threshold']}); "
|
| 449 |
+
f"compaction {state}"
|
| 450 |
+
)
|
| 451 |
+
return 0
|
| 452 |
+
if args.command == "compact":
|
| 453 |
+
try:
|
| 454 |
+
compact_result = compact_active_pack_sets(
|
| 455 |
+
wiki_path=Path(args.wiki_path),
|
| 456 |
+
base_export_id=args.base_export_id,
|
| 457 |
+
staging_dir=Path(args.staging_dir) if args.staging_dir else None,
|
| 458 |
+
graph_config_hash=args.graph_config_hash,
|
| 459 |
+
graph_model_id=args.graph_model_id,
|
| 460 |
+
created_at=args.created_at,
|
| 461 |
+
)
|
| 462 |
+
except PackCompactionError as exc:
|
| 463 |
+
print(f"error: {exc}", file=sys.stderr)
|
| 464 |
+
return 1
|
| 465 |
+
payload = compact_result.to_mapping()
|
| 466 |
+
if args.json:
|
| 467 |
+
print(json.dumps(payload, indent=2, sort_keys=True))
|
| 468 |
+
else:
|
| 469 |
+
print(
|
| 470 |
+
"staged graph/wiki compaction: "
|
| 471 |
+
f"{compact_result.graph_manifest.node_count} graph nodes, "
|
| 472 |
+
f"{compact_result.graph_manifest.edge_count} graph edges, "
|
| 473 |
+
f"{compact_result.wiki_manifest.page_count} wiki pages"
|
| 474 |
+
)
|
| 475 |
+
return 0
|
| 476 |
+
if args.command == "compact-promote":
|
| 477 |
+
try:
|
| 478 |
+
compact_result = compact_active_pack_sets(
|
| 479 |
+
wiki_path=Path(args.wiki_path),
|
| 480 |
+
base_export_id=args.base_export_id,
|
| 481 |
+
staging_dir=Path(args.staging_dir) if args.staging_dir else None,
|
| 482 |
+
graph_config_hash=args.graph_config_hash,
|
| 483 |
+
graph_model_id=args.graph_model_id,
|
| 484 |
+
created_at=args.created_at,
|
| 485 |
+
)
|
| 486 |
+
promotion_result = promote_staged_pack_sets(
|
| 487 |
+
wiki_path=Path(args.wiki_path),
|
| 488 |
+
staged_graph_packs_dir=compact_result.staged_graph_packs_dir,
|
| 489 |
+
staged_wiki_packs_dir=compact_result.staged_wiki_packs_dir,
|
| 490 |
+
graph_backup_packs_dir=(
|
| 491 |
+
Path(args.graph_backup_packs_dir)
|
| 492 |
+
if args.graph_backup_packs_dir
|
| 493 |
+
else None
|
| 494 |
+
),
|
| 495 |
+
wiki_backup_packs_dir=(
|
| 496 |
+
Path(args.wiki_backup_packs_dir)
|
| 497 |
+
if args.wiki_backup_packs_dir
|
| 498 |
+
else None
|
| 499 |
+
),
|
| 500 |
+
refresh_graph_store=not args.no_graph_store_refresh,
|
| 501 |
+
graph_store_db_path=Path(args.graph_store_db) if args.graph_store_db else None,
|
| 502 |
+
)
|
| 503 |
+
except PackCompactionError as exc:
|
| 504 |
+
print(f"error: {exc}", file=sys.stderr)
|
| 505 |
+
return 1
|
| 506 |
+
payload = {
|
| 507 |
+
"compaction": compact_result.to_mapping(),
|
| 508 |
+
"promotion": promotion_result.to_mapping(),
|
| 509 |
+
}
|
| 510 |
+
if args.json:
|
| 511 |
+
print(json.dumps(payload, indent=2, sort_keys=True))
|
| 512 |
+
else:
|
| 513 |
+
print(
|
| 514 |
+
"compacted and promoted graph/wiki packs: "
|
| 515 |
+
f"{', '.join(promotion_result.graph.promoted_pack_ids)} / "
|
| 516 |
+
f"{', '.join(promotion_result.wiki.promoted_pack_ids)}"
|
| 517 |
+
)
|
| 518 |
+
return 0
|
| 519 |
+
if args.command == "promote":
|
| 520 |
+
try:
|
| 521 |
+
promotion_result = promote_staged_pack_sets(
|
| 522 |
+
wiki_path=Path(args.wiki_path),
|
| 523 |
+
staged_graph_packs_dir=Path(args.staged_graph_packs_dir),
|
| 524 |
+
staged_wiki_packs_dir=Path(args.staged_wiki_packs_dir),
|
| 525 |
+
graph_backup_packs_dir=(
|
| 526 |
+
Path(args.graph_backup_packs_dir)
|
| 527 |
+
if args.graph_backup_packs_dir
|
| 528 |
+
else None
|
| 529 |
+
),
|
| 530 |
+
wiki_backup_packs_dir=(
|
| 531 |
+
Path(args.wiki_backup_packs_dir)
|
| 532 |
+
if args.wiki_backup_packs_dir
|
| 533 |
+
else None
|
| 534 |
+
),
|
| 535 |
+
refresh_graph_store=not args.no_graph_store_refresh,
|
| 536 |
+
graph_store_db_path=Path(args.graph_store_db) if args.graph_store_db else None,
|
| 537 |
+
)
|
| 538 |
+
except PackCompactionError as exc:
|
| 539 |
+
print(f"error: {exc}", file=sys.stderr)
|
| 540 |
+
return 1
|
| 541 |
+
payload = promotion_result.to_mapping()
|
| 542 |
+
if args.json:
|
| 543 |
+
print(json.dumps(payload, indent=2, sort_keys=True))
|
| 544 |
+
else:
|
| 545 |
+
print(
|
| 546 |
+
"promoted graph/wiki packs: "
|
| 547 |
+
f"{', '.join(promotion_result.graph.promoted_pack_ids)} / "
|
| 548 |
+
f"{', '.join(promotion_result.wiki.promoted_pack_ids)}"
|
| 549 |
+
)
|
| 550 |
+
return 0
|
| 551 |
+
if args.command == "validate":
|
| 552 |
+
try:
|
| 553 |
+
if args.staged_graph_packs_dir or args.staged_wiki_packs_dir:
|
| 554 |
+
if not args.staged_graph_packs_dir or not args.staged_wiki_packs_dir:
|
| 555 |
+
parser.error("--staged-graph-packs-dir and --staged-wiki-packs-dir are required together")
|
| 556 |
+
graph_packs_dir = Path(args.staged_graph_packs_dir)
|
| 557 |
+
wiki_packs_dir = Path(args.staged_wiki_packs_dir)
|
| 558 |
+
elif args.wiki_path:
|
| 559 |
+
wiki_root = Path(args.wiki_path)
|
| 560 |
+
graph_packs_dir = wiki_root / "graphify-out" / "packs"
|
| 561 |
+
wiki_packs_dir = wiki_root / "wiki-packs"
|
| 562 |
+
else:
|
| 563 |
+
parser.error("validate requires --wiki-path or both staged pack dirs")
|
| 564 |
+
validation_result = validate_pack_sets(
|
| 565 |
+
graph_packs_dir=graph_packs_dir,
|
| 566 |
+
wiki_packs_dir=wiki_packs_dir,
|
| 567 |
+
require_compaction_manifest=args.require_compaction_manifest,
|
| 568 |
+
)
|
| 569 |
+
except PackCompactionError as exc:
|
| 570 |
+
print(f"error: {exc}", file=sys.stderr)
|
| 571 |
+
return 1
|
| 572 |
+
if args.json:
|
| 573 |
+
print(json.dumps(validation_result, indent=2, sort_keys=True))
|
| 574 |
+
else:
|
| 575 |
+
print(
|
| 576 |
+
"validated graph/wiki packs: "
|
| 577 |
+
f"{validation_result['graph_nodes']} graph nodes, "
|
| 578 |
+
f"{validation_result['graph_edges']} graph edges, "
|
| 579 |
+
f"{validation_result['wiki_pages']} wiki pages"
|
| 580 |
+
)
|
| 581 |
+
return 0
|
| 582 |
+
return 1
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def _pack_id(base_export_id: str) -> str:
|
| 586 |
+
value = base_export_id.strip()
|
| 587 |
+
return value if value.startswith("base-") else f"base-{value}"
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def _default_overlay_threshold() -> int:
|
| 591 |
+
from ctx_config import cfg # noqa: PLC0415
|
| 592 |
+
|
| 593 |
+
return int(cfg.graph_pack_compaction_overlay_threshold)
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
def _normalise_overlay_threshold(value: int) -> int:
|
| 597 |
+
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
|
| 598 |
+
raise PackCompactionError(
|
| 599 |
+
"overlay_threshold must be an integer >= 1 "
|
| 600 |
+
f"(got {value!r})"
|
| 601 |
+
)
|
| 602 |
+
return value
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
def _overlay_count(entries: Iterable[GraphPackEntry | WikiPackEntry]) -> int:
|
| 606 |
+
return sum(1 for entry in entries if entry.manifest.pack_type == "overlay")
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
def _default_graph_store_db(wiki_path: Path) -> Path:
|
| 610 |
+
return wiki_path / "graphify-out" / "graph-store.sqlite3"
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
def _write_compaction_manifest(
|
| 614 |
+
result: PackCompactionResult,
|
| 615 |
+
*,
|
| 616 |
+
created_at: str | None,
|
| 617 |
+
) -> None:
|
| 618 |
+
payload = result.to_mapping()
|
| 619 |
+
payload["created_at"] = created_at or datetime.now(UTC).isoformat()
|
| 620 |
+
atomic_write_text(
|
| 621 |
+
result.manifest_path,
|
| 622 |
+
json.dumps(payload, indent=2, sort_keys=True) + "\n",
|
| 623 |
+
encoding="utf-8",
|
| 624 |
+
)
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def _validate_staged_pack_roots(
|
| 628 |
+
staged_graph_packs_dir: Path,
|
| 629 |
+
staged_wiki_packs_dir: Path,
|
| 630 |
+
) -> None:
|
| 631 |
+
validate_pack_sets(
|
| 632 |
+
graph_packs_dir=staged_graph_packs_dir,
|
| 633 |
+
wiki_packs_dir=staged_wiki_packs_dir,
|
| 634 |
+
require_compaction_manifest=True,
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
def _restore_graph_packs_after_partial_promotion(result: GraphPackPromotion) -> None:
|
| 639 |
+
active = result.active_packs_dir
|
| 640 |
+
backup = result.backup_packs_dir
|
| 641 |
+
_remove_path(active)
|
| 642 |
+
if backup is not None and backup.exists():
|
| 643 |
+
backup.replace(active)
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
def _remove_path(path: Path) -> None:
|
| 647 |
+
if path.is_dir():
|
| 648 |
+
shutil.rmtree(path)
|
| 649 |
+
elif path.exists():
|
| 650 |
+
path.unlink()
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
if __name__ == "__main__": # pragma: no cover
|
| 654 |
+
raise SystemExit(main())
|
src/ctx/core/wiki/pack_validation.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Validation gates for modular graph/wiki pack promotion."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import re
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import networkx as nx
|
| 12 |
+
|
| 13 |
+
from ctx.core.entity_types import RECOMMENDABLE_ENTITY_TYPES, entity_relpath
|
| 14 |
+
from ctx.core.graph.graph_packs import GraphPackManifestError, discover_pack_manifests
|
| 15 |
+
from ctx.core.wiki.wiki_packs import WikiPackManifestError, discover_wiki_pack_manifests
|
| 16 |
+
|
| 17 |
+
PACK_COMPACTION_MANIFEST = "pack-compaction-manifest.json"
|
| 18 |
+
PACK_COMPACTION_SCHEMA_VERSION = 1
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass(frozen=True)
|
| 22 |
+
class GraphWikiConsistencyReport:
|
| 23 |
+
"""Graph/wiki consistency report for one merged pack view."""
|
| 24 |
+
|
| 25 |
+
missing_wiki_pages: list[dict[str, object]]
|
| 26 |
+
orphan_wiki_pages: list[dict[str, str]]
|
| 27 |
+
stale_wiki_links: list[dict[str, str]]
|
| 28 |
+
|
| 29 |
+
@property
|
| 30 |
+
def ok(self) -> bool:
|
| 31 |
+
"""Return whether the merged graph and wiki entity views agree."""
|
| 32 |
+
return (
|
| 33 |
+
not self.missing_wiki_pages
|
| 34 |
+
and not self.orphan_wiki_pages
|
| 35 |
+
and not self.stale_wiki_links
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
def errors(self) -> list[str]:
|
| 39 |
+
"""Return human-readable validation errors."""
|
| 40 |
+
errors: list[str] = []
|
| 41 |
+
if self.missing_wiki_pages:
|
| 42 |
+
errors.append(f"missing wiki pages: {len(self.missing_wiki_pages)}")
|
| 43 |
+
if self.orphan_wiki_pages:
|
| 44 |
+
errors.append(f"orphan wiki pages: {len(self.orphan_wiki_pages)}")
|
| 45 |
+
if self.stale_wiki_links:
|
| 46 |
+
errors.append(f"stale wiki links: {len(self.stale_wiki_links)}")
|
| 47 |
+
return errors
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def validate_graph_wiki_consistency(
|
| 51 |
+
graph: nx.Graph,
|
| 52 |
+
pages: dict[str, str],
|
| 53 |
+
) -> GraphWikiConsistencyReport:
|
| 54 |
+
"""Validate known graph entity nodes against merged wiki entity pages."""
|
| 55 |
+
normalised_pages = {_normalise_relpath(path) for path in pages}
|
| 56 |
+
graph_nodes = _graph_entity_nodes(graph)
|
| 57 |
+
missing: list[dict[str, object]] = []
|
| 58 |
+
for node_id, entity_type, slug in graph_nodes:
|
| 59 |
+
expected_paths = _entity_page_candidates(entity_type, slug)
|
| 60 |
+
if expected_paths & normalised_pages:
|
| 61 |
+
continue
|
| 62 |
+
missing.append({
|
| 63 |
+
"node_id": node_id,
|
| 64 |
+
"expected_paths": sorted(expected_paths),
|
| 65 |
+
})
|
| 66 |
+
graph_node_ids = {node_id for node_id, _entity_type, _slug in graph_nodes}
|
| 67 |
+
orphan_pages = [
|
| 68 |
+
{"path": page, "expected_node_id": node_id}
|
| 69 |
+
for page in sorted(normalised_pages)
|
| 70 |
+
for node_id in [_node_id_for_entity_page(page)]
|
| 71 |
+
if node_id is not None and node_id not in graph_node_ids
|
| 72 |
+
]
|
| 73 |
+
return GraphWikiConsistencyReport(
|
| 74 |
+
missing_wiki_pages=missing,
|
| 75 |
+
orphan_wiki_pages=orphan_pages,
|
| 76 |
+
stale_wiki_links=_stale_entity_wikilinks(pages, normalised_pages, graph_node_ids),
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def validate_pack_compaction_manifest(
|
| 81 |
+
*,
|
| 82 |
+
staged_graph_packs_dir: Path,
|
| 83 |
+
staged_wiki_packs_dir: Path,
|
| 84 |
+
) -> dict[str, object]:
|
| 85 |
+
"""Validate the top-level manifest tying staged graph/wiki packs together."""
|
| 86 |
+
graph_dir = Path(staged_graph_packs_dir)
|
| 87 |
+
wiki_dir = Path(staged_wiki_packs_dir)
|
| 88 |
+
if graph_dir.parent != wiki_dir.parent:
|
| 89 |
+
raise ValueError("staged graph/wiki pack dirs must share one staging root")
|
| 90 |
+
manifest_path = graph_dir.parent / PACK_COMPACTION_MANIFEST
|
| 91 |
+
if not manifest_path.is_file():
|
| 92 |
+
raise ValueError(f"{PACK_COMPACTION_MANIFEST} is missing")
|
| 93 |
+
try:
|
| 94 |
+
payload = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 95 |
+
except json.JSONDecodeError as exc:
|
| 96 |
+
raise ValueError(f"{PACK_COMPACTION_MANIFEST} is not valid JSON: {exc}") from exc
|
| 97 |
+
if not isinstance(payload, dict):
|
| 98 |
+
raise ValueError(f"{PACK_COMPACTION_MANIFEST} must contain an object")
|
| 99 |
+
if payload.get("schema_version") != PACK_COMPACTION_SCHEMA_VERSION:
|
| 100 |
+
raise ValueError("pack compaction manifest schema_version is not supported")
|
| 101 |
+
if payload.get("operation") != "pack-compaction-stage":
|
| 102 |
+
raise ValueError("pack compaction manifest operation is not pack-compaction-stage")
|
| 103 |
+
_require_path(payload, "staged_graph_packs_dir", graph_dir)
|
| 104 |
+
_require_path(payload, "staged_wiki_packs_dir", wiki_dir)
|
| 105 |
+
base_export_id = _require_str(payload, "base_export_id")
|
| 106 |
+
graph_section = _require_mapping(payload, "graph")
|
| 107 |
+
wiki_section = _require_mapping(payload, "wiki")
|
| 108 |
+
if graph_section.get("base_export_id") != base_export_id:
|
| 109 |
+
raise ValueError("graph base_export_id does not match compaction manifest")
|
| 110 |
+
if wiki_section.get("base_export_id") != base_export_id:
|
| 111 |
+
raise ValueError("wiki base_export_id does not match compaction manifest")
|
| 112 |
+
if graph_section != _single_graph_manifest(graph_dir):
|
| 113 |
+
raise ValueError("graph manifest does not match staged graph base pack")
|
| 114 |
+
if wiki_section != _single_wiki_manifest(wiki_dir):
|
| 115 |
+
raise ValueError("wiki manifest does not match staged wiki base pack")
|
| 116 |
+
return payload
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _single_graph_manifest(graph_dir: Path) -> dict[str, object]:
|
| 120 |
+
try:
|
| 121 |
+
entries = discover_pack_manifests(graph_dir)
|
| 122 |
+
except GraphPackManifestError as exc:
|
| 123 |
+
raise ValueError(f"staged graph packs are invalid: {exc}") from exc
|
| 124 |
+
if len(entries) != 1 or entries[0].manifest.pack_type != "base":
|
| 125 |
+
raise ValueError("staged graph packs must contain exactly one base pack")
|
| 126 |
+
return entries[0].manifest.to_mapping()
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _single_wiki_manifest(wiki_dir: Path) -> dict[str, object]:
|
| 130 |
+
try:
|
| 131 |
+
entries = discover_wiki_pack_manifests(wiki_dir)
|
| 132 |
+
except WikiPackManifestError as exc:
|
| 133 |
+
raise ValueError(f"staged wiki packs are invalid: {exc}") from exc
|
| 134 |
+
if len(entries) != 1 or entries[0].manifest.pack_type != "base":
|
| 135 |
+
raise ValueError("staged wiki packs must contain exactly one base pack")
|
| 136 |
+
return entries[0].manifest.to_mapping()
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _graph_entity_nodes(graph: nx.Graph) -> list[tuple[str, str, str]]:
|
| 140 |
+
nodes: list[tuple[str, str, str]] = []
|
| 141 |
+
for raw_node_id, attrs in graph.nodes(data=True):
|
| 142 |
+
if not isinstance(raw_node_id, str):
|
| 143 |
+
continue
|
| 144 |
+
parsed = _node_parts(raw_node_id, attrs)
|
| 145 |
+
if parsed is not None:
|
| 146 |
+
nodes.append((raw_node_id, *parsed))
|
| 147 |
+
return sorted(nodes)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _node_parts(node_id: str, attrs: dict[str, Any]) -> tuple[str, str] | None:
|
| 151 |
+
if ":" not in node_id:
|
| 152 |
+
return None
|
| 153 |
+
entity_type, slug = node_id.split(":", 1)
|
| 154 |
+
if entity_type not in RECOMMENDABLE_ENTITY_TYPES or not slug:
|
| 155 |
+
return None
|
| 156 |
+
attr_type = attrs.get("type")
|
| 157 |
+
if isinstance(attr_type, str) and attr_type in RECOMMENDABLE_ENTITY_TYPES:
|
| 158 |
+
entity_type = attr_type
|
| 159 |
+
return entity_type, slug
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _entity_page_candidates(entity_type: str, slug: str) -> set[str]:
|
| 163 |
+
relpath = entity_relpath(entity_type, slug)
|
| 164 |
+
candidates = {_normalise_relpath(relpath.as_posix())} if relpath is not None else set()
|
| 165 |
+
if entity_type == "mcp-server":
|
| 166 |
+
candidates.add(f"entities/mcp-servers/{slug}.md")
|
| 167 |
+
return candidates
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _node_id_for_entity_page(relpath: str) -> str | None:
|
| 171 |
+
parts = _pure_parts(relpath)
|
| 172 |
+
if len(parts) < 3 or parts[0] != "entities":
|
| 173 |
+
return None
|
| 174 |
+
subject = parts[1]
|
| 175 |
+
filename = parts[-1]
|
| 176 |
+
if not filename.endswith(".md"):
|
| 177 |
+
return None
|
| 178 |
+
slug = filename[:-3]
|
| 179 |
+
if subject == "skills" and len(parts) == 3:
|
| 180 |
+
return f"skill:{slug}"
|
| 181 |
+
if subject == "agents" and len(parts) == 3:
|
| 182 |
+
return f"agent:{slug}"
|
| 183 |
+
if subject == "harnesses" and len(parts) == 3:
|
| 184 |
+
return f"harness:{slug}"
|
| 185 |
+
if subject == "mcp-servers" and len(parts) in {3, 4}:
|
| 186 |
+
return f"mcp-server:{slug}"
|
| 187 |
+
return None
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
_WIKILINK_RE = re.compile(r"\[\[([^\]|#]+)(?:#[^\]|]*)?(?:\|[^\]]*)?\]\]")
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def _stale_entity_wikilinks(
|
| 194 |
+
pages: dict[str, str],
|
| 195 |
+
known_pages: set[str],
|
| 196 |
+
known_node_ids: set[str],
|
| 197 |
+
) -> list[dict[str, str]]:
|
| 198 |
+
stale: list[dict[str, str]] = []
|
| 199 |
+
seen: set[tuple[str, str, str]] = set()
|
| 200 |
+
for source_path, text in sorted(pages.items()):
|
| 201 |
+
normalised_source = _normalise_relpath(source_path)
|
| 202 |
+
for match in _WIKILINK_RE.finditer(text):
|
| 203 |
+
target = _normalise_wikilink_target(match.group(1))
|
| 204 |
+
node_id = _node_id_for_entity_page(target)
|
| 205 |
+
if node_id is None:
|
| 206 |
+
continue
|
| 207 |
+
if target not in known_pages:
|
| 208 |
+
reason = "missing page"
|
| 209 |
+
elif node_id not in known_node_ids:
|
| 210 |
+
reason = "missing graph node"
|
| 211 |
+
else:
|
| 212 |
+
continue
|
| 213 |
+
key = (normalised_source, target, reason)
|
| 214 |
+
if key in seen:
|
| 215 |
+
continue
|
| 216 |
+
seen.add(key)
|
| 217 |
+
stale.append({
|
| 218 |
+
"source_path": normalised_source,
|
| 219 |
+
"target": target,
|
| 220 |
+
"expected_node_id": node_id,
|
| 221 |
+
"reason": reason,
|
| 222 |
+
})
|
| 223 |
+
return stale
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def _normalise_wikilink_target(target: str) -> str:
|
| 227 |
+
relpath = _normalise_relpath(target)
|
| 228 |
+
return relpath if relpath.endswith(".md") else f"{relpath}.md"
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def _normalise_relpath(path: str) -> str:
|
| 232 |
+
return path.replace("\\", "/").strip("/")
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def _pure_parts(path: str) -> tuple[str, ...]:
|
| 236 |
+
"""Return POSIX parts without touching the local filesystem."""
|
| 237 |
+
return tuple(part for part in path.replace("\\", "/").split("/") if part)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _require_str(payload: dict[str, object], key: str) -> str:
|
| 241 |
+
value = payload.get(key)
|
| 242 |
+
if not isinstance(value, str) or not value:
|
| 243 |
+
raise ValueError(f"pack compaction manifest {key} must be a non-empty string")
|
| 244 |
+
return value
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def _require_mapping(payload: dict[str, object], key: str) -> dict[str, object]:
|
| 248 |
+
value = payload.get(key)
|
| 249 |
+
if not isinstance(value, dict):
|
| 250 |
+
raise ValueError(f"pack compaction manifest {key} must be an object")
|
| 251 |
+
return value
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def _require_path(payload: dict[str, object], key: str, expected: Path) -> None:
|
| 255 |
+
raw_value = _require_str(payload, key)
|
| 256 |
+
if not _same_path(Path(raw_value), expected):
|
| 257 |
+
raise ValueError(f"pack compaction manifest {key} does not match staged path")
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def _same_path(left: Path, right: Path) -> bool:
|
| 261 |
+
try:
|
| 262 |
+
return left.resolve() == right.resolve()
|
| 263 |
+
except OSError:
|
| 264 |
+
return left.absolute() == right.absolute()
|