Sync ctx 03af985 (part 3)
Browse filesGitHub commit: 03af985401f8dd95b559ecb86c10322a86d14af5
This view is limited to 50 files because it contains too many changes. See raw diff
- src/link_conversions.py +45 -14
- src/mcp_add.py +128 -13
- src/mcp_canonical_index.py +45 -12
- src/mcp_enrich.py +109 -11
- src/mcp_quality.py +103 -39
- src/mcp_rebuild_index.py +21 -48
- src/scan_repo.py +33 -15
- src/skill_add.py +164 -24
- src/skill_telemetry.py +96 -2
- src/tests/conftest.py +29 -0
- src/tests/test_agent_add.py +35 -2
- src/tests/test_catalog_builder.py +34 -0
- src/tests/test_ci_classifier.py +92 -0
- src/tests/test_clean_host_contract.py +1 -0
- src/tests/test_context_monitor.py +37 -0
- src/tests/test_ctx_init.py +243 -4
- src/tests/test_ctx_monitor.py +0 -0
- src/tests/test_ctx_monitor_3type.py +190 -96
- src/tests/test_ctx_monitor_browser.py +472 -18
- src/tests/test_dashboard_entities.py +81 -0
- src/tests/test_dashboard_smoke.py +107 -0
- src/tests/test_dashboard_user_story_tracker.py +83 -0
- src/tests/test_dedup_check.py +51 -0
- src/tests/test_docs_catalog_page.py +6 -6
- src/tests/test_enterprise_telemetry.py +2000 -0
- src/tests/test_feature_user_story_tracker.py +235 -0
- src/tests/test_graph_packs.py +830 -0
- src/tests/test_graph_store.py +611 -0
- src/tests/test_harness_add.py +44 -2
- src/tests/test_harness_cli_run.py +323 -2
- src/tests/test_harness_ctx_core.py +350 -0
- src/tests/test_harness_install.py +29 -0
- src/tests/test_harness_recommendations.py +146 -0
- src/tests/test_huggingface_sync.py +60 -21
- src/tests/test_incremental_attach_az_flow.py +6 -6
- src/tests/test_incremental_attach_calibration.py +252 -0
- src/tests/test_incremental_attach_shadow.py +37 -0
- src/tests/test_link_conversions.py +26 -0
- src/tests/test_lint.py +55 -1
- src/tests/test_maintainer_script_bom_inputs.py +91 -0
- src/tests/test_mcp_add.py +208 -10
- src/tests/test_mcp_canonical_index.py +37 -0
- src/tests/test_mcp_enrich_render_scalar.py +45 -0
- src/tests/test_mcp_quality.py +81 -0
- src/tests/test_mcp_server.py +75 -0
- src/tests/test_monitor_testing_api.py +13 -0
- src/tests/test_pack_compaction.py +621 -0
- src/tests/test_pack_full_wiki_tar.py +75 -0
- src/tests/test_pack_validation.py +63 -0
- src/tests/test_package_scaffold.py +11 -0
src/link_conversions.py
CHANGED
|
@@ -22,6 +22,7 @@ from dataclasses import dataclass, field
|
|
| 22 |
from datetime import datetime, timezone
|
| 23 |
from pathlib import Path
|
| 24 |
|
|
|
|
| 25 |
from ctx_config import cfg
|
| 26 |
from ctx.core.wiki.wiki_utils import get_field as _find_field
|
| 27 |
|
|
@@ -58,6 +59,36 @@ _FM_PATTERN = re.compile(r"^---\r?\n(.*?\r?\n)---\r?\n", re.DOTALL)
|
|
| 58 |
_FIELD_PATTERN_TMPL = r"^{key}:\s*(.+)$"
|
| 59 |
|
| 60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
def _set_field(content: str, key: str, value: str) -> str:
|
| 63 |
"""Set or add a frontmatter field. Adds before the closing --- if not present."""
|
|
@@ -202,13 +233,15 @@ def upsert_entity_page(
|
|
| 202 |
skills_dir: Path,
|
| 203 |
) -> bool:
|
| 204 |
"""Create or update a skill entity page. Returns True if a new page was created."""
|
| 205 |
-
|
| 206 |
-
|
| 207 |
|
| 208 |
-
if
|
|
|
|
| 209 |
content = _build_new_entity_page(skill, skills_dir)
|
| 210 |
else:
|
| 211 |
-
|
|
|
|
| 212 |
content = _inject_pipeline_fields(content, skill.pipeline_path)
|
| 213 |
# Bump updated date
|
| 214 |
old_updated = _find_field(content, "updated")
|
|
@@ -220,7 +253,7 @@ def upsert_entity_page(
|
|
| 220 |
flags=re.MULTILINE,
|
| 221 |
)
|
| 222 |
|
| 223 |
-
|
| 224 |
return is_new
|
| 225 |
|
| 226 |
|
|
@@ -234,8 +267,9 @@ def update_index(wiki: Path, new_skills: list[str]) -> None:
|
|
| 234 |
if not new_skills:
|
| 235 |
return
|
| 236 |
|
| 237 |
-
|
| 238 |
-
content
|
|
|
|
| 239 |
lines = content.split("\n")
|
| 240 |
|
| 241 |
# Locate the ## Skills insertion point
|
|
@@ -273,7 +307,7 @@ def update_index(wiki: Path, new_skills: list[str]) -> None:
|
|
| 273 |
lines[i] = re.sub(r"Last updated: [\d-]+", f"Last updated: {TODAY}", lines[i])
|
| 274 |
break
|
| 275 |
|
| 276 |
-
|
| 277 |
|
| 278 |
|
| 279 |
# ---------------------------------------------------------------------------
|
|
@@ -283,13 +317,12 @@ def update_index(wiki: Path, new_skills: list[str]) -> None:
|
|
| 283 |
|
| 284 |
def append_log(wiki: Path, action: str, subject: str, details: list[str]) -> None:
|
| 285 |
"""Append a structured entry to log.md."""
|
| 286 |
-
log_path = wiki / "log.md"
|
| 287 |
lines = [f"\n## [{TODAY}] {action} | {subject}"]
|
| 288 |
lines.extend(f"- {d}" for d in details)
|
| 289 |
entry = "\n".join(lines) + "\n"
|
| 290 |
|
| 291 |
-
|
| 292 |
-
|
| 293 |
|
| 294 |
|
| 295 |
# ---------------------------------------------------------------------------
|
|
@@ -299,8 +332,6 @@ def append_log(wiki: Path, action: str, subject: str, details: list[str]) -> Non
|
|
| 299 |
|
| 300 |
def generate_converted_index(wiki: Path, skills: list[ConvertedSkill]) -> None:
|
| 301 |
"""Generate converted-index.md listing every converted skill."""
|
| 302 |
-
out_path = wiki / "converted-index.md"
|
| 303 |
-
|
| 304 |
header = (
|
| 305 |
f"# Converted Micro-Skill Pipelines Index\n"
|
| 306 |
f"\n"
|
|
@@ -320,7 +351,7 @@ def generate_converted_index(wiki: Path, skills: list[ConvertedSkill]) -> None:
|
|
| 320 |
rows.append(f"| {skill.name} | {entity_link} | {pipeline_link} |")
|
| 321 |
|
| 322 |
content = header + "\n".join(rows) + "\n"
|
| 323 |
-
|
| 324 |
print(f" converted-index.md written ({len(skills)} entries)")
|
| 325 |
|
| 326 |
|
|
|
|
| 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 |
from ctx.core.wiki.wiki_utils import get_field as _find_field
|
| 28 |
|
|
|
|
| 59 |
_FIELD_PATTERN_TMPL = r"^{key}:\s*(.+)$"
|
| 60 |
|
| 61 |
|
| 62 |
+
def _read_wiki_page(wiki: Path, relpath: str) -> str | None:
|
| 63 |
+
"""Read a wiki page from active packs when installed, else from disk."""
|
| 64 |
+
packs_dir = wiki / "wiki-packs"
|
| 65 |
+
path = wiki / relpath
|
| 66 |
+
if packs_dir.is_dir():
|
| 67 |
+
pages = load_merged_wiki_pages(packs_dir)
|
| 68 |
+
if relpath in pages:
|
| 69 |
+
return pages[relpath]
|
| 70 |
+
if path.exists():
|
| 71 |
+
return path.read_text(encoding="utf-8", errors="replace")
|
| 72 |
+
return None
|
| 73 |
+
if not path.exists():
|
| 74 |
+
return None
|
| 75 |
+
return path.read_text(encoding="utf-8", errors="replace")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _write_wiki_page(wiki: Path, relpath: str, content: str) -> None:
|
| 79 |
+
"""Write a wiki page, mirroring into overlay packs when installed."""
|
| 80 |
+
packs_dir = wiki / "wiki-packs"
|
| 81 |
+
path = wiki / relpath
|
| 82 |
+
if path.exists() or not packs_dir.is_dir():
|
| 83 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 84 |
+
path.write_text(content, encoding="utf-8")
|
| 85 |
+
if packs_dir.is_dir():
|
| 86 |
+
write_active_wiki_overlay_pack(
|
| 87 |
+
packs_dir=packs_dir,
|
| 88 |
+
pages={relpath: content},
|
| 89 |
+
tombstones=[],
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
|
| 93 |
def _set_field(content: str, key: str, value: str) -> str:
|
| 94 |
"""Set or add a frontmatter field. Adds before the closing --- if not present."""
|
|
|
|
| 233 |
skills_dir: Path,
|
| 234 |
) -> bool:
|
| 235 |
"""Create or update a skill entity page. Returns True if a new page was created."""
|
| 236 |
+
relpath = f"entities/skills/{skill.name}.md"
|
| 237 |
+
existing = _read_wiki_page(wiki, relpath)
|
| 238 |
|
| 239 |
+
if existing is None:
|
| 240 |
+
is_new = True
|
| 241 |
content = _build_new_entity_page(skill, skills_dir)
|
| 242 |
else:
|
| 243 |
+
is_new = False
|
| 244 |
+
content = existing
|
| 245 |
content = _inject_pipeline_fields(content, skill.pipeline_path)
|
| 246 |
# Bump updated date
|
| 247 |
old_updated = _find_field(content, "updated")
|
|
|
|
| 253 |
flags=re.MULTILINE,
|
| 254 |
)
|
| 255 |
|
| 256 |
+
_write_wiki_page(wiki, relpath, content)
|
| 257 |
return is_new
|
| 258 |
|
| 259 |
|
|
|
|
| 267 |
if not new_skills:
|
| 268 |
return
|
| 269 |
|
| 270 |
+
content = _read_wiki_page(wiki, "index.md")
|
| 271 |
+
if content is None:
|
| 272 |
+
return
|
| 273 |
lines = content.split("\n")
|
| 274 |
|
| 275 |
# Locate the ## Skills insertion point
|
|
|
|
| 307 |
lines[i] = re.sub(r"Last updated: [\d-]+", f"Last updated: {TODAY}", lines[i])
|
| 308 |
break
|
| 309 |
|
| 310 |
+
_write_wiki_page(wiki, "index.md", "\n".join(lines))
|
| 311 |
|
| 312 |
|
| 313 |
# ---------------------------------------------------------------------------
|
|
|
|
| 317 |
|
| 318 |
def append_log(wiki: Path, action: str, subject: str, details: list[str]) -> None:
|
| 319 |
"""Append a structured entry to log.md."""
|
|
|
|
| 320 |
lines = [f"\n## [{TODAY}] {action} | {subject}"]
|
| 321 |
lines.extend(f"- {d}" for d in details)
|
| 322 |
entry = "\n".join(lines) + "\n"
|
| 323 |
|
| 324 |
+
content = _read_wiki_page(wiki, "log.md") or ""
|
| 325 |
+
_write_wiki_page(wiki, "log.md", content + entry)
|
| 326 |
|
| 327 |
|
| 328 |
# ---------------------------------------------------------------------------
|
|
|
|
| 332 |
|
| 333 |
def generate_converted_index(wiki: Path, skills: list[ConvertedSkill]) -> None:
|
| 334 |
"""Generate converted-index.md listing every converted skill."""
|
|
|
|
|
|
|
| 335 |
header = (
|
| 336 |
f"# Converted Micro-Skill Pipelines Index\n"
|
| 337 |
f"\n"
|
|
|
|
| 351 |
rows.append(f"| {skill.name} | {entity_link} | {pipeline_link} |")
|
| 352 |
|
| 353 |
content = header + "\n".join(rows) + "\n"
|
| 354 |
+
_write_wiki_page(wiki, "converted-index.md", content)
|
| 355 |
print(f" converted-index.md written ({len(skills)} entries)")
|
| 356 |
|
| 357 |
|
src/mcp_add.py
CHANGED
|
@@ -39,6 +39,10 @@ import mcp_canonical_index
|
|
| 39 |
from mcp_entity import McpRecord
|
| 40 |
from wiki_batch_entities import generate_mcp_page
|
| 41 |
from ctx.core.wiki.wiki_sync import append_log, ensure_wiki, update_index
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
from ctx.core.wiki.wiki_queue import enqueue_entity_upsert
|
| 43 |
from ctx.core.wiki.wiki_utils import validate_skill_name
|
| 44 |
from ctx.utils._fs_utils import reject_symlink_path, safe_atomic_write_text
|
|
@@ -286,6 +290,111 @@ def _find_existing_by_github_url(
|
|
| 286 |
return None
|
| 287 |
|
| 288 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
def add_mcp(
|
| 290 |
*,
|
| 291 |
record: McpRecord,
|
|
@@ -328,6 +437,7 @@ def add_mcp(
|
|
| 328 |
entity_rel = record.entity_relpath() # e.g. "f/fetch-mcp.md"
|
| 329 |
mcp_dir = wiki_path / _MCP_ENTITY_SUBDIR
|
| 330 |
target_path = mcp_dir / entity_rel
|
|
|
|
| 331 |
|
| 332 |
# Phase 3.6: cross-source dedup by canonical github_url before the
|
| 333 |
# slug-based check. When awesome-mcp and pulsemcp both catalog the
|
|
@@ -337,9 +447,10 @@ def add_mcp(
|
|
| 337 |
# listing-page records currently have only homepage_url (Phase 6
|
| 338 |
# detail-page enrichment will populate github_url so this dedup
|
| 339 |
# path becomes meaningful for them too).
|
| 340 |
-
canonical_match =
|
| 341 |
if canonical_match is not None and canonical_match != target_path:
|
| 342 |
target_path = canonical_match
|
|
|
|
| 343 |
|
| 344 |
reject_symlink_path(target_path)
|
| 345 |
target_path.parent.mkdir(parents=True, exist_ok=True)
|
|
@@ -354,13 +465,13 @@ def add_mcp(
|
|
| 354 |
# Phase 1 of branching: compute the read-side state. No serialization
|
| 355 |
# work happens here so dry-run cannot fail on a malformed existing
|
| 356 |
# page — that's deferred to the write-gate below.
|
| 357 |
-
|
|
|
|
| 358 |
# Existing entity → straight to merge. No intake call: the gate
|
| 359 |
# would reject this as DUPLICATE against the cached embedding
|
| 360 |
# of the original ingest, blocking the source-merge that's the
|
| 361 |
# whole point of re-fetching. Phase 3b made this concrete.
|
| 362 |
is_new_page = False
|
| 363 |
-
existing_text = target_path.read_text(encoding="utf-8")
|
| 364 |
existing_fm = _parse_frontmatter(existing_text)
|
| 365 |
merged_sources = _merge_sources(existing_fm, record.sources)
|
| 366 |
kept_description = _keep_longer_description(existing_fm, record)
|
|
@@ -411,7 +522,12 @@ def add_mcp(
|
|
| 411 |
if not dry_run:
|
| 412 |
# Phase 2 of branching: render and write. Any YAML serialization
|
| 413 |
# failure now is a real error, not a dry-run side-effect.
|
| 414 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
queue_job = enqueue_entity_upsert(
|
| 416 |
wiki_path=wiki_path,
|
| 417 |
entity_type="mcp-server",
|
|
@@ -502,7 +618,6 @@ def _process_batch(
|
|
| 502 |
dry_run: bool,
|
| 503 |
skip_existing: bool,
|
| 504 |
update_existing: bool,
|
| 505 |
-
mcp_entity_dir: Path,
|
| 506 |
) -> tuple[int, int, int, int, int]:
|
| 507 |
"""Process records. Returns (added, merged, reviewed, rejected, errors)."""
|
| 508 |
added = merged = reviewed = rejected = errors = 0
|
|
@@ -518,9 +633,9 @@ def _process_batch(
|
|
| 518 |
continue
|
| 519 |
|
| 520 |
entity_rel = record.entity_relpath()
|
| 521 |
-
|
| 522 |
|
| 523 |
-
if skip_existing and
|
| 524 |
merged += 1
|
| 525 |
print(f" [{i}/{total}] [skipped] {record.slug}")
|
| 526 |
continue
|
|
@@ -595,7 +710,6 @@ def main() -> None:
|
|
| 595 |
|
| 596 |
wiki_path = Path(os.path.expanduser(args.wiki))
|
| 597 |
ensure_wiki(str(wiki_path))
|
| 598 |
-
mcp_entity_dir = wiki_path / _MCP_ENTITY_SUBDIR
|
| 599 |
|
| 600 |
raw_records: list[dict[str, Any]] = []
|
| 601 |
|
|
@@ -605,7 +719,7 @@ def main() -> None:
|
|
| 605 |
print(f"Error: {json_path} does not exist.", file=sys.stderr)
|
| 606 |
sys.exit(1)
|
| 607 |
try:
|
| 608 |
-
raw_records = [json.loads(json_path.read_text(encoding="utf-8"))]
|
| 609 |
except json.JSONDecodeError as exc:
|
| 610 |
print(f"Error: failed to parse JSON: {exc}", file=sys.stderr)
|
| 611 |
sys.exit(1)
|
|
@@ -616,9 +730,9 @@ def main() -> None:
|
|
| 616 |
print(f"Error: {jsonl_path} does not exist.", file=sys.stderr)
|
| 617 |
sys.exit(1)
|
| 618 |
for lineno, line in enumerate(
|
| 619 |
-
jsonl_path.read_text(encoding="utf-8").splitlines(), 1
|
| 620 |
):
|
| 621 |
-
line = line.strip()
|
| 622 |
if not line:
|
| 623 |
continue
|
| 624 |
try:
|
|
@@ -628,7 +742,7 @@ def main() -> None:
|
|
| 628 |
|
| 629 |
elif args.from_stdin:
|
| 630 |
for lineno, line in enumerate(sys.stdin, 1):
|
| 631 |
-
line = line.strip()
|
| 632 |
if not line:
|
| 633 |
continue
|
| 634 |
try:
|
|
@@ -646,7 +760,6 @@ def main() -> None:
|
|
| 646 |
dry_run=args.dry_run,
|
| 647 |
skip_existing=args.skip_existing,
|
| 648 |
update_existing=args.update_existing,
|
| 649 |
-
mcp_entity_dir=mcp_entity_dir,
|
| 650 |
)
|
| 651 |
|
| 652 |
dry_label = " (dry-run)" if args.dry_run else ""
|
|
@@ -654,6 +767,8 @@ def main() -> None:
|
|
| 654 |
f"\nDone{dry_label}: {added} added, {merged} updated, "
|
| 655 |
f"{reviewed} reviewed, {rejected} rejected, {errors} errors"
|
| 656 |
)
|
|
|
|
|
|
|
| 657 |
|
| 658 |
|
| 659 |
if __name__ == "__main__":
|
|
|
|
| 39 |
from mcp_entity import McpRecord
|
| 40 |
from wiki_batch_entities import generate_mcp_page
|
| 41 |
from ctx.core.wiki.wiki_sync import append_log, ensure_wiki, update_index
|
| 42 |
+
from ctx.core.wiki.wiki_packs import (
|
| 43 |
+
load_merged_wiki_pages,
|
| 44 |
+
write_active_wiki_overlay_pack,
|
| 45 |
+
)
|
| 46 |
from ctx.core.wiki.wiki_queue import enqueue_entity_upsert
|
| 47 |
from ctx.core.wiki.wiki_utils import validate_skill_name
|
| 48 |
from ctx.utils._fs_utils import reject_symlink_path, safe_atomic_write_text
|
|
|
|
| 290 |
return None
|
| 291 |
|
| 292 |
|
| 293 |
+
def _entity_relpath(entity_rel: Path | str) -> str:
|
| 294 |
+
return f"{_MCP_ENTITY_SUBDIR}/{Path(entity_rel).as_posix()}"
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def _read_entity_page(wiki_path: Path, relpath: str) -> str | None:
|
| 298 |
+
packs_dir = wiki_path / "wiki-packs"
|
| 299 |
+
if packs_dir.is_dir():
|
| 300 |
+
pages = load_merged_wiki_pages(packs_dir)
|
| 301 |
+
if relpath in pages:
|
| 302 |
+
return pages[relpath]
|
| 303 |
+
target_path = wiki_path / relpath
|
| 304 |
+
if target_path.exists():
|
| 305 |
+
return target_path.read_text(encoding="utf-8", errors="replace")
|
| 306 |
+
return None
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def _find_indexed_entity_page_by_github_url(
|
| 310 |
+
*,
|
| 311 |
+
wiki_path: Path,
|
| 312 |
+
target: str,
|
| 313 |
+
index: mcp_canonical_index.CanonicalIndex,
|
| 314 |
+
) -> Path | None:
|
| 315 |
+
"""Return a canonical-index hit after confirming it in the merged wiki view."""
|
| 316 |
+
mcp_dir = wiki_path / _MCP_ENTITY_SUBDIR
|
| 317 |
+
entry = index["by_github_url"].get(target)
|
| 318 |
+
if entry is None:
|
| 319 |
+
return None
|
| 320 |
+
|
| 321 |
+
relpath = entry["relpath"]
|
| 322 |
+
text = _read_entity_page(wiki_path, _entity_relpath(relpath))
|
| 323 |
+
if text is None:
|
| 324 |
+
return None
|
| 325 |
+
fm = _parse_frontmatter(text)
|
| 326 |
+
if _normalize_github_url(fm.get("github_url")) != target:
|
| 327 |
+
return None
|
| 328 |
+
return mcp_dir / relpath
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def _find_existing_by_github_url_in_wiki(
|
| 332 |
+
wiki_path: Path,
|
| 333 |
+
target_github_url: str | None,
|
| 334 |
+
) -> Path | None:
|
| 335 |
+
target = _normalize_github_url(target_github_url)
|
| 336 |
+
if target is None:
|
| 337 |
+
return None
|
| 338 |
+
|
| 339 |
+
mcp_dir = wiki_path / _MCP_ENTITY_SUBDIR
|
| 340 |
+
index = mcp_canonical_index.load_index(mcp_dir)
|
| 341 |
+
indexed_hit = _find_indexed_entity_page_by_github_url(
|
| 342 |
+
wiki_path=wiki_path,
|
| 343 |
+
target=target,
|
| 344 |
+
index=index,
|
| 345 |
+
)
|
| 346 |
+
if indexed_hit is not None:
|
| 347 |
+
return indexed_hit
|
| 348 |
+
|
| 349 |
+
physical_hit = _find_existing_by_github_url(mcp_dir, target)
|
| 350 |
+
if physical_hit is not None:
|
| 351 |
+
return physical_hit
|
| 352 |
+
|
| 353 |
+
packs_dir = wiki_path / "wiki-packs"
|
| 354 |
+
if not packs_dir.is_dir():
|
| 355 |
+
return None
|
| 356 |
+
prefix = f"{_MCP_ENTITY_SUBDIR}/"
|
| 357 |
+
for relpath, text in sorted(load_merged_wiki_pages(packs_dir).items()):
|
| 358 |
+
if not relpath.startswith(prefix) or not relpath.endswith(".md"):
|
| 359 |
+
continue
|
| 360 |
+
if target not in text.lower():
|
| 361 |
+
continue
|
| 362 |
+
fm = _parse_frontmatter(text)
|
| 363 |
+
if _normalize_github_url(fm.get("github_url")) == target:
|
| 364 |
+
if mcp_dir.is_dir():
|
| 365 |
+
try:
|
| 366 |
+
entity_relpath = relpath[len(prefix) :]
|
| 367 |
+
mcp_canonical_index.upsert(
|
| 368 |
+
mcp_dir,
|
| 369 |
+
target,
|
| 370 |
+
slug=Path(entity_relpath).stem,
|
| 371 |
+
relpath=entity_relpath,
|
| 372 |
+
index=index,
|
| 373 |
+
)
|
| 374 |
+
except (OSError, ValueError):
|
| 375 |
+
pass
|
| 376 |
+
return wiki_path / relpath
|
| 377 |
+
return None
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def _write_entity_page(
|
| 381 |
+
*,
|
| 382 |
+
wiki_path: Path,
|
| 383 |
+
relpath: str,
|
| 384 |
+
target_path: Path,
|
| 385 |
+
content: str,
|
| 386 |
+
) -> None:
|
| 387 |
+
packs_dir = wiki_path / "wiki-packs"
|
| 388 |
+
if target_path.exists() or not packs_dir.is_dir():
|
| 389 |
+
safe_atomic_write_text(target_path, content, encoding="utf-8")
|
| 390 |
+
if packs_dir.is_dir():
|
| 391 |
+
write_active_wiki_overlay_pack(
|
| 392 |
+
packs_dir=packs_dir,
|
| 393 |
+
pages={relpath: content},
|
| 394 |
+
tombstones=[],
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
|
| 398 |
def add_mcp(
|
| 399 |
*,
|
| 400 |
record: McpRecord,
|
|
|
|
| 437 |
entity_rel = record.entity_relpath() # e.g. "f/fetch-mcp.md"
|
| 438 |
mcp_dir = wiki_path / _MCP_ENTITY_SUBDIR
|
| 439 |
target_path = mcp_dir / entity_rel
|
| 440 |
+
target_relpath = _entity_relpath(entity_rel)
|
| 441 |
|
| 442 |
# Phase 3.6: cross-source dedup by canonical github_url before the
|
| 443 |
# slug-based check. When awesome-mcp and pulsemcp both catalog the
|
|
|
|
| 447 |
# listing-page records currently have only homepage_url (Phase 6
|
| 448 |
# detail-page enrichment will populate github_url so this dedup
|
| 449 |
# path becomes meaningful for them too).
|
| 450 |
+
canonical_match = _find_existing_by_github_url_in_wiki(wiki_path, record.github_url)
|
| 451 |
if canonical_match is not None and canonical_match != target_path:
|
| 452 |
target_path = canonical_match
|
| 453 |
+
target_relpath = target_path.relative_to(wiki_path).as_posix()
|
| 454 |
|
| 455 |
reject_symlink_path(target_path)
|
| 456 |
target_path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 465 |
# Phase 1 of branching: compute the read-side state. No serialization
|
| 466 |
# work happens here so dry-run cannot fail on a malformed existing
|
| 467 |
# page — that's deferred to the write-gate below.
|
| 468 |
+
existing_text = _read_entity_page(wiki_path, target_relpath)
|
| 469 |
+
if existing_text is not None:
|
| 470 |
# Existing entity → straight to merge. No intake call: the gate
|
| 471 |
# would reject this as DUPLICATE against the cached embedding
|
| 472 |
# of the original ingest, blocking the source-merge that's the
|
| 473 |
# whole point of re-fetching. Phase 3b made this concrete.
|
| 474 |
is_new_page = False
|
|
|
|
| 475 |
existing_fm = _parse_frontmatter(existing_text)
|
| 476 |
merged_sources = _merge_sources(existing_fm, record.sources)
|
| 477 |
kept_description = _keep_longer_description(existing_fm, record)
|
|
|
|
| 522 |
if not dry_run:
|
| 523 |
# Phase 2 of branching: render and write. Any YAML serialization
|
| 524 |
# failure now is a real error, not a dry-run side-effect.
|
| 525 |
+
_write_entity_page(
|
| 526 |
+
wiki_path=wiki_path,
|
| 527 |
+
relpath=target_relpath,
|
| 528 |
+
target_path=target_path,
|
| 529 |
+
content=final_text,
|
| 530 |
+
)
|
| 531 |
queue_job = enqueue_entity_upsert(
|
| 532 |
wiki_path=wiki_path,
|
| 533 |
entity_type="mcp-server",
|
|
|
|
| 618 |
dry_run: bool,
|
| 619 |
skip_existing: bool,
|
| 620 |
update_existing: bool,
|
|
|
|
| 621 |
) -> tuple[int, int, int, int, int]:
|
| 622 |
"""Process records. Returns (added, merged, reviewed, rejected, errors)."""
|
| 623 |
added = merged = reviewed = rejected = errors = 0
|
|
|
|
| 633 |
continue
|
| 634 |
|
| 635 |
entity_rel = record.entity_relpath()
|
| 636 |
+
target_relpath = _entity_relpath(entity_rel)
|
| 637 |
|
| 638 |
+
if skip_existing and _read_entity_page(wiki_path, target_relpath) is not None:
|
| 639 |
merged += 1
|
| 640 |
print(f" [{i}/{total}] [skipped] {record.slug}")
|
| 641 |
continue
|
|
|
|
| 710 |
|
| 711 |
wiki_path = Path(os.path.expanduser(args.wiki))
|
| 712 |
ensure_wiki(str(wiki_path))
|
|
|
|
| 713 |
|
| 714 |
raw_records: list[dict[str, Any]] = []
|
| 715 |
|
|
|
|
| 719 |
print(f"Error: {json_path} does not exist.", file=sys.stderr)
|
| 720 |
sys.exit(1)
|
| 721 |
try:
|
| 722 |
+
raw_records = [json.loads(json_path.read_text(encoding="utf-8-sig"))]
|
| 723 |
except json.JSONDecodeError as exc:
|
| 724 |
print(f"Error: failed to parse JSON: {exc}", file=sys.stderr)
|
| 725 |
sys.exit(1)
|
|
|
|
| 730 |
print(f"Error: {jsonl_path} does not exist.", file=sys.stderr)
|
| 731 |
sys.exit(1)
|
| 732 |
for lineno, line in enumerate(
|
| 733 |
+
jsonl_path.read_text(encoding="utf-8-sig").splitlines(), 1
|
| 734 |
):
|
| 735 |
+
line = line.lstrip("\ufeff").strip()
|
| 736 |
if not line:
|
| 737 |
continue
|
| 738 |
try:
|
|
|
|
| 742 |
|
| 743 |
elif args.from_stdin:
|
| 744 |
for lineno, line in enumerate(sys.stdin, 1):
|
| 745 |
+
line = line.lstrip("\ufeff").strip()
|
| 746 |
if not line:
|
| 747 |
continue
|
| 748 |
try:
|
|
|
|
| 760 |
dry_run=args.dry_run,
|
| 761 |
skip_existing=args.skip_existing,
|
| 762 |
update_existing=args.update_existing,
|
|
|
|
| 763 |
)
|
| 764 |
|
| 765 |
dry_label = " (dry-run)" if args.dry_run else ""
|
|
|
|
| 767 |
f"\nDone{dry_label}: {added} added, {merged} updated, "
|
| 768 |
f"{reviewed} reviewed, {rejected} rejected, {errors} errors"
|
| 769 |
)
|
| 770 |
+
if rejected or errors:
|
| 771 |
+
sys.exit(1)
|
| 772 |
|
| 773 |
|
| 774 |
if __name__ == "__main__":
|
src/mcp_canonical_index.py
CHANGED
|
@@ -56,6 +56,7 @@ from datetime import datetime, timezone
|
|
| 56 |
from pathlib import Path
|
| 57 |
from typing import TypedDict
|
| 58 |
|
|
|
|
| 59 |
from ctx.utils._fs_utils import atomic_write_json
|
| 60 |
|
| 61 |
__all__ = [
|
|
@@ -253,7 +254,37 @@ def remove(
|
|
| 253 |
return idx
|
| 254 |
|
| 255 |
|
| 256 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
"""Scan every entity page, rebuild the index from scratch.
|
| 258 |
|
| 259 |
Returns ``(index, indexed, skipped)`` where *indexed* counts pages
|
|
@@ -273,19 +304,22 @@ def rebuild_from_scan(mcp_dir: Path) -> tuple[CanonicalIndex, int, int]:
|
|
| 273 |
indexed = 0
|
| 274 |
skipped = 0
|
| 275 |
|
| 276 |
-
|
|
|
|
| 277 |
return index, indexed, skipped
|
| 278 |
|
| 279 |
-
for
|
| 280 |
# Skip non-entity files that might land under the tree later.
|
| 281 |
-
if
|
| 282 |
-
skipped += 1
|
| 283 |
-
continue
|
| 284 |
-
try:
|
| 285 |
-
text = page.read_text(encoding="utf-8", errors="replace")
|
| 286 |
-
except OSError:
|
| 287 |
skipped += 1
|
| 288 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
fm = _parse_frontmatter(text)
|
| 290 |
normalized = _normalize_github_url(fm.get("github_url"))
|
| 291 |
if normalized is None:
|
|
@@ -296,8 +330,6 @@ def rebuild_from_scan(mcp_dir: Path) -> tuple[CanonicalIndex, int, int]:
|
|
| 296 |
# ``McpRecord.slug``, whereas the ``name`` field may store the
|
| 297 |
# original upstream display name (e.g. ``1mcp/agent`` for a
|
| 298 |
# file at ``0-9/1mcp-agent.md``).
|
| 299 |
-
slug = page.stem
|
| 300 |
-
relpath = page.relative_to(mcp_dir).as_posix()
|
| 301 |
upsert(
|
| 302 |
mcp_dir,
|
| 303 |
normalized,
|
|
@@ -308,5 +340,6 @@ def rebuild_from_scan(mcp_dir: Path) -> tuple[CanonicalIndex, int, int]:
|
|
| 308 |
)
|
| 309 |
indexed += 1
|
| 310 |
|
| 311 |
-
|
|
|
|
| 312 |
return index, indexed, skipped
|
|
|
|
| 56 |
from pathlib import Path
|
| 57 |
from typing import TypedDict
|
| 58 |
|
| 59 |
+
from ctx.core.wiki.wiki_packs import load_merged_wiki_pages
|
| 60 |
from ctx.utils._fs_utils import atomic_write_json
|
| 61 |
|
| 62 |
__all__ = [
|
|
|
|
| 254 |
return idx
|
| 255 |
|
| 256 |
|
| 257 |
+
def _wiki_packs_dir_for_mcp_dir(mcp_dir: Path) -> Path:
|
| 258 |
+
if mcp_dir.name != "mcp-servers" or mcp_dir.parent.name != "entities":
|
| 259 |
+
return mcp_dir / ".no-wiki-packs"
|
| 260 |
+
return mcp_dir.parent.parent / "wiki-packs"
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def _iter_entity_pages(mcp_dir: Path) -> list[tuple[str, str, str | None]]:
|
| 264 |
+
packs_dir = _wiki_packs_dir_for_mcp_dir(mcp_dir)
|
| 265 |
+
if packs_dir.is_dir():
|
| 266 |
+
prefix = "entities/mcp-servers/"
|
| 267 |
+
rows: list[tuple[str, str, str | None]] = []
|
| 268 |
+
for full_relpath, text in sorted(load_merged_wiki_pages(packs_dir).items()):
|
| 269 |
+
if not full_relpath.startswith(prefix) or not full_relpath.endswith(".md"):
|
| 270 |
+
continue
|
| 271 |
+
relpath = full_relpath[len(prefix):]
|
| 272 |
+
rows.append((relpath, Path(relpath).stem, text))
|
| 273 |
+
return rows
|
| 274 |
+
|
| 275 |
+
if not mcp_dir.is_dir():
|
| 276 |
+
return []
|
| 277 |
+
rows = []
|
| 278 |
+
for page in sorted(mcp_dir.rglob("*.md")):
|
| 279 |
+
rows.append((page.relative_to(mcp_dir).as_posix(), page.stem, None))
|
| 280 |
+
return rows
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def rebuild_from_scan(
|
| 284 |
+
mcp_dir: Path,
|
| 285 |
+
*,
|
| 286 |
+
persist: bool = True,
|
| 287 |
+
) -> tuple[CanonicalIndex, int, int]:
|
| 288 |
"""Scan every entity page, rebuild the index from scratch.
|
| 289 |
|
| 290 |
Returns ``(index, indexed, skipped)`` where *indexed* counts pages
|
|
|
|
| 304 |
indexed = 0
|
| 305 |
skipped = 0
|
| 306 |
|
| 307 |
+
rows = _iter_entity_pages(mcp_dir)
|
| 308 |
+
if not rows:
|
| 309 |
return index, indexed, skipped
|
| 310 |
|
| 311 |
+
for relpath, slug, text in rows:
|
| 312 |
# Skip non-entity files that might land under the tree later.
|
| 313 |
+
if Path(relpath).name.startswith("."):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
skipped += 1
|
| 315 |
continue
|
| 316 |
+
if text is None:
|
| 317 |
+
page = mcp_dir / relpath
|
| 318 |
+
try:
|
| 319 |
+
text = page.read_text(encoding="utf-8", errors="replace")
|
| 320 |
+
except OSError:
|
| 321 |
+
skipped += 1
|
| 322 |
+
continue
|
| 323 |
fm = _parse_frontmatter(text)
|
| 324 |
normalized = _normalize_github_url(fm.get("github_url"))
|
| 325 |
if normalized is None:
|
|
|
|
| 330 |
# ``McpRecord.slug``, whereas the ``name`` field may store the
|
| 331 |
# original upstream display name (e.g. ``1mcp/agent`` for a
|
| 332 |
# file at ``0-9/1mcp-agent.md``).
|
|
|
|
|
|
|
| 333 |
upsert(
|
| 334 |
mcp_dir,
|
| 335 |
normalized,
|
|
|
|
| 340 |
)
|
| 341 |
indexed += 1
|
| 342 |
|
| 343 |
+
if persist:
|
| 344 |
+
save_index(mcp_dir, index)
|
| 345 |
return index, indexed, skipped
|
src/mcp_enrich.py
CHANGED
|
@@ -48,7 +48,8 @@ from datetime import datetime, timezone
|
|
| 48 |
from pathlib import Path
|
| 49 |
from typing import Any, Iterable
|
| 50 |
|
| 51 |
-
from ctx.
|
|
|
|
| 52 |
from ctx_config import cfg
|
| 53 |
from mcp_sources import SOURCES
|
| 54 |
|
|
@@ -183,6 +184,15 @@ def _iter_entities(wiki_path: Path) -> Iterable[Path]:
|
|
| 183 |
at entity #5,000 might skip ahead or rewind depending on platform
|
| 184 |
shard-iteration order.
|
| 185 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
root = wiki_path / _MCP_ENTITY_SUBDIR
|
| 187 |
if not root.is_dir():
|
| 188 |
return []
|
|
@@ -211,8 +221,62 @@ _SOURCE_SLUG_PATTERNS: dict[str, re.Pattern[str]] = {
|
|
| 211 |
}
|
| 212 |
|
| 213 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
def _source_slug_from_entity(
|
| 215 |
-
entity_path: Path,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
) -> str | None:
|
| 217 |
"""Pull the upstream slug out of the entity's frontmatter.
|
| 218 |
|
|
@@ -228,9 +292,16 @@ def _source_slug_from_entity(
|
|
| 228 |
pattern = _SOURCE_SLUG_PATTERNS.get(source_name)
|
| 229 |
if pattern is None:
|
| 230 |
return None
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
return None
|
| 235 |
fm_match = _FRONTMATTER_RE.match(text)
|
| 236 |
if fm_match is None:
|
|
@@ -343,7 +414,12 @@ def _render_scalar(value: Any) -> str:
|
|
| 343 |
|
| 344 |
|
| 345 |
def apply_enrichment(
|
| 346 |
-
entity_path: Path,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
) -> dict:
|
| 348 |
"""Write ``enrichment`` fields into the entity's frontmatter.
|
| 349 |
|
|
@@ -355,7 +431,14 @@ def apply_enrichment(
|
|
| 355 |
if not enrichment:
|
| 356 |
return {}
|
| 357 |
|
| 358 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 359 |
fm_match = _FRONTMATTER_RE.match(text)
|
| 360 |
if fm_match is None:
|
| 361 |
return {}
|
|
@@ -382,7 +465,10 @@ def apply_enrichment(
|
|
| 382 |
if diff and not dry_run:
|
| 383 |
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
| 384 |
text = _set_frontmatter_field(text, "updated", today)
|
| 385 |
-
|
|
|
|
|
|
|
|
|
|
| 386 |
return diff
|
| 387 |
|
| 388 |
|
|
@@ -420,6 +506,7 @@ def enrich_entities(
|
|
| 420 |
|
| 421 |
processed = checkpoint["processed"]
|
| 422 |
failures = checkpoint["failures"]
|
|
|
|
| 423 |
|
| 424 |
attempted = enriched = unchanged = failed = skipped = 0
|
| 425 |
for path in entity_paths:
|
|
@@ -439,7 +526,12 @@ def enrich_entities(
|
|
| 439 |
attempted += 1
|
| 440 |
checkpoint["total_seen"] += 1
|
| 441 |
|
| 442 |
-
source_slug = _source_slug_from_entity(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 443 |
if source_slug is None:
|
| 444 |
# Entity has no homepage_url for this source (e.g. ingested
|
| 445 |
# from a different source). Record a skip so we don't
|
|
@@ -478,7 +570,13 @@ def enrich_entities(
|
|
| 478 |
continue
|
| 479 |
|
| 480 |
try:
|
| 481 |
-
diff = apply_enrichment(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 482 |
except Exception as exc: # noqa: BLE001
|
| 483 |
failed += 1
|
| 484 |
failures[wiki_slug] = {
|
|
@@ -647,7 +745,7 @@ def main() -> None:
|
|
| 647 |
# Shard lookup mirrors McpRecord.entity_relpath.
|
| 648 |
shard = args.slug[0] if args.slug and args.slug[0].isalpha() else "0-9"
|
| 649 |
entity_paths = [root / shard / f"{args.slug}.md"]
|
| 650 |
-
if
|
| 651 |
print(
|
| 652 |
f"Error: no entity at {entity_paths[0]} — has it been ingested?",
|
| 653 |
file=sys.stderr,
|
|
|
|
| 48 |
from pathlib import Path
|
| 49 |
from typing import Any, Iterable
|
| 50 |
|
| 51 |
+
from ctx.core.wiki.wiki_packs import load_merged_wiki_pages, write_active_wiki_overlay_pack
|
| 52 |
+
from ctx.utils._fs_utils import atomic_write_json, reject_symlink_path, safe_atomic_write_text
|
| 53 |
from ctx_config import cfg
|
| 54 |
from mcp_sources import SOURCES
|
| 55 |
|
|
|
|
| 184 |
at entity #5,000 might skip ahead or rewind depending on platform
|
| 185 |
shard-iteration order.
|
| 186 |
"""
|
| 187 |
+
packs_dir = wiki_path / "wiki-packs"
|
| 188 |
+
if packs_dir.is_dir():
|
| 189 |
+
prefix = f"{_MCP_ENTITY_SUBDIR.as_posix()}/"
|
| 190 |
+
return [
|
| 191 |
+
wiki_path / relpath
|
| 192 |
+
for relpath in sorted(load_merged_wiki_pages(packs_dir))
|
| 193 |
+
if relpath.startswith(prefix) and relpath.endswith(".md")
|
| 194 |
+
]
|
| 195 |
+
|
| 196 |
root = wiki_path / _MCP_ENTITY_SUBDIR
|
| 197 |
if not root.is_dir():
|
| 198 |
return []
|
|
|
|
| 221 |
}
|
| 222 |
|
| 223 |
|
| 224 |
+
def _entity_relpath(wiki_path: Path, entity_path: Path) -> str:
|
| 225 |
+
return entity_path.relative_to(wiki_path).as_posix()
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def _load_active_wiki_pack_pages(wiki_path: Path) -> dict[str, str] | None:
|
| 229 |
+
packs_dir = wiki_path / "wiki-packs"
|
| 230 |
+
if not packs_dir.is_dir():
|
| 231 |
+
return None
|
| 232 |
+
return load_merged_wiki_pages(packs_dir)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def _read_entity_text(
|
| 236 |
+
wiki_path: Path,
|
| 237 |
+
entity_path: Path,
|
| 238 |
+
*,
|
| 239 |
+
pages: dict[str, str] | None = None,
|
| 240 |
+
) -> str | None:
|
| 241 |
+
relpath = _entity_relpath(wiki_path, entity_path)
|
| 242 |
+
packs_dir = wiki_path / "wiki-packs"
|
| 243 |
+
if packs_dir.is_dir():
|
| 244 |
+
page_map = pages if pages is not None else load_merged_wiki_pages(packs_dir)
|
| 245 |
+
if relpath in page_map:
|
| 246 |
+
return page_map[relpath]
|
| 247 |
+
if entity_path.exists():
|
| 248 |
+
reject_symlink_path(entity_path)
|
| 249 |
+
return entity_path.read_text(encoding="utf-8", errors="replace")
|
| 250 |
+
return None
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def _write_entity_text(
|
| 254 |
+
wiki_path: Path,
|
| 255 |
+
entity_path: Path,
|
| 256 |
+
text: str,
|
| 257 |
+
*,
|
| 258 |
+
pages: dict[str, str] | None = None,
|
| 259 |
+
) -> None:
|
| 260 |
+
relpath = _entity_relpath(wiki_path, entity_path)
|
| 261 |
+
packs_dir = wiki_path / "wiki-packs"
|
| 262 |
+
if entity_path.exists() or not packs_dir.is_dir():
|
| 263 |
+
safe_atomic_write_text(entity_path, text, encoding="utf-8")
|
| 264 |
+
if packs_dir.is_dir():
|
| 265 |
+
write_active_wiki_overlay_pack(
|
| 266 |
+
packs_dir=packs_dir,
|
| 267 |
+
pages={relpath: text},
|
| 268 |
+
tombstones=[],
|
| 269 |
+
)
|
| 270 |
+
if pages is not None:
|
| 271 |
+
pages[relpath] = text
|
| 272 |
+
|
| 273 |
+
|
| 274 |
def _source_slug_from_entity(
|
| 275 |
+
entity_path: Path,
|
| 276 |
+
source_name: str,
|
| 277 |
+
*,
|
| 278 |
+
wiki_path: Path | None = None,
|
| 279 |
+
pages: dict[str, str] | None = None,
|
| 280 |
) -> str | None:
|
| 281 |
"""Pull the upstream slug out of the entity's frontmatter.
|
| 282 |
|
|
|
|
| 292 |
pattern = _SOURCE_SLUG_PATTERNS.get(source_name)
|
| 293 |
if pattern is None:
|
| 294 |
return None
|
| 295 |
+
text: str | None
|
| 296 |
+
if wiki_path is None:
|
| 297 |
+
try:
|
| 298 |
+
reject_symlink_path(entity_path)
|
| 299 |
+
text = entity_path.read_text(encoding="utf-8", errors="replace")
|
| 300 |
+
except OSError:
|
| 301 |
+
return None
|
| 302 |
+
else:
|
| 303 |
+
text = _read_entity_text(wiki_path, entity_path, pages=pages)
|
| 304 |
+
if text is None:
|
| 305 |
return None
|
| 306 |
fm_match = _FRONTMATTER_RE.match(text)
|
| 307 |
if fm_match is None:
|
|
|
|
| 414 |
|
| 415 |
|
| 416 |
def apply_enrichment(
|
| 417 |
+
entity_path: Path,
|
| 418 |
+
enrichment: dict,
|
| 419 |
+
*,
|
| 420 |
+
dry_run: bool,
|
| 421 |
+
wiki_path: Path | None = None,
|
| 422 |
+
pages: dict[str, str] | None = None,
|
| 423 |
) -> dict:
|
| 424 |
"""Write ``enrichment`` fields into the entity's frontmatter.
|
| 425 |
|
|
|
|
| 431 |
if not enrichment:
|
| 432 |
return {}
|
| 433 |
|
| 434 |
+
if wiki_path is None:
|
| 435 |
+
reject_symlink_path(entity_path)
|
| 436 |
+
text = entity_path.read_text(encoding="utf-8", errors="replace")
|
| 437 |
+
else:
|
| 438 |
+
read_text = _read_entity_text(wiki_path, entity_path, pages=pages)
|
| 439 |
+
if read_text is None:
|
| 440 |
+
return {}
|
| 441 |
+
text = read_text
|
| 442 |
fm_match = _FRONTMATTER_RE.match(text)
|
| 443 |
if fm_match is None:
|
| 444 |
return {}
|
|
|
|
| 465 |
if diff and not dry_run:
|
| 466 |
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
| 467 |
text = _set_frontmatter_field(text, "updated", today)
|
| 468 |
+
if wiki_path is None:
|
| 469 |
+
safe_atomic_write_text(entity_path, text, encoding="utf-8")
|
| 470 |
+
else:
|
| 471 |
+
_write_entity_text(wiki_path, entity_path, text, pages=pages)
|
| 472 |
return diff
|
| 473 |
|
| 474 |
|
|
|
|
| 506 |
|
| 507 |
processed = checkpoint["processed"]
|
| 508 |
failures = checkpoint["failures"]
|
| 509 |
+
pages = _load_active_wiki_pack_pages(wiki_path)
|
| 510 |
|
| 511 |
attempted = enriched = unchanged = failed = skipped = 0
|
| 512 |
for path in entity_paths:
|
|
|
|
| 526 |
attempted += 1
|
| 527 |
checkpoint["total_seen"] += 1
|
| 528 |
|
| 529 |
+
source_slug = _source_slug_from_entity(
|
| 530 |
+
path,
|
| 531 |
+
source_name,
|
| 532 |
+
wiki_path=wiki_path,
|
| 533 |
+
pages=pages,
|
| 534 |
+
)
|
| 535 |
if source_slug is None:
|
| 536 |
# Entity has no homepage_url for this source (e.g. ingested
|
| 537 |
# from a different source). Record a skip so we don't
|
|
|
|
| 570 |
continue
|
| 571 |
|
| 572 |
try:
|
| 573 |
+
diff = apply_enrichment(
|
| 574 |
+
path,
|
| 575 |
+
enrichment,
|
| 576 |
+
dry_run=dry_run,
|
| 577 |
+
wiki_path=wiki_path,
|
| 578 |
+
pages=pages,
|
| 579 |
+
)
|
| 580 |
except Exception as exc: # noqa: BLE001
|
| 581 |
failed += 1
|
| 582 |
failures[wiki_slug] = {
|
|
|
|
| 745 |
# Shard lookup mirrors McpRecord.entity_relpath.
|
| 746 |
shard = args.slug[0] if args.slug and args.slug[0].isalpha() else "0-9"
|
| 747 |
entity_paths = [root / shard / f"{args.slug}.md"]
|
| 748 |
+
if _read_entity_text(wiki_path, entity_paths[0]) is None:
|
| 749 |
print(
|
| 750 |
f"Error: no entity at {entity_paths[0]} — has it been ingested?",
|
| 751 |
file=sys.stderr,
|
src/mcp_quality.py
CHANGED
|
@@ -46,7 +46,9 @@ from datetime import datetime, timezone
|
|
| 46 |
from pathlib import Path
|
| 47 |
from typing import Any, Mapping
|
| 48 |
|
|
|
|
| 49 |
from ctx.utils._fs_utils import atomic_write_text as _atomic_write
|
|
|
|
| 50 |
from mcp_entity import MCP_SLUG_RE, McpRecord
|
| 51 |
from ctx.core.quality.quality_signals import SignalResult
|
| 52 |
from ctx.core.wiki.wiki_utils import parse_frontmatter_and_body
|
|
@@ -286,8 +288,65 @@ def _resolve_mcp_entity_path(slug: str, wiki_dir: Path) -> Path:
|
|
| 286 |
return wiki_dir / "entities" / "mcp-servers" / shard / f"{slug}.md"
|
| 287 |
|
| 288 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
def _read_mcp_entity(
|
| 290 |
-
slug: str,
|
|
|
|
|
|
|
|
|
|
| 291 |
) -> tuple[McpRecord, dict[str, Any]]:
|
| 292 |
"""Read entity .md, parse frontmatter, reconstruct McpRecord.
|
| 293 |
|
|
@@ -304,11 +363,11 @@ def _read_mcp_entity(
|
|
| 304 |
ValueError: If the frontmatter cannot produce a valid McpRecord.
|
| 305 |
"""
|
| 306 |
path = _resolve_mcp_entity_path(slug, wiki_dir)
|
| 307 |
-
|
|
|
|
| 308 |
raise FileNotFoundError(
|
| 309 |
f"MCP entity not found: {path}"
|
| 310 |
)
|
| 311 |
-
raw = path.read_text(encoding="utf-8", errors="replace")
|
| 312 |
fm, _body = parse_frontmatter_and_body(raw)
|
| 313 |
# McpRecord.from_dict is tolerant of missing optional fields.
|
| 314 |
record = McpRecord.from_dict({**fm, "slug": slug})
|
|
@@ -321,47 +380,31 @@ def _read_mcp_entity(
|
|
| 321 |
|
| 322 |
|
| 323 |
def load_graph_index(wiki_dir: Path) -> dict[str, dict[str, Any]]:
|
| 324 |
-
"""Load
|
| 325 |
|
| 326 |
Returns a mapping of ``{node_id: {"degree": int, "cross_type_degree": int}}``.
|
| 327 |
Cross-type degree counts neighbours whose ``node_id`` starts with a
|
| 328 |
different type prefix (e.g. ``skill:`` or ``agent:`` vs ``mcp-server:``).
|
| 329 |
-
Returns an empty dict if
|
|
|
|
| 330 |
"""
|
| 331 |
graph_path = wiki_dir / "graphify-out" / "graph.json"
|
| 332 |
-
|
|
|
|
| 333 |
return {}
|
| 334 |
try:
|
| 335 |
-
|
| 336 |
-
except (json.JSONDecodeError, OSError):
|
| 337 |
-
_logger.warning("load_graph_index: could not parse %s", graph_path)
|
| 338 |
-
return {}
|
| 339 |
|
| 340 |
-
|
|
|
|
|
|
|
| 341 |
return {}
|
| 342 |
|
| 343 |
-
# Build neighbour lists from links/edges.
|
| 344 |
-
edge_key = "links" if "links" in data else "edges"
|
| 345 |
-
raw_edges = data.get(edge_key) or []
|
| 346 |
-
|
| 347 |
-
# adjacency: node_id -> set of neighbour node_ids
|
| 348 |
-
adjacency: dict[str, set[str]] = {}
|
| 349 |
-
for node in data.get("nodes", []):
|
| 350 |
-
nid = node.get("id")
|
| 351 |
-
if isinstance(nid, str):
|
| 352 |
-
adjacency[nid] = set()
|
| 353 |
-
|
| 354 |
-
for edge in raw_edges:
|
| 355 |
-
if not isinstance(edge, dict):
|
| 356 |
-
continue
|
| 357 |
-
src = edge.get("source") or edge.get("from")
|
| 358 |
-
tgt = edge.get("target") or edge.get("to")
|
| 359 |
-
if isinstance(src, str) and isinstance(tgt, str):
|
| 360 |
-
adjacency.setdefault(src, set()).add(tgt)
|
| 361 |
-
adjacency.setdefault(tgt, set()).add(src)
|
| 362 |
-
|
| 363 |
index: dict[str, dict[str, Any]] = {}
|
| 364 |
-
for node_id
|
|
|
|
|
|
|
|
|
|
| 365 |
# Derive this node's type prefix (e.g. "skill", "mcp-server").
|
| 366 |
node_prefix = node_id.split(":")[0] if ":" in node_id else ""
|
| 367 |
cross_type = sum(
|
|
@@ -409,6 +452,7 @@ def extract_signals_for_slug(
|
|
| 409 |
wiki_dir: Path,
|
| 410 |
config: McpQualityConfig | None = None,
|
| 411 |
graph_index: Mapping[str, dict[str, Any]] | None = None,
|
|
|
|
| 412 |
) -> Mapping[str, SignalResult]:
|
| 413 |
"""Read entity, compute graph degrees, call all six signal functions.
|
| 414 |
|
|
@@ -441,7 +485,7 @@ def extract_signals_for_slug(
|
|
| 441 |
_ensure_safe_slug(slug)
|
| 442 |
cfg = config or McpQualityConfig()
|
| 443 |
|
| 444 |
-
record, fm = _read_mcp_entity(slug, wiki_dir)
|
| 445 |
|
| 446 |
# Graph degrees.
|
| 447 |
node_id = f"{_MCP_NODE_PREFIX}{slug}"
|
|
@@ -623,6 +667,7 @@ def persist_quality(
|
|
| 623 |
wiki_dir: Path,
|
| 624 |
sidecar_dir: Path | None = None,
|
| 625 |
update_frontmatter: bool = True,
|
|
|
|
| 626 |
) -> dict[str, Path]:
|
| 627 |
"""Write the quality result to the three on-disk sinks atomically.
|
| 628 |
|
|
@@ -649,15 +694,14 @@ def persist_quality(
|
|
| 649 |
|
| 650 |
# Sinks 2 + 3 — entity .md (frontmatter + body).
|
| 651 |
entity_path = _resolve_mcp_entity_path(score.slug, wiki_dir)
|
| 652 |
-
|
|
|
|
| 653 |
_logger.info(
|
| 654 |
"mcp_quality: no entity page at %s; frontmatter/body sinks skipped",
|
| 655 |
entity_path,
|
| 656 |
)
|
| 657 |
return written
|
| 658 |
|
| 659 |
-
raw = entity_path.read_text(encoding="utf-8", errors="replace")
|
| 660 |
-
|
| 661 |
# Sink 2 — frontmatter.
|
| 662 |
updated = _update_frontmatter_quality(raw, score)
|
| 663 |
|
|
@@ -671,7 +715,7 @@ def persist_quality(
|
|
| 671 |
new_body = _inject_quality_section(body, _render_quality_section(score))
|
| 672 |
updated = header + new_body
|
| 673 |
|
| 674 |
-
|
| 675 |
written["frontmatter"] = entity_path
|
| 676 |
written["wiki_body"] = entity_path
|
| 677 |
|
|
@@ -726,6 +770,7 @@ def recompute_slug(
|
|
| 726 |
graph_index: Mapping[str, dict[str, Any]] | None = None,
|
| 727 |
sidecar_dir: Path | None = None,
|
| 728 |
update_frontmatter: bool = True,
|
|
|
|
| 729 |
) -> McpQualityScore:
|
| 730 |
"""End-to-end recompute: extract signals → compute → persist."""
|
| 731 |
signals = extract_signals_for_slug(
|
|
@@ -733,6 +778,7 @@ def recompute_slug(
|
|
| 733 |
wiki_dir=wiki_dir,
|
| 734 |
config=config,
|
| 735 |
graph_index=graph_index,
|
|
|
|
| 736 |
)
|
| 737 |
score = compute_quality(
|
| 738 |
slug=slug,
|
|
@@ -745,16 +791,32 @@ def recompute_slug(
|
|
| 745 |
wiki_dir=wiki_dir,
|
| 746 |
sidecar_dir=sidecar_dir,
|
| 747 |
update_frontmatter=update_frontmatter,
|
|
|
|
| 748 |
)
|
| 749 |
return score
|
| 750 |
|
| 751 |
|
| 752 |
-
def discover_mcp_slugs(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 753 |
"""Enumerate every MCP server slug in the wiki entity tree.
|
| 754 |
|
| 755 |
Walks ``<wiki>/entities/mcp-servers/`` shards, collecting ``*.md``
|
| 756 |
stems that pass ``MCP_SLUG_RE``. Returns sorted list.
|
| 757 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 758 |
mcp_root = wiki_dir / "entities" / "mcp-servers"
|
| 759 |
if not mcp_root.is_dir():
|
| 760 |
return []
|
|
@@ -782,7 +844,8 @@ def recompute_all(
|
|
| 782 |
``(successes, failures)`` where failures is a list of
|
| 783 |
``(slug, exception)`` pairs.
|
| 784 |
"""
|
| 785 |
-
|
|
|
|
| 786 |
graph_index = load_graph_index(wiki_dir)
|
| 787 |
|
| 788 |
successes: list[McpQualityScore] = []
|
|
@@ -796,6 +859,7 @@ def recompute_all(
|
|
| 796 |
graph_index=graph_index,
|
| 797 |
sidecar_dir=sidecar_dir,
|
| 798 |
update_frontmatter=update_frontmatter,
|
|
|
|
| 799 |
)
|
| 800 |
successes.append(score)
|
| 801 |
except (FileNotFoundError, ValueError, OSError, ImportError) as exc:
|
|
|
|
| 46 |
from pathlib import Path
|
| 47 |
from typing import Any, Mapping
|
| 48 |
|
| 49 |
+
from ctx.core.wiki.wiki_packs import load_merged_wiki_pages, write_active_wiki_overlay_pack
|
| 50 |
from ctx.utils._fs_utils import atomic_write_text as _atomic_write
|
| 51 |
+
from ctx.utils._fs_utils import reject_symlink_path, safe_atomic_write_text
|
| 52 |
from mcp_entity import MCP_SLUG_RE, McpRecord
|
| 53 |
from ctx.core.quality.quality_signals import SignalResult
|
| 54 |
from ctx.core.wiki.wiki_utils import parse_frontmatter_and_body
|
|
|
|
| 288 |
return wiki_dir / "entities" / "mcp-servers" / shard / f"{slug}.md"
|
| 289 |
|
| 290 |
|
| 291 |
+
def _mcp_entity_relpath(slug: str) -> str:
|
| 292 |
+
path = _resolve_mcp_entity_path(slug, Path("."))
|
| 293 |
+
return path.as_posix()
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _load_active_wiki_pack_pages(wiki_dir: Path) -> dict[str, str] | None:
|
| 297 |
+
packs_dir = wiki_dir / "wiki-packs"
|
| 298 |
+
if not packs_dir.is_dir():
|
| 299 |
+
return None
|
| 300 |
+
return load_merged_wiki_pages(packs_dir)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def _read_mcp_entity_text(
|
| 304 |
+
slug: str,
|
| 305 |
+
wiki_dir: Path,
|
| 306 |
+
*,
|
| 307 |
+
pages: dict[str, str] | None = None,
|
| 308 |
+
) -> str | None:
|
| 309 |
+
relpath = _mcp_entity_relpath(slug)
|
| 310 |
+
packs_dir = wiki_dir / "wiki-packs"
|
| 311 |
+
if packs_dir.is_dir():
|
| 312 |
+
page_map = pages if pages is not None else load_merged_wiki_pages(packs_dir)
|
| 313 |
+
if relpath in page_map:
|
| 314 |
+
return page_map[relpath]
|
| 315 |
+
path = _resolve_mcp_entity_path(slug, wiki_dir)
|
| 316 |
+
if path.is_file():
|
| 317 |
+
reject_symlink_path(path)
|
| 318 |
+
return path.read_text(encoding="utf-8", errors="replace")
|
| 319 |
+
return None
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def _write_mcp_entity_text(
|
| 323 |
+
slug: str,
|
| 324 |
+
wiki_dir: Path,
|
| 325 |
+
text: str,
|
| 326 |
+
*,
|
| 327 |
+
pages: dict[str, str] | None = None,
|
| 328 |
+
) -> Path:
|
| 329 |
+
relpath = _mcp_entity_relpath(slug)
|
| 330 |
+
path = _resolve_mcp_entity_path(slug, wiki_dir)
|
| 331 |
+
packs_dir = wiki_dir / "wiki-packs"
|
| 332 |
+
if path.exists() or not packs_dir.is_dir():
|
| 333 |
+
safe_atomic_write_text(path, text, encoding="utf-8")
|
| 334 |
+
if packs_dir.is_dir():
|
| 335 |
+
write_active_wiki_overlay_pack(
|
| 336 |
+
packs_dir=packs_dir,
|
| 337 |
+
pages={relpath: text},
|
| 338 |
+
tombstones=[],
|
| 339 |
+
)
|
| 340 |
+
if pages is not None:
|
| 341 |
+
pages[relpath] = text
|
| 342 |
+
return path
|
| 343 |
+
|
| 344 |
+
|
| 345 |
def _read_mcp_entity(
|
| 346 |
+
slug: str,
|
| 347 |
+
wiki_dir: Path,
|
| 348 |
+
*,
|
| 349 |
+
pages: dict[str, str] | None = None,
|
| 350 |
) -> tuple[McpRecord, dict[str, Any]]:
|
| 351 |
"""Read entity .md, parse frontmatter, reconstruct McpRecord.
|
| 352 |
|
|
|
|
| 363 |
ValueError: If the frontmatter cannot produce a valid McpRecord.
|
| 364 |
"""
|
| 365 |
path = _resolve_mcp_entity_path(slug, wiki_dir)
|
| 366 |
+
raw = _read_mcp_entity_text(slug, wiki_dir, pages=pages)
|
| 367 |
+
if raw is None:
|
| 368 |
raise FileNotFoundError(
|
| 369 |
f"MCP entity not found: {path}"
|
| 370 |
)
|
|
|
|
| 371 |
fm, _body = parse_frontmatter_and_body(raw)
|
| 372 |
# McpRecord.from_dict is tolerant of missing optional fields.
|
| 373 |
record = McpRecord.from_dict({**fm, "slug": slug})
|
|
|
|
| 380 |
|
| 381 |
|
| 382 |
def load_graph_index(wiki_dir: Path) -> dict[str, dict[str, Any]]:
|
| 383 |
+
"""Load the merged wiki graph and build a degree index.
|
| 384 |
|
| 385 |
Returns a mapping of ``{node_id: {"degree": int, "cross_type_degree": int}}``.
|
| 386 |
Cross-type degree counts neighbours whose ``node_id`` starts with a
|
| 387 |
different type prefix (e.g. ``skill:`` or ``agent:`` vs ``mcp-server:``).
|
| 388 |
+
Returns an empty dict if graph packs and legacy ``graph.json`` are both
|
| 389 |
+
missing or malformed.
|
| 390 |
"""
|
| 391 |
graph_path = wiki_dir / "graphify-out" / "graph.json"
|
| 392 |
+
packs_dir = graph_path.parent / "packs"
|
| 393 |
+
if not graph_path.is_file() and not packs_dir.is_dir():
|
| 394 |
return {}
|
| 395 |
try:
|
| 396 |
+
from ctx.core.graph.resolve_graph import load_graph # noqa: PLC0415
|
|
|
|
|
|
|
|
|
|
| 397 |
|
| 398 |
+
graph = load_graph(graph_path)
|
| 399 |
+
except Exception as exc: # noqa: BLE001 - quality recompute must keep going.
|
| 400 |
+
_logger.warning("load_graph_index: could not load %s: %s", graph_path, exc)
|
| 401 |
return {}
|
| 402 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 403 |
index: dict[str, dict[str, Any]] = {}
|
| 404 |
+
for node_id in graph.nodes:
|
| 405 |
+
if not isinstance(node_id, str):
|
| 406 |
+
continue
|
| 407 |
+
neighbours = {str(neighbour) for neighbour in graph.neighbors(node_id)}
|
| 408 |
# Derive this node's type prefix (e.g. "skill", "mcp-server").
|
| 409 |
node_prefix = node_id.split(":")[0] if ":" in node_id else ""
|
| 410 |
cross_type = sum(
|
|
|
|
| 452 |
wiki_dir: Path,
|
| 453 |
config: McpQualityConfig | None = None,
|
| 454 |
graph_index: Mapping[str, dict[str, Any]] | None = None,
|
| 455 |
+
pages: dict[str, str] | None = None,
|
| 456 |
) -> Mapping[str, SignalResult]:
|
| 457 |
"""Read entity, compute graph degrees, call all six signal functions.
|
| 458 |
|
|
|
|
| 485 |
_ensure_safe_slug(slug)
|
| 486 |
cfg = config or McpQualityConfig()
|
| 487 |
|
| 488 |
+
record, fm = _read_mcp_entity(slug, wiki_dir, pages=pages)
|
| 489 |
|
| 490 |
# Graph degrees.
|
| 491 |
node_id = f"{_MCP_NODE_PREFIX}{slug}"
|
|
|
|
| 667 |
wiki_dir: Path,
|
| 668 |
sidecar_dir: Path | None = None,
|
| 669 |
update_frontmatter: bool = True,
|
| 670 |
+
pages: dict[str, str] | None = None,
|
| 671 |
) -> dict[str, Path]:
|
| 672 |
"""Write the quality result to the three on-disk sinks atomically.
|
| 673 |
|
|
|
|
| 694 |
|
| 695 |
# Sinks 2 + 3 — entity .md (frontmatter + body).
|
| 696 |
entity_path = _resolve_mcp_entity_path(score.slug, wiki_dir)
|
| 697 |
+
raw = _read_mcp_entity_text(score.slug, wiki_dir, pages=pages)
|
| 698 |
+
if raw is None:
|
| 699 |
_logger.info(
|
| 700 |
"mcp_quality: no entity page at %s; frontmatter/body sinks skipped",
|
| 701 |
entity_path,
|
| 702 |
)
|
| 703 |
return written
|
| 704 |
|
|
|
|
|
|
|
| 705 |
# Sink 2 — frontmatter.
|
| 706 |
updated = _update_frontmatter_quality(raw, score)
|
| 707 |
|
|
|
|
| 715 |
new_body = _inject_quality_section(body, _render_quality_section(score))
|
| 716 |
updated = header + new_body
|
| 717 |
|
| 718 |
+
entity_path = _write_mcp_entity_text(score.slug, wiki_dir, updated, pages=pages)
|
| 719 |
written["frontmatter"] = entity_path
|
| 720 |
written["wiki_body"] = entity_path
|
| 721 |
|
|
|
|
| 770 |
graph_index: Mapping[str, dict[str, Any]] | None = None,
|
| 771 |
sidecar_dir: Path | None = None,
|
| 772 |
update_frontmatter: bool = True,
|
| 773 |
+
pages: dict[str, str] | None = None,
|
| 774 |
) -> McpQualityScore:
|
| 775 |
"""End-to-end recompute: extract signals → compute → persist."""
|
| 776 |
signals = extract_signals_for_slug(
|
|
|
|
| 778 |
wiki_dir=wiki_dir,
|
| 779 |
config=config,
|
| 780 |
graph_index=graph_index,
|
| 781 |
+
pages=pages,
|
| 782 |
)
|
| 783 |
score = compute_quality(
|
| 784 |
slug=slug,
|
|
|
|
| 791 |
wiki_dir=wiki_dir,
|
| 792 |
sidecar_dir=sidecar_dir,
|
| 793 |
update_frontmatter=update_frontmatter,
|
| 794 |
+
pages=pages,
|
| 795 |
)
|
| 796 |
return score
|
| 797 |
|
| 798 |
|
| 799 |
+
def discover_mcp_slugs(
|
| 800 |
+
wiki_dir: Path,
|
| 801 |
+
*,
|
| 802 |
+
pages: dict[str, str] | None = None,
|
| 803 |
+
) -> list[str]:
|
| 804 |
"""Enumerate every MCP server slug in the wiki entity tree.
|
| 805 |
|
| 806 |
Walks ``<wiki>/entities/mcp-servers/`` shards, collecting ``*.md``
|
| 807 |
stems that pass ``MCP_SLUG_RE``. Returns sorted list.
|
| 808 |
"""
|
| 809 |
+
page_map = pages if pages is not None else _load_active_wiki_pack_pages(wiki_dir)
|
| 810 |
+
if page_map is not None:
|
| 811 |
+
prefix = "entities/mcp-servers/"
|
| 812 |
+
return sorted(
|
| 813 |
+
Path(relpath).stem
|
| 814 |
+
for relpath in page_map
|
| 815 |
+
if relpath.startswith(prefix)
|
| 816 |
+
and relpath.endswith(".md")
|
| 817 |
+
and MCP_SLUG_RE.match(Path(relpath).stem)
|
| 818 |
+
)
|
| 819 |
+
|
| 820 |
mcp_root = wiki_dir / "entities" / "mcp-servers"
|
| 821 |
if not mcp_root.is_dir():
|
| 822 |
return []
|
|
|
|
| 844 |
``(successes, failures)`` where failures is a list of
|
| 845 |
``(slug, exception)`` pairs.
|
| 846 |
"""
|
| 847 |
+
pages = _load_active_wiki_pack_pages(wiki_dir)
|
| 848 |
+
slugs = discover_mcp_slugs(wiki_dir, pages=pages)
|
| 849 |
graph_index = load_graph_index(wiki_dir)
|
| 850 |
|
| 851 |
successes: list[McpQualityScore] = []
|
|
|
|
| 859 |
graph_index=graph_index,
|
| 860 |
sidecar_dir=sidecar_dir,
|
| 861 |
update_frontmatter=update_frontmatter,
|
| 862 |
+
pages=pages,
|
| 863 |
)
|
| 864 |
successes.append(score)
|
| 865 |
except (FileNotFoundError, ValueError, OSError, ImportError) as exc:
|
src/mcp_rebuild_index.py
CHANGED
|
@@ -1,25 +1,19 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
mcp_rebuild_index.py -- Rebuild the canonical-key sidecar index
|
| 4 |
|
| 5 |
Usage
|
| 6 |
-----
|
| 7 |
ctx-mcp-rebuild-index [--wiki PATH] [--dry-run]
|
| 8 |
|
| 9 |
-
Reads
|
| 10 |
-
YAML frontmatter, and writes
|
| 11 |
-
``<wiki>/entities/mcp-servers/.canonical-index.json`` with a fresh
|
| 12 |
-
``github_url -> {slug, relpath}`` map.
|
| 13 |
|
| 14 |
-
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
- Any time the index is suspected stale (manual edits, restored from
|
| 20 |
-
backup, cross-wiki merge). The normal scan-and-repair fallback in
|
| 21 |
-
``_find_existing_by_github_url`` handles one-off drift, but a full
|
| 22 |
-
rebuild is cheap (~1 s at 15k entities) and gives a clean baseline.
|
| 23 |
|
| 24 |
Exit codes: 0 on success, 2 on missing wiki path, 1 on unexpected error.
|
| 25 |
"""
|
|
@@ -60,52 +54,31 @@ def main() -> None:
|
|
| 60 |
|
| 61 |
wiki_path = Path(os.path.expanduser(args.wiki))
|
| 62 |
mcp_dir = wiki_path / _MCP_ENTITY_SUBDIR
|
|
|
|
| 63 |
|
| 64 |
-
if not mcp_dir.is_dir():
|
| 65 |
print(
|
| 66 |
-
f"Error: MCP entity directory
|
| 67 |
file=sys.stderr,
|
| 68 |
)
|
| 69 |
sys.exit(2)
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
if args.dry_run:
|
| 72 |
-
# Dry-run uses the same traversal but discards the write. Easiest
|
| 73 |
-
# way is to call the real rebuild, then overwrite the file back
|
| 74 |
-
# — but that's still a write. Instead, walk inline and count.
|
| 75 |
-
indexed = 0
|
| 76 |
-
skipped = 0
|
| 77 |
-
for page in mcp_dir.rglob("*.md"):
|
| 78 |
-
if page.name.startswith("."):
|
| 79 |
-
skipped += 1
|
| 80 |
-
continue
|
| 81 |
-
# Lazy import to match the module pattern.
|
| 82 |
-
from mcp_add import _normalize_github_url, _parse_frontmatter # noqa: PLC0415
|
| 83 |
-
try:
|
| 84 |
-
text = page.read_text(encoding="utf-8", errors="replace")
|
| 85 |
-
except OSError:
|
| 86 |
-
skipped += 1
|
| 87 |
-
continue
|
| 88 |
-
fm = _parse_frontmatter(text)
|
| 89 |
-
if _normalize_github_url(fm.get("github_url")) is None:
|
| 90 |
-
skipped += 1
|
| 91 |
-
else:
|
| 92 |
-
indexed += 1
|
| 93 |
print(
|
| 94 |
f"[dry-run] would index {indexed} entities, "
|
| 95 |
f"skip {skipped} (no github_url or unreadable)."
|
| 96 |
)
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
print(f"Error: rebuild failed: {exc}", file=sys.stderr)
|
| 103 |
-
sys.exit(1)
|
| 104 |
-
|
| 105 |
-
print(
|
| 106 |
-
f"Canonical index rebuilt: {indexed} entities indexed, "
|
| 107 |
-
f"{skipped} skipped (no github_url)."
|
| 108 |
-
)
|
| 109 |
sys.exit(0)
|
| 110 |
|
| 111 |
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
mcp_rebuild_index.py -- Rebuild the canonical-key sidecar index for MCP entities.
|
| 4 |
|
| 5 |
Usage
|
| 6 |
-----
|
| 7 |
ctx-mcp-rebuild-index [--wiki PATH] [--dry-run]
|
| 8 |
|
| 9 |
+
Reads MCP entity markdown from either:
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
- ``<wiki>/wiki-packs`` when modular wiki packs are active, or
|
| 12 |
+
- ``<wiki>/entities/mcp-servers/`` for an extracted/editable wiki tree.
|
| 13 |
|
| 14 |
+
It writes ``<wiki>/entities/mcp-servers/.canonical-index.json`` with a fresh
|
| 15 |
+
``github_url -> {slug, relpath}`` map. The sidecar is a cache; the merged wiki
|
| 16 |
+
page set remains authoritative.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
Exit codes: 0 on success, 2 on missing wiki path, 1 on unexpected error.
|
| 19 |
"""
|
|
|
|
| 54 |
|
| 55 |
wiki_path = Path(os.path.expanduser(args.wiki))
|
| 56 |
mcp_dir = wiki_path / _MCP_ENTITY_SUBDIR
|
| 57 |
+
packs_dir = wiki_path / "wiki-packs"
|
| 58 |
|
| 59 |
+
if not mcp_dir.is_dir() and not packs_dir.is_dir():
|
| 60 |
print(
|
| 61 |
+
f"Error: MCP entity directory or wiki-packs do not exist under: {wiki_path}",
|
| 62 |
file=sys.stderr,
|
| 63 |
)
|
| 64 |
sys.exit(2)
|
| 65 |
|
| 66 |
+
try:
|
| 67 |
+
_, indexed, skipped = rebuild_from_scan(mcp_dir, persist=not args.dry_run)
|
| 68 |
+
except Exception as exc: # noqa: BLE001 - surface any failure to operator.
|
| 69 |
+
print(f"Error: rebuild failed: {exc}", file=sys.stderr)
|
| 70 |
+
sys.exit(1)
|
| 71 |
+
|
| 72 |
if args.dry_run:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
print(
|
| 74 |
f"[dry-run] would index {indexed} entities, "
|
| 75 |
f"skip {skipped} (no github_url or unreadable)."
|
| 76 |
)
|
| 77 |
+
else:
|
| 78 |
+
print(
|
| 79 |
+
f"Canonical index rebuilt: {indexed} entities indexed, "
|
| 80 |
+
f"{skipped} skipped (no github_url)."
|
| 81 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
sys.exit(0)
|
| 83 |
|
| 84 |
|
src/scan_repo.py
CHANGED
|
@@ -125,19 +125,22 @@ def scan_directory(repo_path: str, max_depth: int = MAX_DEPTH) -> dict:
|
|
| 125 |
def read_json_safe(path: str) -> dict | None:
|
| 126 |
"""Read a JSON file, return None on failure."""
|
| 127 |
try:
|
| 128 |
-
with open(path) as f:
|
| 129 |
return json.load(f)
|
| 130 |
except Exception as exc:
|
| 131 |
print(f"Warning: failed to read JSON file {path}: {exc}", file=sys.stderr)
|
| 132 |
return None
|
| 133 |
|
| 134 |
|
| 135 |
-
def read_toml_deps(path: str) -> list[str]:
|
| 136 |
"""Extract dependency names from pyproject.toml.
|
| 137 |
|
| 138 |
Covers PEP 621 ``[project].dependencies`` / ``optional-dependencies`` and
|
| 139 |
Poetry-style ``[tool.poetry].dependencies`` / ``dev-dependencies``. Version
|
| 140 |
-
specifiers and extras are stripped via PEP 508 splitting.
|
|
|
|
|
|
|
|
|
|
| 141 |
"""
|
| 142 |
try:
|
| 143 |
data = tomllib.loads(Path(path).read_text(encoding="utf-8-sig"))
|
|
@@ -152,15 +155,17 @@ def read_toml_deps(path: str) -> list[str]:
|
|
| 152 |
deps = project.get("dependencies", [])
|
| 153 |
if isinstance(deps, list):
|
| 154 |
raw.extend(d for d in deps if isinstance(d, str))
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
|
|
|
| 160 |
|
| 161 |
poetry = data.get("tool", {}).get("poetry", {}) if isinstance(data.get("tool"), dict) else {}
|
| 162 |
if isinstance(poetry, dict):
|
| 163 |
-
|
|
|
|
| 164 |
deps = poetry.get(key, {})
|
| 165 |
if isinstance(deps, dict):
|
| 166 |
raw.extend(k for k in deps.keys() if isinstance(k, str) and k.lower() != "python")
|
|
@@ -222,6 +227,7 @@ def detect_stack(repo_path: str, signals: dict) -> dict:
|
|
| 222 |
|
| 223 |
# Collect all deps from Python and JS configs
|
| 224 |
all_py_deps: list[str] = []
|
|
|
|
| 225 |
all_js_deps: list[str] = []
|
| 226 |
pkg_json = None
|
| 227 |
|
|
@@ -229,10 +235,15 @@ def detect_stack(repo_path: str, signals: dict) -> dict:
|
|
| 229 |
base = os.path.basename(cfg)
|
| 230 |
if base == "pyproject.toml":
|
| 231 |
all_py_deps.extend(read_toml_deps(cfg))
|
|
|
|
| 232 |
elif base == "requirements.txt":
|
| 233 |
-
|
|
|
|
|
|
|
| 234 |
elif base == "Pipfile":
|
| 235 |
-
|
|
|
|
|
|
|
| 236 |
elif base == "package.json":
|
| 237 |
data = read_json_safe(cfg)
|
| 238 |
if data:
|
|
@@ -242,6 +253,7 @@ def detect_stack(repo_path: str, signals: dict) -> dict:
|
|
| 242 |
all_js_deps.extend(k.lower() for k in data[section])
|
| 243 |
|
| 244 |
py_dep_set = set(all_py_deps)
|
|
|
|
| 245 |
js_dep_set = set(all_js_deps)
|
| 246 |
|
| 247 |
# --- LANGUAGES ---
|
|
@@ -540,6 +552,14 @@ def detect_stack(repo_path: str, signals: dict) -> dict:
|
|
| 540 |
|
| 541 |
# --- PROJECT TYPE ---
|
| 542 |
fw_names = {f["name"] for f in profile["frameworks"]}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 543 |
if fw_names & {"react", "vue", "angular", "svelte", "nextjs", "nuxt"}:
|
| 544 |
if fw_names & {"fastapi", "django", "flask", "express", "nestjs"}:
|
| 545 |
profile["project_type"] = "fullstack"
|
|
@@ -547,9 +567,9 @@ def detect_stack(repo_path: str, signals: dict) -> dict:
|
|
| 547 |
profile["project_type"] = "frontend"
|
| 548 |
elif fw_names & {"fastapi", "django", "flask", "express", "nestjs", "gin", "actix"}:
|
| 549 |
profile["project_type"] = "api-service"
|
| 550 |
-
elif fw_names & {"pytorch", "tensorflow", "huggingface"}:
|
| 551 |
profile["project_type"] = "ml-project"
|
| 552 |
-
elif fw_names & {"langchain", "llamaindex", "crewai"}:
|
| 553 |
profile["project_type"] = "ai-agent"
|
| 554 |
elif profile["infrastructure"]:
|
| 555 |
profile["project_type"] = "infrastructure"
|
|
@@ -588,8 +608,6 @@ def _shared_recommendations(profile: dict) -> list[dict[str, Any]] | None:
|
|
| 588 |
from ctx_config import cfg # noqa: PLC0415
|
| 589 |
|
| 590 |
graph_path = cfg.wiki_dir / "graphify-out" / "graph.json"
|
| 591 |
-
if not graph_path.is_file():
|
| 592 |
-
return None
|
| 593 |
graph = load_graph(graph_path)
|
| 594 |
if graph.number_of_nodes() == 0:
|
| 595 |
return None
|
|
|
|
| 125 |
def read_json_safe(path: str) -> dict | None:
|
| 126 |
"""Read a JSON file, return None on failure."""
|
| 127 |
try:
|
| 128 |
+
with open(path, encoding="utf-8-sig") as f:
|
| 129 |
return json.load(f)
|
| 130 |
except Exception as exc:
|
| 131 |
print(f"Warning: failed to read JSON file {path}: {exc}", file=sys.stderr)
|
| 132 |
return None
|
| 133 |
|
| 134 |
|
| 135 |
+
def read_toml_deps(path: str, *, include_optional: bool = True) -> list[str]:
|
| 136 |
"""Extract dependency names from pyproject.toml.
|
| 137 |
|
| 138 |
Covers PEP 621 ``[project].dependencies`` / ``optional-dependencies`` and
|
| 139 |
Poetry-style ``[tool.poetry].dependencies`` / ``dev-dependencies``. Version
|
| 140 |
+
specifiers and extras are stripped via PEP 508 splitting. Callers can set
|
| 141 |
+
``include_optional=False`` when deciding the primary project type; optional
|
| 142 |
+
extras should remain searchable signals but should not make a docs/tooling
|
| 143 |
+
repo look like an ML project just because it offers an embeddings extra.
|
| 144 |
"""
|
| 145 |
try:
|
| 146 |
data = tomllib.loads(Path(path).read_text(encoding="utf-8-sig"))
|
|
|
|
| 155 |
deps = project.get("dependencies", [])
|
| 156 |
if isinstance(deps, list):
|
| 157 |
raw.extend(d for d in deps if isinstance(d, str))
|
| 158 |
+
if include_optional:
|
| 159 |
+
opt = project.get("optional-dependencies", {})
|
| 160 |
+
if isinstance(opt, dict):
|
| 161 |
+
for group in opt.values():
|
| 162 |
+
if isinstance(group, list):
|
| 163 |
+
raw.extend(d for d in group if isinstance(d, str))
|
| 164 |
|
| 165 |
poetry = data.get("tool", {}).get("poetry", {}) if isinstance(data.get("tool"), dict) else {}
|
| 166 |
if isinstance(poetry, dict):
|
| 167 |
+
keys = ("dependencies", "dev-dependencies") if include_optional else ("dependencies",)
|
| 168 |
+
for key in keys:
|
| 169 |
deps = poetry.get(key, {})
|
| 170 |
if isinstance(deps, dict):
|
| 171 |
raw.extend(k for k in deps.keys() if isinstance(k, str) and k.lower() != "python")
|
|
|
|
| 227 |
|
| 228 |
# Collect all deps from Python and JS configs
|
| 229 |
all_py_deps: list[str] = []
|
| 230 |
+
core_py_deps: list[str] = []
|
| 231 |
all_js_deps: list[str] = []
|
| 232 |
pkg_json = None
|
| 233 |
|
|
|
|
| 235 |
base = os.path.basename(cfg)
|
| 236 |
if base == "pyproject.toml":
|
| 237 |
all_py_deps.extend(read_toml_deps(cfg))
|
| 238 |
+
core_py_deps.extend(read_toml_deps(cfg, include_optional=False))
|
| 239 |
elif base == "requirements.txt":
|
| 240 |
+
deps = read_requirements(cfg)
|
| 241 |
+
all_py_deps.extend(deps)
|
| 242 |
+
core_py_deps.extend(deps)
|
| 243 |
elif base == "Pipfile":
|
| 244 |
+
deps = read_requirements(cfg)
|
| 245 |
+
all_py_deps.extend(deps)
|
| 246 |
+
core_py_deps.extend(deps)
|
| 247 |
elif base == "package.json":
|
| 248 |
data = read_json_safe(cfg)
|
| 249 |
if data:
|
|
|
|
| 253 |
all_js_deps.extend(k.lower() for k in data[section])
|
| 254 |
|
| 255 |
py_dep_set = set(all_py_deps)
|
| 256 |
+
py_core_dep_set = set(core_py_deps)
|
| 257 |
js_dep_set = set(all_js_deps)
|
| 258 |
|
| 259 |
# --- LANGUAGES ---
|
|
|
|
| 552 |
|
| 553 |
# --- PROJECT TYPE ---
|
| 554 |
fw_names = {f["name"] for f in profile["frameworks"]}
|
| 555 |
+
core_ml_deps = py_core_dep_set & {"torch", "pytorch", "tensorflow", "transformers"}
|
| 556 |
+
core_ai_deps = py_core_dep_set & {
|
| 557 |
+
"langchain",
|
| 558 |
+
"langchain-core",
|
| 559 |
+
"llama-index",
|
| 560 |
+
"crewai",
|
| 561 |
+
"dspy-ai",
|
| 562 |
+
}
|
| 563 |
if fw_names & {"react", "vue", "angular", "svelte", "nextjs", "nuxt"}:
|
| 564 |
if fw_names & {"fastapi", "django", "flask", "express", "nestjs"}:
|
| 565 |
profile["project_type"] = "fullstack"
|
|
|
|
| 567 |
profile["project_type"] = "frontend"
|
| 568 |
elif fw_names & {"fastapi", "django", "flask", "express", "nestjs", "gin", "actix"}:
|
| 569 |
profile["project_type"] = "api-service"
|
| 570 |
+
elif (fw_names & {"pytorch", "tensorflow", "huggingface"}) and core_ml_deps:
|
| 571 |
profile["project_type"] = "ml-project"
|
| 572 |
+
elif (fw_names & {"langchain", "llamaindex", "crewai"}) and core_ai_deps:
|
| 573 |
profile["project_type"] = "ai-agent"
|
| 574 |
elif profile["infrastructure"]:
|
| 575 |
profile["project_type"] = "infrastructure"
|
|
|
|
| 608 |
from ctx_config import cfg # noqa: PLC0415
|
| 609 |
|
| 610 |
graph_path = cfg.wiki_dir / "graphify-out" / "graph.json"
|
|
|
|
|
|
|
| 611 |
graph = load_graph(graph_path)
|
| 612 |
if graph.number_of_nodes() == 0:
|
| 613 |
return None
|
src/skill_add.py
CHANGED
|
@@ -22,10 +22,18 @@ from pathlib import Path
|
|
| 22 |
|
| 23 |
from batch_convert import convert_skill
|
| 24 |
from ctx.core.entity_update import build_update_review, render_update_review
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
from ctx_config import cfg
|
| 26 |
from intake_pipeline import IntakeRejected, check_intake, record_embedding
|
| 27 |
from ctx.adapters.claude_code.install.install_utils import safe_copy_file
|
| 28 |
from ctx.core.wiki.wiki_queue import enqueue_entity_upsert
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
from ctx.core.wiki.wiki_sync import append_log, ensure_wiki, update_index
|
| 30 |
from ctx.core.wiki.wiki_utils import parse_frontmatter, validate_skill_name
|
| 31 |
from ctx.utils._fs_utils import reject_symlink_path, safe_atomic_write_text
|
|
@@ -104,6 +112,7 @@ def build_entity_page(
|
|
| 104 |
original_path: Path,
|
| 105 |
related: list[str],
|
| 106 |
scan_sources: list[str],
|
|
|
|
| 107 |
) -> str:
|
| 108 |
"""Render the full entity page markdown for a skill."""
|
| 109 |
pipeline_path_str = (
|
|
@@ -131,6 +140,11 @@ def build_entity_page(
|
|
| 131 |
}
|
| 132 |
if scan_sources:
|
| 133 |
fm_dict["sources"] = scan_sources
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
frontmatter_body = yaml.safe_dump(fm_dict, default_flow_style=False, allow_unicode=True, sort_keys=False)
|
| 136 |
frontmatter_block = f"---\n{frontmatter_body}---"
|
|
@@ -145,6 +159,16 @@ def build_entity_page(
|
|
| 145 |
else f"Skill is {line_count} lines — under the {cfg.line_threshold}-line threshold, no pipeline generated."
|
| 146 |
)
|
| 147 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
return frontmatter_block + f"""
|
| 149 |
|
| 150 |
# {name}
|
|
@@ -166,18 +190,67 @@ def build_entity_page(
|
|
| 166 |
| Date | Action | Notes |
|
| 167 |
|------|--------|-------|
|
| 168 |
| {TODAY} | Added | Ingested via skill_add.py |
|
|
|
|
| 169 |
"""
|
| 170 |
|
| 171 |
|
| 172 |
def write_entity_page(wiki_path: Path, name: str, content: str) -> bool:
|
| 173 |
"""Write entity page. Returns True if newly created."""
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
is_new = not page.exists()
|
| 177 |
-
safe_atomic_write_text(page, content, encoding="utf-8")
|
| 178 |
return is_new
|
| 179 |
|
| 180 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
# ── Wikilink backfill ─────────────────────────────────────────────────────────
|
| 182 |
|
| 183 |
def _tag_set_from_frontmatter(raw: object) -> set[str]:
|
|
@@ -194,9 +267,12 @@ def _tag_set_from_frontmatter(raw: object) -> set[str]:
|
|
| 194 |
|
| 195 |
|
| 196 |
def _existing_skill_review_text(entity_page: Path, installed_path: Path) -> str:
|
|
|
|
| 197 |
if entity_page.exists():
|
| 198 |
reject_symlink_path(entity_page)
|
| 199 |
-
|
|
|
|
|
|
|
| 200 |
if installed_path.exists():
|
| 201 |
reject_symlink_path(installed_path)
|
| 202 |
installed = installed_path.read_text(encoding="utf-8", errors="replace")
|
|
@@ -229,28 +305,24 @@ def _proposed_skill_review_text(
|
|
| 229 |
|
| 230 |
def find_related_skills(wiki_path: Path, name: str, tags: list[str]) -> list[str]:
|
| 231 |
"""Scan existing entity pages for skills that share at least one tag."""
|
| 232 |
-
skills_dir = wiki_path / "entities" / "skills"
|
| 233 |
related: list[str] = []
|
| 234 |
tag_set = set(tags) - {"uncategorized"}
|
| 235 |
|
| 236 |
-
for
|
| 237 |
-
if
|
| 238 |
continue
|
| 239 |
-
content = page.read_text(encoding="utf-8", errors="replace")
|
| 240 |
page_tags = _tag_set_from_frontmatter(parse_frontmatter(content).get("tags"))
|
| 241 |
if tag_set & page_tags:
|
| 242 |
-
related.append(
|
| 243 |
|
| 244 |
return related
|
| 245 |
|
| 246 |
|
| 247 |
def _add_backlink(wiki_path: Path, target_name: str, source_name: str) -> None:
|
| 248 |
"""Add a [[wikilink]] from target page back to source if not already present."""
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
if not page.exists():
|
| 252 |
return
|
| 253 |
-
content = page.read_text(encoding="utf-8", errors="replace")
|
| 254 |
link = f"[[entities/skills/{source_name}]]"
|
| 255 |
if link in content:
|
| 256 |
return
|
|
@@ -263,7 +335,7 @@ def _add_backlink(wiki_path: Path, target_name: str, source_name: str) -> None:
|
|
| 263 |
)
|
| 264 |
else:
|
| 265 |
content = content.rstrip() + f"\n\n- {link}\n"
|
| 266 |
-
|
| 267 |
|
| 268 |
|
| 269 |
def wire_backlinks(wiki_path: Path, name: str, related: list[str]) -> None:
|
|
@@ -300,6 +372,12 @@ def add_skill(
|
|
| 300 |
skills_dir: Path,
|
| 301 |
review_existing: bool = False,
|
| 302 |
update_existing: bool = False,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
) -> dict:
|
| 304 |
"""Add a single skill: install, convert if needed, ingest into wiki.
|
| 305 |
|
|
@@ -316,17 +394,15 @@ def add_skill(
|
|
| 316 |
f"Split the skill or trim content before ingestion."
|
| 317 |
)
|
| 318 |
|
| 319 |
-
content = source_path.read_text(encoding="utf-8", errors="replace")
|
| 320 |
line_count = len(content.splitlines())
|
| 321 |
|
| 322 |
installed_path = skills_dir / name / "SKILL.md"
|
| 323 |
entity_page = wiki_path / "entities" / "skills" / f"{name}.md"
|
| 324 |
-
|
| 325 |
-
installed_path
|
| 326 |
-
|
| 327 |
-
else entity_page if entity_page.exists() else None
|
| 328 |
)
|
| 329 |
-
has_existing = existing_path is not None
|
| 330 |
tags = infer_tags(name, content)
|
| 331 |
|
| 332 |
if review_existing and has_existing and not update_existing:
|
|
@@ -353,6 +429,21 @@ def add_skill(
|
|
| 353 |
"update_review": render_update_review(review),
|
| 354 |
}
|
| 355 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
if not has_existing:
|
| 357 |
# Intake gate: reject broken/duplicate candidates before we touch
|
| 358 |
# skills-dir. Existing updates bypass similarity intake because
|
|
@@ -388,7 +479,7 @@ def add_skill(
|
|
| 388 |
|
| 389 |
# Ensure at least 2 wikilinks (pad with first two related even if no tag match)
|
| 390 |
all_entity_pages = sorted(
|
| 391 |
-
|
| 392 |
)
|
| 393 |
while len(related) < 2 and len(all_entity_pages) > len(related):
|
| 394 |
candidate = all_entity_pages[len(related)]
|
|
@@ -404,6 +495,7 @@ def add_skill(
|
|
| 404 |
original_path=installed_path,
|
| 405 |
related=related,
|
| 406 |
scan_sources=scan_sources,
|
|
|
|
| 407 |
)
|
| 408 |
is_new = write_entity_page(wiki_path, name, page_content)
|
| 409 |
|
|
@@ -451,6 +543,9 @@ def add_skill(
|
|
| 451 |
"converted": converted,
|
| 452 |
"tags": tags,
|
| 453 |
"related": related,
|
|
|
|
|
|
|
|
|
|
| 454 |
},
|
| 455 |
)
|
| 456 |
if converted:
|
|
@@ -469,6 +564,7 @@ def add_skill(
|
|
| 469 |
"skipped": False,
|
| 470 |
"update_required": False,
|
| 471 |
"queued_job_id": queue_job.id,
|
|
|
|
| 472 |
}
|
| 473 |
|
| 474 |
|
|
@@ -485,6 +581,32 @@ def main() -> None:
|
|
| 485 |
action="store_true",
|
| 486 |
help="Apply the reviewed replacement when a skill already exists",
|
| 487 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 488 |
parser.add_argument("--wiki", default=str(cfg.wiki_dir), help="Wiki path")
|
| 489 |
parser.add_argument("--skills-dir", default=str(cfg.skills_dir), help="Skills install path")
|
| 490 |
args = parser.parse_args()
|
|
@@ -533,7 +655,10 @@ def main() -> None:
|
|
| 533 |
total = len(candidates)
|
| 534 |
for i, (source_path, name) in enumerate(candidates, 1):
|
| 535 |
# Skip if already installed and --skip-existing is set
|
| 536 |
-
if args.skip_existing and (
|
|
|
|
|
|
|
|
|
|
| 537 |
skipped += 1
|
| 538 |
if skipped <= 5 or skipped % 100 == 0:
|
| 539 |
print(f" [{i}/{total}] [skipped] {name}")
|
|
@@ -546,6 +671,13 @@ def main() -> None:
|
|
| 546 |
skills_dir=skills_dir,
|
| 547 |
review_existing=True,
|
| 548 |
update_existing=args.update_existing,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 549 |
)
|
| 550 |
if result.get("skipped"):
|
| 551 |
skipped += 1
|
|
@@ -564,7 +696,13 @@ def main() -> None:
|
|
| 564 |
if not result["is_new_page"]
|
| 565 |
else "converted" if result["converted"] else "installed"
|
| 566 |
)
|
| 567 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 568 |
except Exception as exc:
|
| 569 |
errors += 1
|
| 570 |
print(f" [{i}/{total}] ERROR: {name}: {exc}", file=sys.stderr)
|
|
@@ -573,6 +711,8 @@ def main() -> None:
|
|
| 573 |
f"\nDone: {added} added, {updated} updated, {converted} converted, "
|
| 574 |
f"{skipped} skipped, {errors} errors"
|
| 575 |
)
|
|
|
|
|
|
|
| 576 |
|
| 577 |
|
| 578 |
if __name__ == "__main__":
|
|
|
|
| 22 |
|
| 23 |
from batch_convert import convert_skill
|
| 24 |
from ctx.core.entity_update import build_update_review, render_update_review
|
| 25 |
+
from ctx.core.quality.skillspector_service import SkillSpectorResult
|
| 26 |
+
from ctx.core.quality.skillspector_service import render_scan_report
|
| 27 |
+
from ctx.core.quality.skillspector_service import run_skillspector_scan
|
| 28 |
+
from ctx.core.quality.skillspector_service import skill_scan_target
|
| 29 |
from ctx_config import cfg
|
| 30 |
from intake_pipeline import IntakeRejected, check_intake, record_embedding
|
| 31 |
from ctx.adapters.claude_code.install.install_utils import safe_copy_file
|
| 32 |
from ctx.core.wiki.wiki_queue import enqueue_entity_upsert
|
| 33 |
+
from ctx.core.wiki.wiki_packs import (
|
| 34 |
+
load_merged_wiki_pages,
|
| 35 |
+
write_active_wiki_overlay_pack,
|
| 36 |
+
)
|
| 37 |
from ctx.core.wiki.wiki_sync import append_log, ensure_wiki, update_index
|
| 38 |
from ctx.core.wiki.wiki_utils import parse_frontmatter, validate_skill_name
|
| 39 |
from ctx.utils._fs_utils import reject_symlink_path, safe_atomic_write_text
|
|
|
|
| 112 |
original_path: Path,
|
| 113 |
related: list[str],
|
| 114 |
scan_sources: list[str],
|
| 115 |
+
security_scan: SkillSpectorResult | None = None,
|
| 116 |
) -> str:
|
| 117 |
"""Render the full entity page markdown for a skill."""
|
| 118 |
pipeline_path_str = (
|
|
|
|
| 140 |
}
|
| 141 |
if scan_sources:
|
| 142 |
fm_dict["sources"] = scan_sources
|
| 143 |
+
if security_scan is not None:
|
| 144 |
+
fm_dict["skillspector_checked"] = True
|
| 145 |
+
fm_dict["skillspector_status"] = security_scan.status
|
| 146 |
+
fm_dict["skillspector_exit_code"] = security_scan.exit_code
|
| 147 |
+
fm_dict["skillspector_note"] = "ctx-run SkillSpector check; not NVIDIA endorsement"
|
| 148 |
|
| 149 |
frontmatter_body = yaml.safe_dump(fm_dict, default_flow_style=False, allow_unicode=True, sort_keys=False)
|
| 150 |
frontmatter_block = f"---\n{frontmatter_body}---"
|
|
|
|
| 159 |
else f"Skill is {line_count} lines — under the {cfg.line_threshold}-line threshold, no pipeline generated."
|
| 160 |
)
|
| 161 |
|
| 162 |
+
security_section = ""
|
| 163 |
+
if security_scan is not None:
|
| 164 |
+
security_section = f"""
|
| 165 |
+
|
| 166 |
+
## Security Check
|
| 167 |
+
|
| 168 |
+
SkillSpector status: `{security_scan.status}`.
|
| 169 |
+
This is a ctx-run check, not NVIDIA endorsement or certification.
|
| 170 |
+
"""
|
| 171 |
+
|
| 172 |
return frontmatter_block + f"""
|
| 173 |
|
| 174 |
# {name}
|
|
|
|
| 190 |
| Date | Action | Notes |
|
| 191 |
|------|--------|-------|
|
| 192 |
| {TODAY} | Added | Ingested via skill_add.py |
|
| 193 |
+
{security_section}
|
| 194 |
"""
|
| 195 |
|
| 196 |
|
| 197 |
def write_entity_page(wiki_path: Path, name: str, content: str) -> bool:
|
| 198 |
"""Write entity page. Returns True if newly created."""
|
| 199 |
+
is_new = _read_entity_page_text(wiki_path, name) is None
|
| 200 |
+
_write_entity_page_text(wiki_path, name, content)
|
|
|
|
|
|
|
| 201 |
return is_new
|
| 202 |
|
| 203 |
|
| 204 |
+
def _skill_relpath(name: str) -> str:
|
| 205 |
+
return f"entities/skills/{name}.md"
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def _read_entity_page_text(wiki_path: Path, name: str) -> str | None:
|
| 209 |
+
relpath = _skill_relpath(name)
|
| 210 |
+
page = wiki_path / relpath
|
| 211 |
+
if page.exists():
|
| 212 |
+
reject_symlink_path(page)
|
| 213 |
+
packs_dir = wiki_path / "wiki-packs"
|
| 214 |
+
if packs_dir.is_dir():
|
| 215 |
+
pages = load_merged_wiki_pages(packs_dir)
|
| 216 |
+
if relpath in pages:
|
| 217 |
+
return pages[relpath]
|
| 218 |
+
if page.exists():
|
| 219 |
+
return page.read_text(encoding="utf-8", errors="replace")
|
| 220 |
+
return None
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def _write_entity_page_text(wiki_path: Path, name: str, content: str) -> None:
|
| 224 |
+
relpath = _skill_relpath(name)
|
| 225 |
+
page = wiki_path / relpath
|
| 226 |
+
packs_dir = wiki_path / "wiki-packs"
|
| 227 |
+
if page.exists() or not packs_dir.is_dir():
|
| 228 |
+
reject_symlink_path(page)
|
| 229 |
+
safe_atomic_write_text(page, content, encoding="utf-8")
|
| 230 |
+
if packs_dir.is_dir():
|
| 231 |
+
write_active_wiki_overlay_pack(
|
| 232 |
+
packs_dir=packs_dir,
|
| 233 |
+
pages={relpath: content},
|
| 234 |
+
tombstones=[],
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def _load_skill_pages(wiki_path: Path) -> dict[str, str]:
|
| 239 |
+
packs_dir = wiki_path / "wiki-packs"
|
| 240 |
+
if packs_dir.is_dir():
|
| 241 |
+
return {
|
| 242 |
+
Path(relpath).stem: text
|
| 243 |
+
for relpath, text in load_merged_wiki_pages(packs_dir).items()
|
| 244 |
+
if relpath.startswith("entities/skills/") and relpath.endswith(".md")
|
| 245 |
+
}
|
| 246 |
+
skills_dir = wiki_path / "entities" / "skills"
|
| 247 |
+
pages: dict[str, str] = {}
|
| 248 |
+
for page in sorted(skills_dir.glob("*.md")):
|
| 249 |
+
reject_symlink_path(page)
|
| 250 |
+
pages[page.stem] = page.read_text(encoding="utf-8", errors="replace")
|
| 251 |
+
return pages
|
| 252 |
+
|
| 253 |
+
|
| 254 |
# ── Wikilink backfill ─────────────────────────────────────────────────────────
|
| 255 |
|
| 256 |
def _tag_set_from_frontmatter(raw: object) -> set[str]:
|
|
|
|
| 267 |
|
| 268 |
|
| 269 |
def _existing_skill_review_text(entity_page: Path, installed_path: Path) -> str:
|
| 270 |
+
wiki_path = entity_page.parents[2]
|
| 271 |
if entity_page.exists():
|
| 272 |
reject_symlink_path(entity_page)
|
| 273 |
+
existing_page = _read_entity_page_text(wiki_path, entity_page.stem)
|
| 274 |
+
if existing_page is not None:
|
| 275 |
+
existing = existing_page
|
| 276 |
if installed_path.exists():
|
| 277 |
reject_symlink_path(installed_path)
|
| 278 |
installed = installed_path.read_text(encoding="utf-8", errors="replace")
|
|
|
|
| 305 |
|
| 306 |
def find_related_skills(wiki_path: Path, name: str, tags: list[str]) -> list[str]:
|
| 307 |
"""Scan existing entity pages for skills that share at least one tag."""
|
|
|
|
| 308 |
related: list[str] = []
|
| 309 |
tag_set = set(tags) - {"uncategorized"}
|
| 310 |
|
| 311 |
+
for slug, content in sorted(_load_skill_pages(wiki_path).items()):
|
| 312 |
+
if slug == name:
|
| 313 |
continue
|
|
|
|
| 314 |
page_tags = _tag_set_from_frontmatter(parse_frontmatter(content).get("tags"))
|
| 315 |
if tag_set & page_tags:
|
| 316 |
+
related.append(slug)
|
| 317 |
|
| 318 |
return related
|
| 319 |
|
| 320 |
|
| 321 |
def _add_backlink(wiki_path: Path, target_name: str, source_name: str) -> None:
|
| 322 |
"""Add a [[wikilink]] from target page back to source if not already present."""
|
| 323 |
+
content = _read_entity_page_text(wiki_path, target_name)
|
| 324 |
+
if content is None:
|
|
|
|
| 325 |
return
|
|
|
|
| 326 |
link = f"[[entities/skills/{source_name}]]"
|
| 327 |
if link in content:
|
| 328 |
return
|
|
|
|
| 335 |
)
|
| 336 |
else:
|
| 337 |
content = content.rstrip() + f"\n\n- {link}\n"
|
| 338 |
+
_write_entity_page_text(wiki_path, target_name, content)
|
| 339 |
|
| 340 |
|
| 341 |
def wire_backlinks(wiki_path: Path, name: str, related: list[str]) -> None:
|
|
|
|
| 372 |
skills_dir: Path,
|
| 373 |
review_existing: bool = False,
|
| 374 |
update_existing: bool = False,
|
| 375 |
+
security_scan: bool = False,
|
| 376 |
+
security_scan_required: bool = False,
|
| 377 |
+
security_scan_use_llm: bool = False,
|
| 378 |
+
security_scan_command: list[str] | None = None,
|
| 379 |
+
skillspector_bin: str | None = None,
|
| 380 |
+
security_scan_timeout: int = 120,
|
| 381 |
) -> dict:
|
| 382 |
"""Add a single skill: install, convert if needed, ingest into wiki.
|
| 383 |
|
|
|
|
| 394 |
f"Split the skill or trim content before ingestion."
|
| 395 |
)
|
| 396 |
|
| 397 |
+
content = source_path.read_text(encoding="utf-8-sig", errors="replace")
|
| 398 |
line_count = len(content.splitlines())
|
| 399 |
|
| 400 |
installed_path = skills_dir / name / "SKILL.md"
|
| 401 |
entity_page = wiki_path / "entities" / "skills" / f"{name}.md"
|
| 402 |
+
has_existing = (
|
| 403 |
+
installed_path.exists()
|
| 404 |
+
or _read_entity_page_text(wiki_path, name) is not None
|
|
|
|
| 405 |
)
|
|
|
|
| 406 |
tags = infer_tags(name, content)
|
| 407 |
|
| 408 |
if review_existing and has_existing and not update_existing:
|
|
|
|
| 429 |
"update_review": render_update_review(review),
|
| 430 |
}
|
| 431 |
|
| 432 |
+
scan_result = None
|
| 433 |
+
if security_scan:
|
| 434 |
+
scan_result = run_skillspector_scan(
|
| 435 |
+
skill_scan_target(source_path),
|
| 436 |
+
command=security_scan_command,
|
| 437 |
+
binary=skillspector_bin,
|
| 438 |
+
use_llm=security_scan_use_llm,
|
| 439 |
+
timeout_seconds=security_scan_timeout,
|
| 440 |
+
)
|
| 441 |
+
if security_scan_required and scan_result.status != "passed":
|
| 442 |
+
raise ValueError(
|
| 443 |
+
"SkillSpector security scan did not pass: "
|
| 444 |
+
f"{scan_result.status}\n\n{render_scan_report(scan_result)}"
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
if not has_existing:
|
| 448 |
# Intake gate: reject broken/duplicate candidates before we touch
|
| 449 |
# skills-dir. Existing updates bypass similarity intake because
|
|
|
|
| 479 |
|
| 480 |
# Ensure at least 2 wikilinks (pad with first two related even if no tag match)
|
| 481 |
all_entity_pages = sorted(
|
| 482 |
+
slug for slug in _load_skill_pages(wiki_path) if slug != name
|
| 483 |
)
|
| 484 |
while len(related) < 2 and len(all_entity_pages) > len(related):
|
| 485 |
candidate = all_entity_pages[len(related)]
|
|
|
|
| 495 |
original_path=installed_path,
|
| 496 |
related=related,
|
| 497 |
scan_sources=scan_sources,
|
| 498 |
+
security_scan=scan_result,
|
| 499 |
)
|
| 500 |
is_new = write_entity_page(wiki_path, name, page_content)
|
| 501 |
|
|
|
|
| 543 |
"converted": converted,
|
| 544 |
"tags": tags,
|
| 545 |
"related": related,
|
| 546 |
+
"skillspector_status": (
|
| 547 |
+
scan_result.status if scan_result is not None else None
|
| 548 |
+
),
|
| 549 |
},
|
| 550 |
)
|
| 551 |
if converted:
|
|
|
|
| 564 |
"skipped": False,
|
| 565 |
"update_required": False,
|
| 566 |
"queued_job_id": queue_job.id,
|
| 567 |
+
"security_scan": scan_result.to_json() if scan_result is not None else None,
|
| 568 |
}
|
| 569 |
|
| 570 |
|
|
|
|
| 581 |
action="store_true",
|
| 582 |
help="Apply the reviewed replacement when a skill already exists",
|
| 583 |
)
|
| 584 |
+
parser.add_argument(
|
| 585 |
+
"--no-security-scan",
|
| 586 |
+
action="store_true",
|
| 587 |
+
help="Do not run SkillSpector before adding or updating a skill",
|
| 588 |
+
)
|
| 589 |
+
parser.add_argument(
|
| 590 |
+
"--security-scan-optional",
|
| 591 |
+
action="store_true",
|
| 592 |
+
help="Run SkillSpector but do not fail the add when it reports findings or is missing",
|
| 593 |
+
)
|
| 594 |
+
parser.add_argument(
|
| 595 |
+
"--security-scan-use-llm",
|
| 596 |
+
action="store_true",
|
| 597 |
+
help="Allow SkillSpector LLM analysis instead of static-only --no-llm",
|
| 598 |
+
)
|
| 599 |
+
parser.add_argument(
|
| 600 |
+
"--skillspector-bin",
|
| 601 |
+
default=None,
|
| 602 |
+
help="SkillSpector executable. Defaults to CTX_SKILLSPECTOR_BIN or 'skillspector' on PATH.",
|
| 603 |
+
)
|
| 604 |
+
parser.add_argument(
|
| 605 |
+
"--security-scan-timeout",
|
| 606 |
+
type=int,
|
| 607 |
+
default=120,
|
| 608 |
+
help="SkillSpector timeout in seconds (default: 120)",
|
| 609 |
+
)
|
| 610 |
parser.add_argument("--wiki", default=str(cfg.wiki_dir), help="Wiki path")
|
| 611 |
parser.add_argument("--skills-dir", default=str(cfg.skills_dir), help="Skills install path")
|
| 612 |
args = parser.parse_args()
|
|
|
|
| 655 |
total = len(candidates)
|
| 656 |
for i, (source_path, name) in enumerate(candidates, 1):
|
| 657 |
# Skip if already installed and --skip-existing is set
|
| 658 |
+
if args.skip_existing and (
|
| 659 |
+
(skills_dir / name / "SKILL.md").exists()
|
| 660 |
+
or _read_entity_page_text(wiki_path, name) is not None
|
| 661 |
+
):
|
| 662 |
skipped += 1
|
| 663 |
if skipped <= 5 or skipped % 100 == 0:
|
| 664 |
print(f" [{i}/{total}] [skipped] {name}")
|
|
|
|
| 671 |
skills_dir=skills_dir,
|
| 672 |
review_existing=True,
|
| 673 |
update_existing=args.update_existing,
|
| 674 |
+
security_scan=not args.no_security_scan,
|
| 675 |
+
security_scan_required=(
|
| 676 |
+
not args.no_security_scan and not args.security_scan_optional
|
| 677 |
+
),
|
| 678 |
+
security_scan_use_llm=args.security_scan_use_llm,
|
| 679 |
+
skillspector_bin=args.skillspector_bin,
|
| 680 |
+
security_scan_timeout=args.security_scan_timeout,
|
| 681 |
)
|
| 682 |
if result.get("skipped"):
|
| 683 |
skipped += 1
|
|
|
|
| 696 |
if not result["is_new_page"]
|
| 697 |
else "converted" if result["converted"] else "installed"
|
| 698 |
)
|
| 699 |
+
scan = result.get("security_scan")
|
| 700 |
+
scan_suffix = (
|
| 701 |
+
f"; SkillSpector: {scan.get('status')}"
|
| 702 |
+
if isinstance(scan, dict)
|
| 703 |
+
else ""
|
| 704 |
+
)
|
| 705 |
+
print(f" [{i}/{total}] [{status}] {name}{scan_suffix}")
|
| 706 |
except Exception as exc:
|
| 707 |
errors += 1
|
| 708 |
print(f" [{i}/{total}] ERROR: {name}: {exc}", file=sys.stderr)
|
|
|
|
| 711 |
f"\nDone: {added} added, {updated} updated, {converted} converted, "
|
| 712 |
f"{skipped} skipped, {errors} errors"
|
| 713 |
)
|
| 714 |
+
if errors:
|
| 715 |
+
sys.exit(1)
|
| 716 |
|
| 717 |
|
| 718 |
if __name__ == "__main__":
|
src/skill_telemetry.py
CHANGED
|
@@ -36,11 +36,15 @@ from datetime import datetime, timezone
|
|
| 36 |
from pathlib import Path
|
| 37 |
from typing import Any, Iterator, Mapping
|
| 38 |
|
|
|
|
| 39 |
from ctx.utils._file_lock import file_lock
|
|
|
|
| 40 |
|
| 41 |
_logger = logging.getLogger(__name__)
|
| 42 |
|
|
|
|
| 43 |
EVENT_TYPES = frozenset({"load", "unload", "override", "switch_away"})
|
|
|
|
| 44 |
|
| 45 |
# Same policy as wiki_utils.SAFE_NAME_RE: alnum start, alnum / _ / - / .
|
| 46 |
# inside, bounded length. Dots are allowed intentionally for names like
|
|
@@ -56,6 +60,8 @@ _ALLOWED_EVENTS_DIR = DEFAULT_EVENTS_PATH.parent.resolve()
|
|
| 56 |
_TRUSTED_ROOT = DEFAULT_EVENTS_PATH.parent.resolve()
|
| 57 |
DEFAULT_SESSION_FRACTION = 0.20
|
| 58 |
DEFAULT_MIN_RETENTION_MIN = 20.0
|
|
|
|
|
|
|
| 59 |
|
| 60 |
# Bounds on caller-supplied meta dicts. Keeps the log line small and
|
| 61 |
# prevents inadvertent leakage of large mappings like ``os.environ``
|
|
@@ -64,6 +70,26 @@ DEFAULT_MIN_RETENTION_MIN = 20.0
|
|
| 64 |
_MAX_META_KEYS = 20
|
| 65 |
_MAX_META_VALUE_LEN = 512
|
| 66 |
_META_SCALAR_TYPES: tuple[type, ...] = (str, int, float, bool, type(None))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
|
| 69 |
@dataclass(frozen=True)
|
|
@@ -76,8 +102,14 @@ class TelemetryEvent:
|
|
| 76 |
session_id: str
|
| 77 |
event_id: str
|
| 78 |
meta: Mapping[str, Any] = field(default_factory=dict)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
def __post_init__(self) -> None:
|
|
|
|
|
|
|
| 81 |
if self.event not in EVENT_TYPES:
|
| 82 |
raise ValueError(
|
| 83 |
f"invalid event type {self.event!r}; expected one of {sorted(EVENT_TYPES)}"
|
|
@@ -88,6 +120,12 @@ class TelemetryEvent:
|
|
| 88 |
raise ValueError("session_id must be a non-empty string")
|
| 89 |
if not isinstance(self.event_id, str) or not self.event_id:
|
| 90 |
raise ValueError("event_id must be a non-empty string")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
# timestamp must parse as ISO-8601 so downstream readers don't choke
|
| 92 |
try:
|
| 93 |
datetime.fromisoformat(self.timestamp)
|
|
@@ -130,6 +168,51 @@ def _validate_meta(meta: Mapping[str, Any]) -> None:
|
|
| 130 |
)
|
| 131 |
|
| 132 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
def _resolve_events_path(
|
| 134 |
path: Path | None,
|
| 135 |
*,
|
|
@@ -171,6 +254,7 @@ def log_event(
|
|
| 171 |
session_id: str,
|
| 172 |
*,
|
| 173 |
meta: Mapping[str, Any] | None = None,
|
|
|
|
| 174 |
path: Path | None = None,
|
| 175 |
trusted_root: Path = _TRUSTED_ROOT,
|
| 176 |
) -> TelemetryEvent:
|
|
@@ -183,10 +267,11 @@ def log_event(
|
|
| 183 |
write to ``tmp_path`` should pass ``trusted_root=tmp_path``.
|
| 184 |
"""
|
| 185 |
target = _resolve_events_path(path, trusted_root=trusted_root)
|
| 186 |
-
|
| 187 |
|
| 188 |
-
safe_meta
|
| 189 |
_validate_meta(safe_meta)
|
|
|
|
| 190 |
|
| 191 |
record = TelemetryEvent(
|
| 192 |
event=event,
|
|
@@ -195,6 +280,9 @@ def log_event(
|
|
| 195 |
session_id=session_id,
|
| 196 |
event_id=_new_event_id(),
|
| 197 |
meta=safe_meta,
|
|
|
|
|
|
|
|
|
|
| 198 |
)
|
| 199 |
line = json.dumps(asdict(record), ensure_ascii=False, sort_keys=True) + "\n"
|
| 200 |
|
|
@@ -240,6 +328,12 @@ def read_events(
|
|
| 240 |
session_id=obj["session_id"],
|
| 241 |
event_id=obj["event_id"],
|
| 242 |
meta=obj.get("meta", {}),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
)
|
| 244 |
except (json.JSONDecodeError, KeyError, ValueError, TypeError) as exc:
|
| 245 |
msg = (
|
|
|
|
| 36 |
from pathlib import Path
|
| 37 |
from typing import Any, Iterator, Mapping
|
| 38 |
|
| 39 |
+
from ctx.telemetry import hash_identifier
|
| 40 |
from ctx.utils._file_lock import file_lock
|
| 41 |
+
from ctx.utils._secret_scan import redact_secret_text, secret_key_like
|
| 42 |
|
| 43 |
_logger = logging.getLogger(__name__)
|
| 44 |
|
| 45 |
+
SCHEMA_VERSION = "ctx.skill_telemetry.v1"
|
| 46 |
EVENT_TYPES = frozenset({"load", "unload", "override", "switch_away"})
|
| 47 |
+
ENTITY_TYPES = frozenset({"skill", "agent", "mcp-server"})
|
| 48 |
|
| 49 |
# Same policy as wiki_utils.SAFE_NAME_RE: alnum start, alnum / _ / - / .
|
| 50 |
# inside, bounded length. Dots are allowed intentionally for names like
|
|
|
|
| 60 |
_TRUSTED_ROOT = DEFAULT_EVENTS_PATH.parent.resolve()
|
| 61 |
DEFAULT_SESSION_FRACTION = 0.20
|
| 62 |
DEFAULT_MIN_RETENTION_MIN = 20.0
|
| 63 |
+
_PRIVATE_DIR_MODE = 0o700
|
| 64 |
+
_PRIVATE_FILE_MODE = 0o600
|
| 65 |
|
| 66 |
# Bounds on caller-supplied meta dicts. Keeps the log line small and
|
| 67 |
# prevents inadvertent leakage of large mappings like ``os.environ``
|
|
|
|
| 70 |
_MAX_META_KEYS = 20
|
| 71 |
_MAX_META_VALUE_LEN = 512
|
| 72 |
_META_SCALAR_TYPES: tuple[type, ...] = (str, int, float, bool, type(None))
|
| 73 |
+
_HASHED_META_KEYS = frozenset({
|
| 74 |
+
"command",
|
| 75 |
+
"cwd",
|
| 76 |
+
"goal",
|
| 77 |
+
"input",
|
| 78 |
+
"output",
|
| 79 |
+
"path",
|
| 80 |
+
"prompt",
|
| 81 |
+
"query",
|
| 82 |
+
"raw_input",
|
| 83 |
+
"raw_prompt",
|
| 84 |
+
"repo",
|
| 85 |
+
"response",
|
| 86 |
+
"stderr",
|
| 87 |
+
"stdout",
|
| 88 |
+
"task",
|
| 89 |
+
"tool_args",
|
| 90 |
+
"tool_input",
|
| 91 |
+
"tool_output",
|
| 92 |
+
})
|
| 93 |
|
| 94 |
|
| 95 |
@dataclass(frozen=True)
|
|
|
|
| 102 |
session_id: str
|
| 103 |
event_id: str
|
| 104 |
meta: Mapping[str, Any] = field(default_factory=dict)
|
| 105 |
+
skill_hash: str | None = None
|
| 106 |
+
session_hash: str | None = None
|
| 107 |
+
entity_type: str | None = None
|
| 108 |
+
schema_version: str = SCHEMA_VERSION
|
| 109 |
|
| 110 |
def __post_init__(self) -> None:
|
| 111 |
+
if self.schema_version != SCHEMA_VERSION:
|
| 112 |
+
raise ValueError(f"unsupported telemetry schema: {self.schema_version!r}")
|
| 113 |
if self.event not in EVENT_TYPES:
|
| 114 |
raise ValueError(
|
| 115 |
f"invalid event type {self.event!r}; expected one of {sorted(EVENT_TYPES)}"
|
|
|
|
| 120 |
raise ValueError("session_id must be a non-empty string")
|
| 121 |
if not isinstance(self.event_id, str) or not self.event_id:
|
| 122 |
raise ValueError("event_id must be a non-empty string")
|
| 123 |
+
if self.skill_hash is not None and not str(self.skill_hash).startswith("sha256:"):
|
| 124 |
+
raise ValueError("skill_hash must be a sha256 identifier")
|
| 125 |
+
if self.session_hash is not None and not str(self.session_hash).startswith("sha256:"):
|
| 126 |
+
raise ValueError("session_hash must be a sha256 identifier")
|
| 127 |
+
if self.entity_type is not None and self.entity_type not in ENTITY_TYPES:
|
| 128 |
+
raise ValueError(f"entity_type must be one of: {sorted(ENTITY_TYPES)}")
|
| 129 |
# timestamp must parse as ISO-8601 so downstream readers don't choke
|
| 130 |
try:
|
| 131 |
datetime.fromisoformat(self.timestamp)
|
|
|
|
| 168 |
)
|
| 169 |
|
| 170 |
|
| 171 |
+
def _sanitize_meta(meta: Mapping[str, Any]) -> dict[str, Any]:
|
| 172 |
+
"""Return bounded metadata without raw secrets, prompts, paths, or command text."""
|
| 173 |
+
|
| 174 |
+
safe: dict[str, Any] = {}
|
| 175 |
+
for key, value in meta.items():
|
| 176 |
+
if not isinstance(value, str):
|
| 177 |
+
safe[key] = value
|
| 178 |
+
continue
|
| 179 |
+
normalized_key = key.lower()
|
| 180 |
+
if secret_key_like(key):
|
| 181 |
+
safe[key] = "[redacted]"
|
| 182 |
+
continue
|
| 183 |
+
if normalized_key in _HASHED_META_KEYS:
|
| 184 |
+
safe[f"{key}_hash"] = hash_identifier(value)
|
| 185 |
+
continue
|
| 186 |
+
redacted = redact_secret_text(value)
|
| 187 |
+
if redacted != value:
|
| 188 |
+
safe[key] = redacted
|
| 189 |
+
continue
|
| 190 |
+
safe[key] = value
|
| 191 |
+
return safe
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def ensure_private_events_file(path: Path) -> None:
|
| 195 |
+
"""Create or tighten the legacy local event file to owner read/write only."""
|
| 196 |
+
|
| 197 |
+
path.parent.mkdir(parents=True, exist_ok=True, mode=_PRIVATE_DIR_MODE)
|
| 198 |
+
try:
|
| 199 |
+
os.chmod(path.parent, _PRIVATE_DIR_MODE)
|
| 200 |
+
except OSError:
|
| 201 |
+
pass
|
| 202 |
+
if path.exists():
|
| 203 |
+
try:
|
| 204 |
+
os.chmod(path, _PRIVATE_FILE_MODE)
|
| 205 |
+
except OSError:
|
| 206 |
+
pass
|
| 207 |
+
return
|
| 208 |
+
fd = os.open(path, os.O_APPEND | os.O_CREAT | os.O_WRONLY, _PRIVATE_FILE_MODE)
|
| 209 |
+
os.close(fd)
|
| 210 |
+
try:
|
| 211 |
+
os.chmod(path, _PRIVATE_FILE_MODE)
|
| 212 |
+
except OSError:
|
| 213 |
+
pass
|
| 214 |
+
|
| 215 |
+
|
| 216 |
def _resolve_events_path(
|
| 217 |
path: Path | None,
|
| 218 |
*,
|
|
|
|
| 254 |
session_id: str,
|
| 255 |
*,
|
| 256 |
meta: Mapping[str, Any] | None = None,
|
| 257 |
+
entity_type: str | None = None,
|
| 258 |
path: Path | None = None,
|
| 259 |
trusted_root: Path = _TRUSTED_ROOT,
|
| 260 |
) -> TelemetryEvent:
|
|
|
|
| 267 |
write to ``tmp_path`` should pass ``trusted_root=tmp_path``.
|
| 268 |
"""
|
| 269 |
target = _resolve_events_path(path, trusted_root=trusted_root)
|
| 270 |
+
ensure_private_events_file(target)
|
| 271 |
|
| 272 |
+
safe_meta = _sanitize_meta(dict(meta or {}))
|
| 273 |
_validate_meta(safe_meta)
|
| 274 |
+
resolved_entity_type = entity_type or "skill"
|
| 275 |
|
| 276 |
record = TelemetryEvent(
|
| 277 |
event=event,
|
|
|
|
| 280 |
session_id=session_id,
|
| 281 |
event_id=_new_event_id(),
|
| 282 |
meta=safe_meta,
|
| 283 |
+
skill_hash=hash_identifier(skill),
|
| 284 |
+
session_hash=hash_identifier(session_id),
|
| 285 |
+
entity_type=resolved_entity_type,
|
| 286 |
)
|
| 287 |
line = json.dumps(asdict(record), ensure_ascii=False, sort_keys=True) + "\n"
|
| 288 |
|
|
|
|
| 328 |
session_id=obj["session_id"],
|
| 329 |
event_id=obj["event_id"],
|
| 330 |
meta=obj.get("meta", {}),
|
| 331 |
+
skill_hash=obj.get("skill_hash") or hash_identifier(str(obj["skill"])),
|
| 332 |
+
session_hash=obj.get("session_hash") or hash_identifier(
|
| 333 |
+
str(obj["session_id"])
|
| 334 |
+
),
|
| 335 |
+
entity_type=obj.get("entity_type"),
|
| 336 |
+
schema_version=obj.get("schema_version", SCHEMA_VERSION),
|
| 337 |
)
|
| 338 |
except (json.JSONDecodeError, KeyError, ValueError, TypeError) as exc:
|
| 339 |
msg = (
|
src/tests/conftest.py
CHANGED
|
@@ -65,6 +65,35 @@ def project_root() -> Path:
|
|
| 65 |
return _PROJECT_ROOT
|
| 66 |
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
@pytest.fixture()
|
| 69 |
def tmp_wiki(tmp_path: Path) -> Path:
|
| 70 |
"""
|
|
|
|
| 65 |
return _PROJECT_ROOT
|
| 66 |
|
| 67 |
|
| 68 |
+
@pytest.fixture(autouse=True)
|
| 69 |
+
def disable_enterprise_telemetry_side_effects(
|
| 70 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 71 |
+
) -> None:
|
| 72 |
+
"""Keep telemetry-enabled product code from writing to real user paths in tests."""
|
| 73 |
+
|
| 74 |
+
def _noop_record_event(*args: object, **kwargs: object) -> None:
|
| 75 |
+
return None
|
| 76 |
+
|
| 77 |
+
import ctx.telemetry as telemetry # noqa: PLC0415
|
| 78 |
+
|
| 79 |
+
monkeypatch.setattr(telemetry, "record_event", _noop_record_event)
|
| 80 |
+
for module_name in (
|
| 81 |
+
"ctx.adapters.generic.ctx_core_tools",
|
| 82 |
+
"ctx.adapters.generic.runtime_lifecycle",
|
| 83 |
+
"ctx.api",
|
| 84 |
+
"ctx.cli.run",
|
| 85 |
+
"ctx.mcp_server.server",
|
| 86 |
+
):
|
| 87 |
+
module = sys.modules.get(module_name)
|
| 88 |
+
if module is not None:
|
| 89 |
+
monkeypatch.setattr(
|
| 90 |
+
module,
|
| 91 |
+
"record_event",
|
| 92 |
+
_noop_record_event,
|
| 93 |
+
raising=False,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
@pytest.fixture()
|
| 98 |
def tmp_wiki(tmp_path: Path) -> Path:
|
| 99 |
"""
|
src/tests/test_agent_add.py
CHANGED
|
@@ -14,6 +14,7 @@ if str(SRC_DIR) not in sys.path:
|
|
| 14 |
sys.path.insert(0, str(SRC_DIR))
|
| 15 |
|
| 16 |
import agent_add # noqa: E402
|
|
|
|
| 17 |
|
| 18 |
|
| 19 |
class _Decision:
|
|
@@ -205,6 +206,25 @@ def test_new_agent_add_writes_converted_agent_mirror(
|
|
| 205 |
assert mirror.read_text(encoding="utf-8") == source_text
|
| 206 |
|
| 207 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
def test_existing_agent_update_refreshes_converted_agent_mirror(
|
| 209 |
tmp_path: Path,
|
| 210 |
monkeypatch: Any,
|
|
@@ -212,11 +232,20 @@ def test_existing_agent_update_refreshes_converted_agent_mirror(
|
|
| 212 |
wiki, agents_dir, source = _setup_paths(tmp_path)
|
| 213 |
installed = agents_dir / "reviewer-agent.md"
|
| 214 |
installed.write_text(_agent_text(), encoding="utf-8")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
mirror = wiki / "converted-agents" / "reviewer-agent.md"
|
| 216 |
mirror.parent.mkdir(parents=True)
|
| 217 |
mirror.write_text("old mirror\n", encoding="utf-8")
|
| 218 |
-
entity = wiki / "entities" / "agents" / "reviewer-agent.md"
|
| 219 |
-
entity.write_text("# existing entity\n", encoding="utf-8")
|
| 220 |
updated_text = _agent_text(description="Updated mirrored agent.")
|
| 221 |
source.write_text(updated_text, encoding="utf-8")
|
| 222 |
_patch_side_effects(monkeypatch)
|
|
@@ -232,6 +261,10 @@ def test_existing_agent_update_refreshes_converted_agent_mirror(
|
|
| 232 |
|
| 233 |
assert result["is_new_page"] is False
|
| 234 |
assert mirror.read_text(encoding="utf-8") == updated_text
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
|
| 236 |
|
| 237 |
def test_main_existing_agent_prints_update_review(
|
|
|
|
| 14 |
sys.path.insert(0, str(SRC_DIR))
|
| 15 |
|
| 16 |
import agent_add # noqa: E402
|
| 17 |
+
from ctx.core.wiki.wiki_packs import load_merged_wiki_pages, write_wiki_base_pack # noqa: E402
|
| 18 |
|
| 19 |
|
| 20 |
class _Decision:
|
|
|
|
| 206 |
assert mirror.read_text(encoding="utf-8") == source_text
|
| 207 |
|
| 208 |
|
| 209 |
+
def test_bom_prefixed_agent_frontmatter_is_accepted(
|
| 210 |
+
tmp_path: Path,
|
| 211 |
+
monkeypatch: Any,
|
| 212 |
+
) -> None:
|
| 213 |
+
wiki, agents_dir, source = _setup_paths(tmp_path)
|
| 214 |
+
source.write_text("\ufeff" + _agent_text(), encoding="utf-8")
|
| 215 |
+
_patch_side_effects(monkeypatch)
|
| 216 |
+
|
| 217 |
+
result = agent_add.add_agent(
|
| 218 |
+
source_path=source,
|
| 219 |
+
name="reviewer-agent",
|
| 220 |
+
wiki_path=wiki,
|
| 221 |
+
agents_dir=agents_dir,
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
assert result["is_new_page"] is True
|
| 225 |
+
assert (wiki / "entities" / "agents" / "reviewer-agent.md").exists()
|
| 226 |
+
|
| 227 |
+
|
| 228 |
def test_existing_agent_update_refreshes_converted_agent_mirror(
|
| 229 |
tmp_path: Path,
|
| 230 |
monkeypatch: Any,
|
|
|
|
| 232 |
wiki, agents_dir, source = _setup_paths(tmp_path)
|
| 233 |
installed = agents_dir / "reviewer-agent.md"
|
| 234 |
installed.write_text(_agent_text(), encoding="utf-8")
|
| 235 |
+
packs_dir = wiki / "wiki-packs"
|
| 236 |
+
write_wiki_base_pack(
|
| 237 |
+
pack_dir=packs_dir / "base-export-1",
|
| 238 |
+
pack_id="base-export-1",
|
| 239 |
+
base_export_id="wiki-export-1",
|
| 240 |
+
pages={
|
| 241 |
+
"entities/agents/reviewer-agent.md": (
|
| 242 |
+
"# reviewer-agent\n\nExisting packed agent page.\n"
|
| 243 |
+
)
|
| 244 |
+
},
|
| 245 |
+
)
|
| 246 |
mirror = wiki / "converted-agents" / "reviewer-agent.md"
|
| 247 |
mirror.parent.mkdir(parents=True)
|
| 248 |
mirror.write_text("old mirror\n", encoding="utf-8")
|
|
|
|
|
|
|
| 249 |
updated_text = _agent_text(description="Updated mirrored agent.")
|
| 250 |
source.write_text(updated_text, encoding="utf-8")
|
| 251 |
_patch_side_effects(monkeypatch)
|
|
|
|
| 261 |
|
| 262 |
assert result["is_new_page"] is False
|
| 263 |
assert mirror.read_text(encoding="utf-8") == updated_text
|
| 264 |
+
entity = wiki / "entities" / "agents" / "reviewer-agent.md"
|
| 265 |
+
merged = load_merged_wiki_pages(packs_dir)
|
| 266 |
+
assert not entity.exists()
|
| 267 |
+
assert "Updated mirrored agent." in merged["entities/agents/reviewer-agent.md"]
|
| 268 |
|
| 269 |
|
| 270 |
def test_main_existing_agent_prints_update_review(
|
src/tests/test_catalog_builder.py
CHANGED
|
@@ -17,6 +17,7 @@ from unittest.mock import MagicMock
|
|
| 17 |
import pytest
|
| 18 |
|
| 19 |
import catalog_builder
|
|
|
|
| 20 |
|
| 21 |
|
| 22 |
# ── Helpers ───────────────────────────────────────────────────────────────────
|
|
@@ -520,6 +521,39 @@ class TestBuildCatalog:
|
|
| 520 |
for i in range(3):
|
| 521 |
assert f"agent-{i}" in content
|
| 522 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 523 |
|
| 524 |
# ── update_wiki_index ─────────────────────────────────────────────────────────
|
| 525 |
|
|
|
|
| 17 |
import pytest
|
| 18 |
|
| 19 |
import catalog_builder
|
| 20 |
+
from ctx.core.wiki.wiki_packs import load_merged_wiki_pages, write_wiki_base_pack
|
| 21 |
|
| 22 |
|
| 23 |
# ── Helpers ───────────────────────────────────────────────────────────────────
|
|
|
|
| 521 |
for i in range(3):
|
| 522 |
assert f"agent-{i}" in content
|
| 523 |
|
| 524 |
+
def test_pack_only_wiki_writes_catalog_overlay(
|
| 525 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 526 |
+
) -> None:
|
| 527 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 528 |
+
wiki_dir = tmp_path / "wiki"
|
| 529 |
+
write_wiki_base_pack(
|
| 530 |
+
pack_dir=wiki_dir / "wiki-packs" / "base-export-1",
|
| 531 |
+
pack_id="base-export-1",
|
| 532 |
+
base_export_id="wiki-export-1",
|
| 533 |
+
pages={
|
| 534 |
+
"index.md": "# Index\n\nTotal pages: 0\n\n## Skills\n",
|
| 535 |
+
"log.md": "# Log\n",
|
| 536 |
+
},
|
| 537 |
+
)
|
| 538 |
+
skills_dir = tmp_path / "skills"
|
| 539 |
+
agents_dir = tmp_path / "agents"
|
| 540 |
+
_make_skill(skills_dir, "pack-skill", 12)
|
| 541 |
+
_make_agent(agents_dir, "pack-agent", 5)
|
| 542 |
+
|
| 543 |
+
stats = catalog_builder.build_catalog(wiki_dir, skills_dir, agents_dir, [])
|
| 544 |
+
catalog_builder.update_wiki_index(wiki_dir, stats)
|
| 545 |
+
catalog_builder.append_log(wiki_dir, stats)
|
| 546 |
+
|
| 547 |
+
assert not (wiki_dir / "catalog.md").exists()
|
| 548 |
+
assert not (wiki_dir / "index.md").exists()
|
| 549 |
+
assert not (wiki_dir / "log.md").exists()
|
| 550 |
+
merged = load_merged_wiki_pages(wiki_dir / "wiki-packs")
|
| 551 |
+
assert "pack-skill" in merged["catalog.md"]
|
| 552 |
+
assert "pack-agent" in merged["catalog.md"]
|
| 553 |
+
assert "[[catalog]]" in merged["index.md"]
|
| 554 |
+
assert "Total pages: 2" in merged["index.md"]
|
| 555 |
+
assert "catalog-build" in merged["log.md"]
|
| 556 |
+
|
| 557 |
|
| 558 |
# ── update_wiki_index ─────────────────────────────────────────────────────────
|
| 559 |
|
src/tests/test_ci_classifier.py
CHANGED
|
@@ -37,6 +37,7 @@ def test_docs_only_classification() -> None:
|
|
| 37 |
"package_changed": False,
|
| 38 |
"similarity_changed": False,
|
| 39 |
"source_changed": False,
|
|
|
|
| 40 |
}
|
| 41 |
|
| 42 |
|
|
@@ -147,6 +148,7 @@ def test_workflow_change_fails_open_for_future_gates() -> None:
|
|
| 147 |
assert flags["package_changed"] is True
|
| 148 |
assert flags["similarity_changed"] is True
|
| 149 |
assert flags["source_changed"] is True
|
|
|
|
| 150 |
assert flags["docs_changed"] is False
|
| 151 |
assert flags["docs_only"] is False
|
| 152 |
|
|
@@ -186,6 +188,19 @@ def test_graph_artifact_job_uses_release_asset_fallback_for_lfs_budget() -> None
|
|
| 186 |
assert "validating pointer metadata only" not in workflow
|
| 187 |
|
| 188 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
def test_publish_oidc_permission_is_limited_to_publish_job() -> None:
|
| 190 |
workflow = Path(".github/workflows/publish.yml").read_text(encoding="utf-8")
|
| 191 |
header = workflow.split("\njobs:\n", maxsplit=1)[0]
|
|
@@ -203,6 +218,21 @@ def test_publish_workflow_rejects_existing_pypi_versions() -> None:
|
|
| 203 |
assert "already exists on PyPI" in workflow
|
| 204 |
|
| 205 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
def test_publish_workflow_validates_and_uploads_graph_assets() -> None:
|
| 207 |
workflow = Path(".github/workflows/publish.yml").read_text(encoding="utf-8")
|
| 208 |
|
|
@@ -225,6 +255,20 @@ def test_publish_workflow_validates_and_uploads_graph_assets() -> None:
|
|
| 225 |
assert "graph_assets_available" in workflow
|
| 226 |
|
| 227 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
def test_changelog_defines_current_release_link() -> None:
|
| 229 |
pyproject = Path("pyproject.toml").read_text(encoding="utf-8")
|
| 230 |
version_match = re.search(r'^version = "([^"]+)"', pyproject, re.MULTILINE)
|
|
@@ -404,6 +448,19 @@ def test_similarity_paths_are_classified() -> None:
|
|
| 404 |
assert flags["source_changed"] is True
|
| 405 |
|
| 406 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 407 |
def test_embedding_backend_change_runs_similarity_gate() -> None:
|
| 408 |
flags = classify_paths(["src/embedding_backend.py"])
|
| 409 |
|
|
@@ -422,6 +479,7 @@ def test_main_writes_github_outputs(tmp_path: Path, monkeypatch) -> None:
|
|
| 422 |
written = output.read_text(encoding="utf-8").splitlines()
|
| 423 |
assert "package_changed=true" in written
|
| 424 |
assert "source_changed=true" in written
|
|
|
|
| 425 |
assert "docs_changed=false" in written
|
| 426 |
assert "docs_only=false" in written
|
| 427 |
|
|
@@ -671,6 +729,29 @@ def test_ci_required_rejects_browser_skip_when_classifier_requests_it() -> None:
|
|
| 671 |
}
|
| 672 |
|
| 673 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 674 |
def test_ci_required_rejects_missing_docs_check_on_mixed_docs_pr() -> None:
|
| 675 |
needs = _required_needs(
|
| 676 |
classify={
|
|
@@ -697,3 +778,14 @@ def test_ci_required_rejects_missing_graph_check_on_mixed_artifact_pr() -> None:
|
|
| 697 |
assert failed_required_jobs(needs, event_name="pull_request") == {
|
| 698 |
"graph-check": "skipped",
|
| 699 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
"package_changed": False,
|
| 38 |
"similarity_changed": False,
|
| 39 |
"source_changed": False,
|
| 40 |
+
"telemetry_changed": False,
|
| 41 |
}
|
| 42 |
|
| 43 |
|
|
|
|
| 148 |
assert flags["package_changed"] is True
|
| 149 |
assert flags["similarity_changed"] is True
|
| 150 |
assert flags["source_changed"] is True
|
| 151 |
+
assert flags["telemetry_changed"] is True
|
| 152 |
assert flags["docs_changed"] is False
|
| 153 |
assert flags["docs_only"] is False
|
| 154 |
|
|
|
|
| 188 |
assert "validating pointer metadata only" not in workflow
|
| 189 |
|
| 190 |
|
| 191 |
+
def test_similarity_gate_caches_and_predownloads_real_model() -> None:
|
| 192 |
+
workflow = Path(".github/workflows/test.yml").read_text(encoding="utf-8")
|
| 193 |
+
|
| 194 |
+
assert "actions/cache@v4" not in workflow
|
| 195 |
+
assert "actions/cache@v5" in workflow
|
| 196 |
+
assert "Cache MiniLM model" in workflow
|
| 197 |
+
assert "hf-sentence-transformers-all-MiniLM-L6-v2-v1" in workflow
|
| 198 |
+
assert "Pre-download MiniLM model" in workflow
|
| 199 |
+
assert "sentence-transformers/all-MiniLM-L6-v2" in workflow
|
| 200 |
+
assert "CTX_REQUIRE_SIMILARITY_EVAL" in workflow
|
| 201 |
+
assert "src/tests/test_similarity_precision_recall.py" in workflow
|
| 202 |
+
|
| 203 |
+
|
| 204 |
def test_publish_oidc_permission_is_limited_to_publish_job() -> None:
|
| 205 |
workflow = Path(".github/workflows/publish.yml").read_text(encoding="utf-8")
|
| 206 |
header = workflow.split("\njobs:\n", maxsplit=1)[0]
|
|
|
|
| 218 |
assert "already exists on PyPI" in workflow
|
| 219 |
|
| 220 |
|
| 221 |
+
def test_publish_static_gate_uses_canonical_python_target() -> None:
|
| 222 |
+
workflow = Path(".github/workflows/publish.yml").read_text(encoding="utf-8")
|
| 223 |
+
setup_match = re.search(
|
| 224 |
+
r"- name: Set up Python\n"
|
| 225 |
+
r"\s+uses: actions/setup-python@v6\n"
|
| 226 |
+
r"\s+with:\n"
|
| 227 |
+
r'\s+python-version: "([^"]+)"',
|
| 228 |
+
workflow,
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
assert setup_match is not None
|
| 232 |
+
assert setup_match.group(1) == "3.11"
|
| 233 |
+
assert "python -m mypy src" in workflow
|
| 234 |
+
|
| 235 |
+
|
| 236 |
def test_publish_workflow_validates_and_uploads_graph_assets() -> None:
|
| 237 |
workflow = Path(".github/workflows/publish.yml").read_text(encoding="utf-8")
|
| 238 |
|
|
|
|
| 255 |
assert "graph_assets_available" in workflow
|
| 256 |
|
| 257 |
|
| 258 |
+
def test_publish_workflow_runs_installed_wheel_telemetry_smoke() -> None:
|
| 259 |
+
workflow = Path(".github/workflows/publish.yml").read_text(encoding="utf-8")
|
| 260 |
+
|
| 261 |
+
assert "Telemetry release smoke" in workflow
|
| 262 |
+
assert "record_event(" in workflow
|
| 263 |
+
assert "record_counter(" in workflow
|
| 264 |
+
assert "ctx-telemetry-export --dry-run --json" in workflow
|
| 265 |
+
assert "ctx-telemetry-export \\" in workflow
|
| 266 |
+
assert "--signal metrics" in workflow
|
| 267 |
+
assert "ctx-telemetry-retention plan --signal all --json" in workflow
|
| 268 |
+
assert "raw-release-telemetry-sentinel" in workflow
|
| 269 |
+
assert "raw telemetry sentinel leaked into exported telemetry" in workflow
|
| 270 |
+
|
| 271 |
+
|
| 272 |
def test_changelog_defines_current_release_link() -> None:
|
| 273 |
pyproject = Path("pyproject.toml").read_text(encoding="utf-8")
|
| 274 |
version_match = re.search(r'^version = "([^"]+)"', pyproject, re.MULTILINE)
|
|
|
|
| 448 |
assert flags["source_changed"] is True
|
| 449 |
|
| 450 |
|
| 451 |
+
def test_telemetry_paths_are_classified() -> None:
|
| 452 |
+
for path in (
|
| 453 |
+
"docs/telemetry.md",
|
| 454 |
+
"src/config.json",
|
| 455 |
+
"src/ctx/telemetry/__init__.py",
|
| 456 |
+
"src/ctx/adapters/generic/runtime_lifecycle.py",
|
| 457 |
+
"src/tests/test_enterprise_telemetry.py",
|
| 458 |
+
):
|
| 459 |
+
flags = classify_paths([path])
|
| 460 |
+
|
| 461 |
+
assert flags["telemetry_changed"] is True
|
| 462 |
+
|
| 463 |
+
|
| 464 |
def test_embedding_backend_change_runs_similarity_gate() -> None:
|
| 465 |
flags = classify_paths(["src/embedding_backend.py"])
|
| 466 |
|
|
|
|
| 479 |
written = output.read_text(encoding="utf-8").splitlines()
|
| 480 |
assert "package_changed=true" in written
|
| 481 |
assert "source_changed=true" in written
|
| 482 |
+
assert "telemetry_changed=false" in written
|
| 483 |
assert "docs_changed=false" in written
|
| 484 |
assert "docs_only=false" in written
|
| 485 |
|
|
|
|
| 729 |
}
|
| 730 |
|
| 731 |
|
| 732 |
+
def test_ci_required_rejects_telemetry_skip_when_classifier_requests_it() -> None:
|
| 733 |
+
needs = _required_needs(
|
| 734 |
+
classify={"result": "success", "outputs": {"telemetry_changed": "true"}},
|
| 735 |
+
**{"telemetry-enterprise": {"result": "skipped"}},
|
| 736 |
+
)
|
| 737 |
+
|
| 738 |
+
assert failed_required_jobs(needs, event_name="pull_request") == {
|
| 739 |
+
"telemetry-enterprise": "skipped",
|
| 740 |
+
}
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def test_ci_required_allows_telemetry_skip_for_unrelated_pr_only() -> None:
|
| 744 |
+
needs = _required_needs(
|
| 745 |
+
classify={"result": "success", "outputs": {"telemetry_changed": "false"}},
|
| 746 |
+
**{"telemetry-enterprise": {"result": "skipped"}},
|
| 747 |
+
)
|
| 748 |
+
|
| 749 |
+
assert failed_required_jobs(needs, event_name="pull_request") == {}
|
| 750 |
+
assert failed_required_jobs(needs, event_name="push") == {
|
| 751 |
+
"telemetry-enterprise": "skipped",
|
| 752 |
+
}
|
| 753 |
+
|
| 754 |
+
|
| 755 |
def test_ci_required_rejects_missing_docs_check_on_mixed_docs_pr() -> None:
|
| 756 |
needs = _required_needs(
|
| 757 |
classify={
|
|
|
|
| 778 |
assert failed_required_jobs(needs, event_name="pull_request") == {
|
| 779 |
"graph-check": "skipped",
|
| 780 |
}
|
| 781 |
+
|
| 782 |
+
|
| 783 |
+
def test_workflow_runs_focused_telemetry_enterprise_gate() -> None:
|
| 784 |
+
workflow = Path(".github/workflows/test.yml").read_text(encoding="utf-8")
|
| 785 |
+
|
| 786 |
+
assert "telemetry_changed: ${{ steps.classify.outputs.telemetry_changed }}" in workflow
|
| 787 |
+
assert "telemetry-enterprise:" in workflow
|
| 788 |
+
assert "needs.classify.outputs.telemetry_changed == 'true'" in workflow
|
| 789 |
+
assert "src/tests/test_enterprise_telemetry.py" in workflow
|
| 790 |
+
assert "src/tests/test_harness_cli_run.py" in workflow
|
| 791 |
+
assert '-k "telemetry or runtime_lifecycle"' in workflow
|
src/tests/test_clean_host_contract.py
CHANGED
|
@@ -167,6 +167,7 @@ def test_isolated_env_does_not_inherit_caller_secrets(
|
|
| 167 |
assert "GITHUB_TOKEN" not in env
|
| 168 |
assert "CTX_WIKI_DIR" not in env
|
| 169 |
assert "CLAUDE_HOME" not in env
|
|
|
|
| 170 |
|
| 171 |
|
| 172 |
def test_assert_inside_rejects_escape(tmp_path: Path) -> None:
|
|
|
|
| 167 |
assert "GITHUB_TOKEN" not in env
|
| 168 |
assert "CTX_WIKI_DIR" not in env
|
| 169 |
assert "CLAUDE_HOME" not in env
|
| 170 |
+
assert env["CTX_ALLOW_MISSING_GRAPH"] == "1"
|
| 171 |
|
| 172 |
|
| 173 |
def test_assert_inside_rejects_escape(tmp_path: Path) -> None:
|
src/tests/test_context_monitor.py
CHANGED
|
@@ -18,6 +18,7 @@ import sys
|
|
| 18 |
from datetime import datetime, timezone
|
| 19 |
from pathlib import Path
|
| 20 |
|
|
|
|
| 21 |
import pytest
|
| 22 |
|
| 23 |
sys.path.insert(0, str(Path(__file__).parents[1]))
|
|
@@ -32,6 +33,7 @@ from ctx.adapters.claude_code.hooks.context_monitor import (
|
|
| 32 |
load_recent_unmatched_count,
|
| 33 |
write_pending_skills,
|
| 34 |
)
|
|
|
|
| 35 |
|
| 36 |
TODAY = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
| 37 |
|
|
@@ -245,6 +247,41 @@ class TestWritePendingSkills:
|
|
| 245 |
assert _cm.graph_suggest(["fastapi"]) == [{"name": "fastapi-pro", "type": "skill"}]
|
| 246 |
assert calls["entity_types"] == ("skill", "agent", "mcp-server")
|
| 247 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
|
| 249 |
# ---------------------------------------------------------------------------
|
| 250 |
# load_recent_unmatched_count
|
|
|
|
| 18 |
from datetime import datetime, timezone
|
| 19 |
from pathlib import Path
|
| 20 |
|
| 21 |
+
import networkx as nx
|
| 22 |
import pytest
|
| 23 |
|
| 24 |
sys.path.insert(0, str(Path(__file__).parents[1]))
|
|
|
|
| 33 |
load_recent_unmatched_count,
|
| 34 |
write_pending_skills,
|
| 35 |
)
|
| 36 |
+
from ctx.core.graph.graph_packs import write_base_pack
|
| 37 |
|
| 38 |
TODAY = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
| 39 |
|
|
|
|
| 247 |
assert _cm.graph_suggest(["fastapi"]) == [{"name": "fastapi-pro", "type": "skill"}]
|
| 248 |
assert calls["entity_types"] == ("skill", "agent", "mcp-server")
|
| 249 |
|
| 250 |
+
def test_graph_suggest_reads_active_packs_without_legacy_graph_json(self, tmp_path, monkeypatch):
|
| 251 |
+
graph_out = tmp_path / "skill-wiki" / "graphify-out"
|
| 252 |
+
graph = nx.Graph()
|
| 253 |
+
graph.add_node("skill:fastapi-pro", type="skill", label="fastapi-pro", tags=["fastapi"])
|
| 254 |
+
write_base_pack(
|
| 255 |
+
pack_dir=graph_out / "packs" / "base-export-1",
|
| 256 |
+
pack_id="base-export-1",
|
| 257 |
+
base_export_id="export-1",
|
| 258 |
+
config_hash="config-1",
|
| 259 |
+
model_id="model-1",
|
| 260 |
+
graph=graph,
|
| 261 |
+
)
|
| 262 |
+
assert not (graph_out / "graph.json").exists()
|
| 263 |
+
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 264 |
+
calls = {}
|
| 265 |
+
|
| 266 |
+
def fake_recommend_by_tags(graph, tags, **kwargs):
|
| 267 |
+
calls["nodes"] = sorted(graph.nodes)
|
| 268 |
+
calls["tags"] = tags
|
| 269 |
+
return [{"name": "fastapi-pro", "type": "skill"}]
|
| 270 |
+
|
| 271 |
+
fake_recommend_module = type(
|
| 272 |
+
"FakeRecommendModule",
|
| 273 |
+
(),
|
| 274 |
+
{"recommend_by_tags": staticmethod(fake_recommend_by_tags)},
|
| 275 |
+
)
|
| 276 |
+
monkeypatch.setitem(
|
| 277 |
+
sys.modules,
|
| 278 |
+
"ctx.core.resolve.recommendations",
|
| 279 |
+
fake_recommend_module,
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
assert _cm.graph_suggest(["fastapi"]) == [{"name": "fastapi-pro", "type": "skill"}]
|
| 283 |
+
assert calls == {"nodes": ["skill:fastapi-pro"], "tags": ["fastapi"]}
|
| 284 |
+
|
| 285 |
|
| 286 |
# ---------------------------------------------------------------------------
|
| 287 |
# load_recent_unmatched_count
|
src/tests/test_ctx_init.py
CHANGED
|
@@ -16,6 +16,9 @@ from types import SimpleNamespace
|
|
| 16 |
import networkx as nx
|
| 17 |
import pytest
|
| 18 |
import ctx_init as ci
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
|
| 21 |
def _write_dashboard_index(path: Path, *, export_id: str = "test-export") -> None:
|
|
@@ -230,6 +233,7 @@ def test_main_auto_wizard_in_terminal_configures_custom_model(
|
|
| 230 |
"verification": "pytest ruff",
|
| 231 |
"privacy": "private repo",
|
| 232 |
"attach_mode": "mcp",
|
|
|
|
| 233 |
}
|
| 234 |
user_config = json.loads((tmp_path / "skill-system-config.json").read_text())
|
| 235 |
assert user_config["knowledge"]["mode"] == "enriched"
|
|
@@ -302,7 +306,14 @@ def test_main_with_hooks_flag_invokes_inject(tmp_path: Path, monkeypatch) -> Non
|
|
| 302 |
assert not any(c == "inject_hooks" for call in calls for c in call)
|
| 303 |
|
| 304 |
|
| 305 |
-
def _write_graph_archive(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
source = tmp_path / "archive-source"
|
| 307 |
graph_out = source / "graphify-out"
|
| 308 |
graph_out.mkdir(parents=True)
|
|
@@ -343,6 +354,27 @@ def _write_graph_archive(tmp_path: Path) -> Path:
|
|
| 343 |
entities.mkdir(parents=True)
|
| 344 |
(entities / "current.md").write_text("# Current\n", encoding="utf-8")
|
| 345 |
(source / "index.md").write_text("# Wiki\n", encoding="utf-8")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
archive = tmp_path / "wiki-graph.tar.gz"
|
| 347 |
with tarfile.open(archive, "w:gz") as tf:
|
| 348 |
for path in sorted(source.rglob("*")):
|
|
@@ -430,8 +462,8 @@ def test_lfs_pointer_graph_archive_is_ignored(
|
|
| 430 |
graph_dir.mkdir()
|
| 431 |
(graph_dir / "wiki-graph-runtime.tar.gz").write_text(
|
| 432 |
"version https://git-lfs.github.com/spec/v1\n"
|
| 433 |
-
"oid sha256:
|
| 434 |
-
"size
|
| 435 |
encoding="utf-8",
|
| 436 |
)
|
| 437 |
cwd = tmp_path / "cwd"
|
|
@@ -820,9 +852,213 @@ def test_graph_install_validation_does_not_parse_full_graph_json(
|
|
| 820 |
ci._validate_graph_install_tree(wiki)
|
| 821 |
|
| 822 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 823 |
def test_graph_install_force_prunes_stale_generated_files(
|
| 824 |
tmp_path: Path,
|
| 825 |
monkeypatch,
|
|
|
|
| 826 |
) -> None:
|
| 827 |
archive = _write_graph_archive(tmp_path)
|
| 828 |
claude = tmp_path / "home"
|
|
@@ -844,6 +1080,9 @@ def test_graph_install_force_prunes_stale_generated_files(
|
|
| 844 |
"--force",
|
| 845 |
"--model-mode", "skip",
|
| 846 |
]) == 0
|
|
|
|
|
|
|
|
|
|
| 847 |
assert not stale.exists()
|
| 848 |
assert (claude / "skill-wiki" / "entities" / "skills" / "current.md").is_file()
|
| 849 |
|
|
@@ -1278,7 +1517,7 @@ def test_recommend_harnesses_avoids_semantic_model_load_by_default(
|
|
| 1278 |
) -> None:
|
| 1279 |
graph = nx.Graph()
|
| 1280 |
graph.add_node("harness:langgraph", label="langgraph", type="harness")
|
| 1281 |
-
monkeypatch.setattr(ci, "
|
| 1282 |
monkeypatch.setattr(ci, "_harness_supports_provider", lambda *args, **kwargs: True)
|
| 1283 |
monkeypatch.setattr(ci, "_installed_harness_slugs", lambda _path: set())
|
| 1284 |
monkeypatch.setattr(
|
|
|
|
| 16 |
import networkx as nx
|
| 17 |
import pytest
|
| 18 |
import ctx_init as ci
|
| 19 |
+
from ctx.core.graph.graph_packs import write_base_pack
|
| 20 |
+
from ctx.core.graph.graph_store import validate_graph_store
|
| 21 |
+
from ctx.core.wiki.wiki_packs import write_wiki_base_pack
|
| 22 |
|
| 23 |
|
| 24 |
def _write_dashboard_index(path: Path, *, export_id: str = "test-export") -> None:
|
|
|
|
| 233 |
"verification": "pytest ruff",
|
| 234 |
"privacy": "private repo",
|
| 235 |
"attach_mode": "mcp",
|
| 236 |
+
"api_key_env": "OPENAI_API_KEY",
|
| 237 |
}
|
| 238 |
user_config = json.loads((tmp_path / "skill-system-config.json").read_text())
|
| 239 |
assert user_config["knowledge"]["mode"] == "enriched"
|
|
|
|
| 306 |
assert not any(c == "inject_hooks" for call in calls for c in call)
|
| 307 |
|
| 308 |
|
| 309 |
+
def _write_graph_archive(
|
| 310 |
+
tmp_path: Path,
|
| 311 |
+
*,
|
| 312 |
+
include_graph_pack: bool = False,
|
| 313 |
+
graph_pack_export_id: str = "test-export",
|
| 314 |
+
include_wiki_pack: bool = False,
|
| 315 |
+
wiki_pack_export_id: str = "test-export",
|
| 316 |
+
) -> Path:
|
| 317 |
source = tmp_path / "archive-source"
|
| 318 |
graph_out = source / "graphify-out"
|
| 319 |
graph_out.mkdir(parents=True)
|
|
|
|
| 354 |
entities.mkdir(parents=True)
|
| 355 |
(entities / "current.md").write_text("# Current\n", encoding="utf-8")
|
| 356 |
(source / "index.md").write_text("# Wiki\n", encoding="utf-8")
|
| 357 |
+
if include_graph_pack:
|
| 358 |
+
graph = nx.Graph()
|
| 359 |
+
graph.add_node("skill:current", label="current", type="skill")
|
| 360 |
+
write_base_pack(
|
| 361 |
+
pack_dir=graph_out / "packs" / f"base-{graph_pack_export_id}",
|
| 362 |
+
pack_id=f"base-{graph_pack_export_id}",
|
| 363 |
+
base_export_id=graph_pack_export_id,
|
| 364 |
+
config_hash="config-1",
|
| 365 |
+
model_id="model-1",
|
| 366 |
+
graph=graph,
|
| 367 |
+
)
|
| 368 |
+
if include_wiki_pack:
|
| 369 |
+
write_wiki_base_pack(
|
| 370 |
+
pack_dir=source / "wiki-packs" / f"base-{wiki_pack_export_id}",
|
| 371 |
+
pack_id=f"base-{wiki_pack_export_id}",
|
| 372 |
+
base_export_id=wiki_pack_export_id,
|
| 373 |
+
pages={
|
| 374 |
+
"index.md": "# Wiki\n",
|
| 375 |
+
"entities/skills/current.md": "# Current\n",
|
| 376 |
+
},
|
| 377 |
+
)
|
| 378 |
archive = tmp_path / "wiki-graph.tar.gz"
|
| 379 |
with tarfile.open(archive, "w:gz") as tf:
|
| 380 |
for path in sorted(source.rglob("*")):
|
|
|
|
| 462 |
graph_dir.mkdir()
|
| 463 |
(graph_dir / "wiki-graph-runtime.tar.gz").write_text(
|
| 464 |
"version https://git-lfs.github.com/spec/v1\n"
|
| 465 |
+
"oid sha256:993fc08377fdb09edcff4414c59b10fc121189b4a161bf796e3f8f6600907bb1\n"
|
| 466 |
+
"size 122141091\n",
|
| 467 |
encoding="utf-8",
|
| 468 |
)
|
| 469 |
cwd = tmp_path / "cwd"
|
|
|
|
| 852 |
ci._validate_graph_install_tree(wiki)
|
| 853 |
|
| 854 |
|
| 855 |
+
def test_graph_json_outline_scans_middle_for_edges_key(
|
| 856 |
+
tmp_path: Path,
|
| 857 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 858 |
+
) -> None:
|
| 859 |
+
monkeypatch.setattr(ci, "_GRAPH_JSON_OUTLINE_BYTES", 32)
|
| 860 |
+
filler = "x" * 256
|
| 861 |
+
graph_json = tmp_path / "graph.json"
|
| 862 |
+
graph_json.write_text(
|
| 863 |
+
'{"nodes":["' + filler + '"],"edges":[],"graph":"' + filler + '"}',
|
| 864 |
+
encoding="utf-8",
|
| 865 |
+
)
|
| 866 |
+
|
| 867 |
+
ci._validate_graph_json_outline(graph_json)
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
def test_graph_install_validation_accepts_base_pack_without_graph_json(
|
| 871 |
+
tmp_path: Path,
|
| 872 |
+
) -> None:
|
| 873 |
+
wiki = tmp_path / "wiki"
|
| 874 |
+
graph_out = wiki / "graphify-out"
|
| 875 |
+
graph_out.mkdir(parents=True)
|
| 876 |
+
(wiki / "index.md").write_text("# Wiki\n", encoding="utf-8")
|
| 877 |
+
graph = nx.Graph()
|
| 878 |
+
graph.add_node("skill:pack-only", label="pack-only", type="skill")
|
| 879 |
+
write_base_pack(
|
| 880 |
+
pack_dir=graph_out / "packs" / "base-export-1",
|
| 881 |
+
pack_id="base-export-1",
|
| 882 |
+
base_export_id="test-export",
|
| 883 |
+
config_hash="config-1",
|
| 884 |
+
model_id="model-1",
|
| 885 |
+
graph=graph,
|
| 886 |
+
)
|
| 887 |
+
(graph_out / "graph-delta.json").write_text(
|
| 888 |
+
json.dumps({"export_id": "test-export", "nodes": [], "edges": []}),
|
| 889 |
+
encoding="utf-8",
|
| 890 |
+
)
|
| 891 |
+
(graph_out / "communities.json").write_text(
|
| 892 |
+
json.dumps({"export_id": "test-export", "total_communities": 0}),
|
| 893 |
+
encoding="utf-8",
|
| 894 |
+
)
|
| 895 |
+
(graph_out / "graph-report.md").write_text(
|
| 896 |
+
"# Graph Report\n\n> Export ID: test-export\n",
|
| 897 |
+
encoding="utf-8",
|
| 898 |
+
)
|
| 899 |
+
(graph_out / "graph-export-manifest.json").write_text(
|
| 900 |
+
json.dumps({
|
| 901 |
+
"version": 1,
|
| 902 |
+
"export_id": "test-export",
|
| 903 |
+
"artifacts": {
|
| 904 |
+
"graph": "graph.json",
|
| 905 |
+
"delta": "graph-delta.json",
|
| 906 |
+
"communities": "communities.json",
|
| 907 |
+
"report": "graph-report.md",
|
| 908 |
+
},
|
| 909 |
+
}),
|
| 910 |
+
encoding="utf-8",
|
| 911 |
+
)
|
| 912 |
+
_write_dashboard_index(graph_out / "dashboard-neighborhoods.sqlite3")
|
| 913 |
+
external = wiki / "external-catalogs" / "skills-sh"
|
| 914 |
+
external.mkdir(parents=True)
|
| 915 |
+
(external / "catalog.json").write_text("{}", encoding="utf-8")
|
| 916 |
+
|
| 917 |
+
ci._validate_graph_install_tree(wiki)
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
def test_runtime_graph_install_extracts_and_validates_wiki_packs(
|
| 921 |
+
tmp_path: Path,
|
| 922 |
+
) -> None:
|
| 923 |
+
archive = _write_graph_archive(tmp_path, include_wiki_pack=True)
|
| 924 |
+
wiki = tmp_path / "installed-wiki"
|
| 925 |
+
|
| 926 |
+
ci._extract_graph_archive(archive, wiki, install_mode="runtime")
|
| 927 |
+
|
| 928 |
+
assert (wiki / "wiki-packs" / "base-test-export" / "wiki-pack-manifest.json").is_file()
|
| 929 |
+
assert not (wiki / "entities" / "skills" / "current.md").exists()
|
| 930 |
+
ci._validate_graph_install_tree(wiki)
|
| 931 |
+
assert ci._graph_full_install_complete(wiki) is True
|
| 932 |
+
|
| 933 |
+
|
| 934 |
+
def test_runtime_graph_install_extracts_and_validates_graph_packs(
|
| 935 |
+
tmp_path: Path,
|
| 936 |
+
) -> None:
|
| 937 |
+
archive = _write_graph_archive(tmp_path, include_graph_pack=True)
|
| 938 |
+
wiki = tmp_path / "installed-wiki"
|
| 939 |
+
|
| 940 |
+
ci._extract_graph_archive(archive, wiki, install_mode="runtime")
|
| 941 |
+
|
| 942 |
+
assert (
|
| 943 |
+
wiki / "graphify-out" / "packs" / "base-test-export" / "graph-pack-manifest.json"
|
| 944 |
+
).is_file()
|
| 945 |
+
ci._validate_graph_install_tree(wiki)
|
| 946 |
+
|
| 947 |
+
|
| 948 |
+
def test_build_graph_refreshes_operational_graph_store(
|
| 949 |
+
tmp_path: Path,
|
| 950 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 951 |
+
) -> None:
|
| 952 |
+
archive = _write_graph_archive(tmp_path, include_graph_pack=True)
|
| 953 |
+
claude = tmp_path / "home"
|
| 954 |
+
monkeypatch.setattr(
|
| 955 |
+
ci,
|
| 956 |
+
"_find_local_graph_archive",
|
| 957 |
+
lambda _install_mode="runtime": archive,
|
| 958 |
+
)
|
| 959 |
+
monkeypatch.setattr(ci, "_verify_local_graph_archive", lambda *_a, **_k: None)
|
| 960 |
+
monkeypatch.setattr(ci, "_install_graph_entity_overlay", lambda *_a, **_k: None)
|
| 961 |
+
|
| 962 |
+
assert ci.build_graph(claude) == 0
|
| 963 |
+
graph_dir = claude / "skill-wiki" / "graphify-out"
|
| 964 |
+
store = graph_dir / "graph-store.sqlite3"
|
| 965 |
+
assert validate_graph_store(store, graph_dir)["ok"] is True
|
| 966 |
+
|
| 967 |
+
store.unlink()
|
| 968 |
+
assert ci.build_graph(claude) == 0
|
| 969 |
+
assert validate_graph_store(store, graph_dir)["ok"] is True
|
| 970 |
+
|
| 971 |
+
|
| 972 |
+
def test_graph_install_rejects_mismatched_graph_pack_export_id(
|
| 973 |
+
tmp_path: Path,
|
| 974 |
+
) -> None:
|
| 975 |
+
archive = _write_graph_archive(
|
| 976 |
+
tmp_path,
|
| 977 |
+
include_graph_pack=True,
|
| 978 |
+
graph_pack_export_id="wrong-export",
|
| 979 |
+
)
|
| 980 |
+
|
| 981 |
+
with pytest.raises(ValueError, match="graphify-out/packs export_id mismatch"):
|
| 982 |
+
ci._extract_graph_archive(archive, tmp_path / "installed-wiki", install_mode="runtime")
|
| 983 |
+
|
| 984 |
+
|
| 985 |
+
def test_graph_install_rejects_mismatched_wiki_pack_export_id(
|
| 986 |
+
tmp_path: Path,
|
| 987 |
+
) -> None:
|
| 988 |
+
archive = _write_graph_archive(
|
| 989 |
+
tmp_path,
|
| 990 |
+
include_wiki_pack=True,
|
| 991 |
+
wiki_pack_export_id="wrong-export",
|
| 992 |
+
)
|
| 993 |
+
|
| 994 |
+
with pytest.raises(ValueError, match="wiki-packs export_id mismatch"):
|
| 995 |
+
ci._extract_graph_archive(archive, tmp_path / "installed-wiki", install_mode="runtime")
|
| 996 |
+
|
| 997 |
+
|
| 998 |
+
def test_runtime_graph_install_without_full_entities_is_not_full_install(
|
| 999 |
+
tmp_path: Path,
|
| 1000 |
+
) -> None:
|
| 1001 |
+
archive = _write_graph_archive(tmp_path)
|
| 1002 |
+
wiki = tmp_path / "installed-wiki"
|
| 1003 |
+
|
| 1004 |
+
ci._extract_graph_archive(archive, wiki, install_mode="runtime")
|
| 1005 |
+
|
| 1006 |
+
assert ci._graph_install_complete(wiki) is True
|
| 1007 |
+
assert ci._graph_full_install_complete(wiki) is False
|
| 1008 |
+
|
| 1009 |
+
|
| 1010 |
+
def test_full_graph_install_uses_system_tar_after_validation(
|
| 1011 |
+
tmp_path: Path,
|
| 1012 |
+
monkeypatch,
|
| 1013 |
+
) -> None:
|
| 1014 |
+
archive = _write_graph_archive(tmp_path)
|
| 1015 |
+
wiki = tmp_path / "installed-wiki"
|
| 1016 |
+
calls: list[list[str]] = []
|
| 1017 |
+
|
| 1018 |
+
def fake_run(cmd: list[str], **_kwargs: object) -> SimpleNamespace:
|
| 1019 |
+
calls.append(list(cmd))
|
| 1020 |
+
target = Path(cmd[cmd.index("-C") + 1])
|
| 1021 |
+
with tarfile.open(archive, "r:gz") as tf:
|
| 1022 |
+
tf.extractall(target)
|
| 1023 |
+
return SimpleNamespace(returncode=0, stdout="", stderr="")
|
| 1024 |
+
|
| 1025 |
+
monkeypatch.setattr(ci.shutil, "which", lambda _name: "tar")
|
| 1026 |
+
monkeypatch.setattr(ci.subprocess, "run", fake_run)
|
| 1027 |
+
|
| 1028 |
+
ci._extract_graph_archive(archive, wiki, install_mode="full")
|
| 1029 |
+
|
| 1030 |
+
assert len(calls) == 1
|
| 1031 |
+
assert calls[0][:3] == ["tar", "-xzf", str(archive)]
|
| 1032 |
+
assert calls[0][3] == "-C"
|
| 1033 |
+
assert Path(calls[0][4]).name.startswith(".installed-wiki-stage-")
|
| 1034 |
+
assert ci._graph_full_install_complete(wiki) is True
|
| 1035 |
+
assert (wiki / "entities" / "skills" / "current.md").is_file()
|
| 1036 |
+
|
| 1037 |
+
|
| 1038 |
+
def test_full_graph_install_prefers_wiki_packs_over_expanded_entities(
|
| 1039 |
+
tmp_path: Path,
|
| 1040 |
+
monkeypatch,
|
| 1041 |
+
) -> None:
|
| 1042 |
+
archive = _write_graph_archive(tmp_path, include_wiki_pack=True)
|
| 1043 |
+
wiki = tmp_path / "installed-wiki"
|
| 1044 |
+
|
| 1045 |
+
def fail_if_system_tar_is_used(*_args: object, **_kwargs: object) -> SimpleNamespace:
|
| 1046 |
+
pytest.fail("packed full install should use filtered extraction")
|
| 1047 |
+
|
| 1048 |
+
monkeypatch.setattr(ci.shutil, "which", lambda _name: "tar")
|
| 1049 |
+
monkeypatch.setattr(ci.subprocess, "run", fail_if_system_tar_is_used)
|
| 1050 |
+
|
| 1051 |
+
ci._extract_graph_archive(archive, wiki, install_mode="full")
|
| 1052 |
+
|
| 1053 |
+
assert (wiki / "wiki-packs" / "base-test-export" / "wiki-pack-manifest.json").is_file()
|
| 1054 |
+
assert not (wiki / "entities" / "skills" / "current.md").exists()
|
| 1055 |
+
assert ci._graph_full_install_complete(wiki) is True
|
| 1056 |
+
|
| 1057 |
+
|
| 1058 |
def test_graph_install_force_prunes_stale_generated_files(
|
| 1059 |
tmp_path: Path,
|
| 1060 |
monkeypatch,
|
| 1061 |
+
capsys,
|
| 1062 |
) -> None:
|
| 1063 |
archive = _write_graph_archive(tmp_path)
|
| 1064 |
claude = tmp_path / "home"
|
|
|
|
| 1080 |
"--force",
|
| 1081 |
"--model-mode", "skip",
|
| 1082 |
]) == 0
|
| 1083 |
+
out = capsys.readouterr().out
|
| 1084 |
+
assert "full graph install expands the markdown LLM-wiki" in out
|
| 1085 |
+
assert "runtime mode is enough for recommendations" in out
|
| 1086 |
assert not stale.exists()
|
| 1087 |
assert (claude / "skill-wiki" / "entities" / "skills" / "current.md").is_file()
|
| 1088 |
|
|
|
|
| 1517 |
) -> None:
|
| 1518 |
graph = nx.Graph()
|
| 1519 |
graph.add_node("harness:langgraph", label="langgraph", type="harness")
|
| 1520 |
+
monkeypatch.setattr(ci, "_load_harness_recommendation_graph", lambda: graph)
|
| 1521 |
monkeypatch.setattr(ci, "_harness_supports_provider", lambda *args, **kwargs: True)
|
| 1522 |
monkeypatch.setattr(ci, "_installed_harness_slugs", lambda _path: set())
|
| 1523 |
monkeypatch.setattr(
|
src/tests/test_ctx_monitor.py
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
src/tests/test_ctx_monitor_3type.py
CHANGED
|
@@ -24,13 +24,17 @@ from __future__ import annotations
|
|
| 24 |
import json
|
| 25 |
import sys
|
| 26 |
from pathlib import Path
|
|
|
|
| 27 |
|
| 28 |
import networkx as nx
|
| 29 |
import pytest
|
| 30 |
|
| 31 |
sys.path.insert(0, str(Path(__file__).parents[1]))
|
| 32 |
|
| 33 |
-
import
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
|
| 36 |
# ────────────────────────────────────────────────────────────────────
|
|
@@ -40,7 +44,8 @@ import ctx_monitor as _cm
|
|
| 40 |
|
| 41 |
@pytest.fixture()
|
| 42 |
def wiki_3type(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
| 43 |
-
"""Build a minimal wiki and point
|
|
|
|
| 44 |
wiki = tmp_path / "skill-wiki"
|
| 45 |
for sub in ("skills", "agents", "harnesses"):
|
| 46 |
(wiki / "entities" / sub).mkdir(parents=True)
|
|
@@ -78,8 +83,8 @@ def wiki_3type(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
|
| 78 |
encoding="utf-8",
|
| 79 |
)
|
| 80 |
|
| 81 |
-
monkeypatch.setattr(
|
| 82 |
-
monkeypatch.setattr(
|
| 83 |
return wiki
|
| 84 |
|
| 85 |
|
|
@@ -90,17 +95,24 @@ def wiki_3type(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
|
| 90 |
|
| 91 |
class TestWikiStats:
|
| 92 |
def test_counts_include_mcps(self, wiki_3type):
|
| 93 |
-
s =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
assert s["skills"] == 2
|
| 95 |
assert s["agents"] == 1
|
| 96 |
assert s["mcps"] == 3
|
| 97 |
assert s["harnesses"] == 1
|
| 98 |
assert s["total"] == 7
|
|
|
|
| 99 |
|
| 100 |
def test_mcps_sharded_dirs_scanned_recursively(self, wiki_3type):
|
| 101 |
"""MCPs live under entities/mcp-servers/<first-char>/<slug>.md —
|
| 102 |
the scan must walk the shard dirs, not just the top level."""
|
| 103 |
-
s =
|
| 104 |
assert s["mcps"] == 3 # 2 under a/, 1 under p/
|
| 105 |
|
| 106 |
def test_no_mcp_dir_gracefully_zero(self, tmp_path, monkeypatch):
|
|
@@ -108,8 +120,8 @@ class TestWikiStats:
|
|
| 108 |
users who have only ingested skills."""
|
| 109 |
wiki = tmp_path / "wiki"
|
| 110 |
(wiki / "entities" / "skills").mkdir(parents=True)
|
| 111 |
-
monkeypatch.setattr(
|
| 112 |
-
s =
|
| 113 |
assert s["mcps"] == 0
|
| 114 |
assert s["harnesses"] == 0
|
| 115 |
assert "mcps" in s # key present even at zero
|
|
@@ -127,14 +139,14 @@ class TestGraphStats:
|
|
| 127 |
"> Nodes: 102,697 | Edges: 2,900,910 | Communities: 52\n",
|
| 128 |
encoding="utf-8",
|
| 129 |
)
|
| 130 |
-
monkeypatch.setattr(
|
| 131 |
monkeypatch.setattr(
|
| 132 |
-
|
| 133 |
-
"
|
| 134 |
lambda: (_ for _ in ()).throw(AssertionError("loaded graph.json")),
|
| 135 |
)
|
| 136 |
|
| 137 |
-
assert
|
| 138 |
"nodes": 102697,
|
| 139 |
"edges": 2900910,
|
| 140 |
"available": True,
|
|
@@ -148,7 +160,7 @@ class TestGraphStats:
|
|
| 148 |
|
| 149 |
class TestWikiIndexEntries:
|
| 150 |
def test_entries_include_mcp_servers(self, wiki_3type):
|
| 151 |
-
entries =
|
| 152 |
types = {e["type"] for e in entries}
|
| 153 |
assert "mcp-server" in types
|
| 154 |
assert "harness" in types
|
|
@@ -156,20 +168,97 @@ class TestWikiIndexEntries:
|
|
| 156 |
assert "agent" in types
|
| 157 |
|
| 158 |
def test_mcp_slugs_surfaced_from_both_shards(self, wiki_3type):
|
| 159 |
-
entries =
|
| 160 |
slugs = {e["slug"] for e in entries if e["type"] == "mcp-server"}
|
| 161 |
assert slugs == {"anthropic-python-sdk", "atlassian-cloud", "pulsemcp-meta"}
|
| 162 |
|
| 163 |
def test_wiki_entity_path_resolves_sharded_mcp_pages(self, wiki_3type):
|
| 164 |
-
|
|
|
|
|
|
|
| 165 |
assert path == (
|
| 166 |
wiki_3type / "entities" / "mcp-servers" / "a" / "anthropic-python-sdk.md"
|
| 167 |
)
|
| 168 |
|
| 169 |
def test_wiki_entity_path_resolves_harness_pages(self, wiki_3type):
|
| 170 |
-
path =
|
| 171 |
assert path == wiki_3type / "entities" / "harnesses" / "langgraph.md"
|
| 172 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
def test_wiki_search_indexes_tags_beyond_preview_limit(self, wiki_3type):
|
| 174 |
page = wiki_3type / "entities" / "skills" / "many-tags.md"
|
| 175 |
page.write_text(
|
|
@@ -181,14 +270,14 @@ class TestWikiIndexEntries:
|
|
| 181 |
encoding="utf-8",
|
| 182 |
)
|
| 183 |
|
| 184 |
-
entries =
|
| 185 |
entry = next(e for e in entries if e["slug"] == "many-tags")
|
| 186 |
|
| 187 |
assert entry["tags"] == ["one", "two", "three", "four", "five", "six"]
|
| 188 |
assert "seventh" in entry["search_tags"]
|
| 189 |
|
| 190 |
def test_index_entries_can_sample_per_entity_type(self, wiki_3type):
|
| 191 |
-
entries =
|
| 192 |
counts: dict[str, int] = {}
|
| 193 |
for entry in entries:
|
| 194 |
counts[entry["type"]] = counts.get(entry["type"], 0) + 1
|
|
@@ -212,7 +301,7 @@ def test_wiki_index_sampling_is_sorted_by_slug(wiki_3type: Path) -> None:
|
|
| 212 |
encoding="utf-8",
|
| 213 |
)
|
| 214 |
|
| 215 |
-
entries =
|
| 216 |
skill_entries = [entry for entry in entries if entry["type"] == "skill"]
|
| 217 |
|
| 218 |
assert [entry["slug"] for entry in skill_entries] == ["aaa-first"]
|
|
@@ -222,7 +311,7 @@ def test_wiki_entity_page_marks_truncated_body_and_frontmatter(
|
|
| 222 |
wiki_3type: Path,
|
| 223 |
monkeypatch: pytest.MonkeyPatch,
|
| 224 |
) -> None:
|
| 225 |
-
monkeypatch.setattr(
|
| 226 |
long_description = "x" * 160
|
| 227 |
long_body = "body-line\n" * 1400
|
| 228 |
(wiki_3type / "entities" / "skills" / "long-page.md").write_text(
|
|
@@ -234,7 +323,7 @@ def test_wiki_entity_page_marks_truncated_body_and_frontmatter(
|
|
| 234 |
encoding="utf-8",
|
| 235 |
)
|
| 236 |
|
| 237 |
-
html =
|
| 238 |
|
| 239 |
assert "Body preview truncated at 12,000 characters." in html
|
| 240 |
assert "(truncated)" in html
|
|
@@ -244,14 +333,14 @@ class TestRenderHome3Type:
|
|
| 244 |
def test_wiki_card_shows_mcp_count(self, wiki_3type, monkeypatch):
|
| 245 |
# Other dependencies of _render_home need shims that don't touch
|
| 246 |
# the real user dir. Empty manifests + empty audit log are fine.
|
| 247 |
-
monkeypatch.setattr(
|
| 248 |
-
monkeypatch.setattr(
|
| 249 |
-
monkeypatch.setattr(
|
| 250 |
-
monkeypatch.setattr(
|
| 251 |
-
monkeypatch.setattr(
|
| 252 |
-
monkeypatch.setattr(
|
| 253 |
-
|
| 254 |
-
html =
|
| 255 |
# The detail line inside the Wiki entities card must name MCPs.
|
| 256 |
assert "MCPs" in html
|
| 257 |
assert "2 skills" in html or "2 skill" in html
|
|
@@ -264,7 +353,7 @@ class TestSessionSummaries3Type:
|
|
| 264 |
def test_agent_unload_and_mcp_actions_get_own_buckets(self, tmp_path, monkeypatch):
|
| 265 |
claude = tmp_path / ".claude"
|
| 266 |
claude.mkdir()
|
| 267 |
-
monkeypatch.setattr(
|
| 268 |
records = [
|
| 269 |
{
|
| 270 |
"ts": "2026-05-02T10:00:00Z",
|
|
@@ -307,7 +396,7 @@ class TestSessionSummaries3Type:
|
|
| 307 |
encoding="utf-8",
|
| 308 |
)
|
| 309 |
|
| 310 |
-
session =
|
| 311 |
|
| 312 |
assert session["agents_loaded"] == ["code-reviewer"]
|
| 313 |
assert session["skills_loaded"] == []
|
|
@@ -317,7 +406,7 @@ class TestSessionSummaries3Type:
|
|
| 317 |
assert session["mcps_unloaded"] == ["anthropic-python-sdk"]
|
| 318 |
|
| 319 |
def test_sessions_index_renders_agent_and_mcp_columns(self, monkeypatch):
|
| 320 |
-
monkeypatch.setattr(
|
| 321 |
"session_id": "S1",
|
| 322 |
"first_seen": "2026-05-02T10:00:00Z",
|
| 323 |
"last_seen": "2026-05-02T10:02:00Z",
|
|
@@ -330,7 +419,7 @@ class TestSessionSummaries3Type:
|
|
| 330 |
"lifecycle_transitions": 0,
|
| 331 |
}])
|
| 332 |
|
| 333 |
-
html =
|
| 334 |
|
| 335 |
assert "Agents↓" in html
|
| 336 |
assert "MCPs↑" in html
|
|
@@ -345,8 +434,8 @@ class TestSessionSummaries3Type:
|
|
| 345 |
|
| 346 |
class TestRenderWikiIndex3Type:
|
| 347 |
def test_mcp_server_checkbox_present(self, wiki_3type, monkeypatch):
|
| 348 |
-
monkeypatch.setattr(
|
| 349 |
-
html =
|
| 350 |
assert "value='mcp-server' checked" in html
|
| 351 |
assert "value='harness' checked" in html
|
| 352 |
# Count for the mcp-server bucket should render.
|
|
@@ -359,9 +448,9 @@ class TestRenderWikiIndex3Type:
|
|
| 359 |
"---\ntype: skill\ntags: [one, two, three, four, five, six, seventh]\n---\n# many-tags\n",
|
| 360 |
encoding="utf-8",
|
| 361 |
)
|
| 362 |
-
monkeypatch.setattr(
|
| 363 |
|
| 364 |
-
html =
|
| 365 |
|
| 366 |
assert "data-tags='one two three four five six seventh'" in html
|
| 367 |
|
|
@@ -373,9 +462,9 @@ class TestRenderWikiIndex3Type:
|
|
| 373 |
|
| 374 |
class TestRenderLoaded3Type:
|
| 375 |
def test_heading_names_all_three_types(self, monkeypatch):
|
| 376 |
-
monkeypatch.setattr(
|
| 377 |
lambda: {"load": [], "unload": []})
|
| 378 |
-
html =
|
| 379 |
assert "skills, agents, MCPs & harnesses" in html or (
|
| 380 |
"skills, agents, MCPs & harnesses" in html
|
| 381 |
)
|
|
@@ -394,8 +483,8 @@ class TestRenderLoaded3Type:
|
|
| 394 |
],
|
| 395 |
"unload": [],
|
| 396 |
}
|
| 397 |
-
monkeypatch.setattr(
|
| 398 |
-
html =
|
| 399 |
# Four section headers render — one per type.
|
| 400 |
assert "<h3" in html
|
| 401 |
assert "Skills " in html or "Skills</h3" in html or "Skills " in html
|
|
@@ -420,8 +509,8 @@ class TestRenderLoaded3Type:
|
|
| 420 |
],
|
| 421 |
"unload": [],
|
| 422 |
}
|
| 423 |
-
monkeypatch.setattr(
|
| 424 |
-
html =
|
| 425 |
assert "data-etype='skill'" in html
|
| 426 |
assert "data-etype='agent'" in html
|
| 427 |
assert "data-etype='mcp-server'" in html
|
|
@@ -432,9 +521,9 @@ class TestRenderLoaded3Type:
|
|
| 432 |
"""Pre-install_utils manifest entries had no entity_type field.
|
| 433 |
Those must default to skill (what the implicit contract was)
|
| 434 |
and still render in the Skills section without crashing."""
|
| 435 |
-
monkeypatch.setattr(
|
| 436 |
lambda: {"load": [{"skill": "legacy"}], "unload": []})
|
| 437 |
-
html =
|
| 438 |
assert "legacy" in html
|
| 439 |
assert "data-etype='skill'" in html
|
| 440 |
|
|
@@ -450,8 +539,8 @@ class TestRenderLoaded3Type:
|
|
| 450 |
},
|
| 451 |
],
|
| 452 |
}
|
| 453 |
-
monkeypatch.setattr(
|
| 454 |
-
html =
|
| 455 |
assert "data-slug='code-reviewer' data-etype='agent'" in html
|
| 456 |
assert (
|
| 457 |
"data-slug='anthropic-python-sdk' data-etype='mcp-server'"
|
|
@@ -478,7 +567,7 @@ class TestPerformUnloadByEntityType:
|
|
| 478 |
from ctx.adapters.claude_code.install import skill_unload
|
| 479 |
monkeypatch.setattr(skill_unload, "unload_from_session",
|
| 480 |
fake_unload_from_session)
|
| 481 |
-
ok, msg =
|
| 482 |
assert ok
|
| 483 |
assert calls["slugs"] == ["python-patterns"]
|
| 484 |
assert calls["entity_type"] == "skill"
|
|
@@ -504,7 +593,7 @@ class TestPerformUnloadByEntityType:
|
|
| 504 |
from ctx.adapters.claude_code.install import mcp_install
|
| 505 |
monkeypatch.setattr(mcp_install, "uninstall_mcp", fake_uninstall)
|
| 506 |
|
| 507 |
-
ok, msg =
|
| 508 |
entity_type="mcp-server")
|
| 509 |
assert ok
|
| 510 |
assert calls["slug"] == "anthropic-python-sdk"
|
|
@@ -517,7 +606,7 @@ class TestPerformUnloadByEntityType:
|
|
| 517 |
):
|
| 518 |
claude = tmp_path / ".claude"
|
| 519 |
claude.mkdir()
|
| 520 |
-
monkeypatch.setattr(
|
| 521 |
(claude / "skill-manifest.json").write_text(
|
| 522 |
json.dumps({
|
| 523 |
"load": [{
|
|
@@ -531,7 +620,7 @@ class TestPerformUnloadByEntityType:
|
|
| 531 |
encoding="utf-8",
|
| 532 |
)
|
| 533 |
|
| 534 |
-
ok, msg =
|
| 535 |
|
| 536 |
assert ok, msg
|
| 537 |
manifest = json.loads(
|
|
@@ -558,7 +647,7 @@ class TestPerformUnloadByEntityType:
|
|
| 558 |
message="claude mcp remove failed"),
|
| 559 |
)
|
| 560 |
|
| 561 |
-
ok, msg =
|
| 562 |
assert not ok
|
| 563 |
assert "claude mcp remove failed" in msg
|
| 564 |
|
|
@@ -573,7 +662,7 @@ class TestPerformUnloadByEntityType:
|
|
| 573 |
|
| 574 |
claude = tmp_path / ".claude"
|
| 575 |
claude.mkdir()
|
| 576 |
-
monkeypatch.setattr(
|
| 577 |
from ctx.adapters.claude_code.install import mcp_install
|
| 578 |
monkeypatch.setattr(
|
| 579 |
mcp_install,
|
|
@@ -581,7 +670,7 @@ class TestPerformUnloadByEntityType:
|
|
| 581 |
lambda slug, **kw: _FakeResult(slug=slug, status="uninstalled"),
|
| 582 |
)
|
| 583 |
|
| 584 |
-
ok, msg =
|
| 585 |
|
| 586 |
assert ok, msg
|
| 587 |
audit = json.loads((claude / "ctx-audit.jsonl").read_text(encoding="utf-8"))
|
|
@@ -591,7 +680,7 @@ class TestPerformUnloadByEntityType:
|
|
| 591 |
assert audit["meta"]["action"] == "unloaded"
|
| 592 |
|
| 593 |
def test_invalid_slug_rejected(self):
|
| 594 |
-
ok, msg =
|
| 595 |
assert not ok
|
| 596 |
assert "invalid slug" in msg
|
| 597 |
|
|
@@ -603,7 +692,7 @@ class TestPerformUnloadByEntityType:
|
|
| 603 |
|
| 604 |
monkeypatch.setattr(skill_unload, "unload_from_session", fail_if_called)
|
| 605 |
|
| 606 |
-
ok, msg =
|
| 607 |
|
| 608 |
assert not ok
|
| 609 |
assert "unsupported entity_type" in msg
|
|
@@ -612,8 +701,8 @@ class TestPerformUnloadByEntityType:
|
|
| 612 |
class TestRenderSidecarDetail3Type:
|
| 613 |
def test_sidecar_timeline_filters_duplicate_slug_by_entity_type(self, monkeypatch):
|
| 614 |
monkeypatch.setattr(
|
| 615 |
-
|
| 616 |
-
"
|
| 617 |
lambda slug, entity_type=None: {
|
| 618 |
"slug": slug,
|
| 619 |
"subject_type": "harness",
|
|
@@ -622,8 +711,8 @@ class TestRenderSidecarDetail3Type:
|
|
| 622 |
},
|
| 623 |
)
|
| 624 |
monkeypatch.setattr(
|
| 625 |
-
|
| 626 |
-
"
|
| 627 |
lambda *args, **kwargs: [
|
| 628 |
{
|
| 629 |
"ts": "t1",
|
|
@@ -649,7 +738,7 @@ class TestRenderSidecarDetail3Type:
|
|
| 649 |
],
|
| 650 |
)
|
| 651 |
|
| 652 |
-
html =
|
| 653 |
|
| 654 |
assert "harness.installed" in html
|
| 655 |
assert "Audit timeline (1 entries)" in html
|
|
@@ -677,12 +766,12 @@ class TestPerformLoadByEntityType:
|
|
| 677 |
from ctx.adapters.claude_code.install import skill_install
|
| 678 |
monkeypatch.setattr(skill_install, "install_skill", fake_install)
|
| 679 |
|
| 680 |
-
ok, msg =
|
| 681 |
|
| 682 |
assert ok
|
| 683 |
assert msg == "ok"
|
| 684 |
assert calls["slug"] == "python-patterns"
|
| 685 |
-
assert calls["kw"]["wiki_dir"] ==
|
| 686 |
|
| 687 |
def test_agent_type_calls_agent_install(self, monkeypatch):
|
| 688 |
from dataclasses import dataclass
|
|
@@ -703,12 +792,12 @@ class TestPerformLoadByEntityType:
|
|
| 703 |
from ctx.adapters.claude_code.install import agent_install
|
| 704 |
monkeypatch.setattr(agent_install, "install_agent", fake_install)
|
| 705 |
|
| 706 |
-
ok, msg =
|
| 707 |
|
| 708 |
assert ok
|
| 709 |
assert msg == "ok"
|
| 710 |
assert calls["slug"] == "code-reviewer"
|
| 711 |
-
assert calls["kw"]["agents_dir"] ==
|
| 712 |
|
| 713 |
def test_mcp_type_calls_mcp_install_auto(self, monkeypatch):
|
| 714 |
from dataclasses import dataclass
|
|
@@ -729,7 +818,7 @@ class TestPerformLoadByEntityType:
|
|
| 729 |
from ctx.adapters.claude_code.install import mcp_install
|
| 730 |
monkeypatch.setattr(mcp_install, "install_mcp", fake_install)
|
| 731 |
|
| 732 |
-
ok, msg =
|
| 733 |
entity_type="mcp-server")
|
| 734 |
|
| 735 |
assert ok
|
|
@@ -756,7 +845,7 @@ class TestPerformLoadByEntityType:
|
|
| 756 |
from ctx.adapters.claude_code.install import mcp_install
|
| 757 |
monkeypatch.setattr(mcp_install, "install_mcp", fake_install)
|
| 758 |
|
| 759 |
-
ok, msg =
|
| 760 |
"anthropic-python-sdk",
|
| 761 |
entity_type="mcp-server",
|
| 762 |
command="npx -y @anthropic/sdk",
|
|
@@ -778,7 +867,7 @@ class TestPerformLoadByEntityType:
|
|
| 778 |
|
| 779 |
claude = tmp_path / ".claude"
|
| 780 |
claude.mkdir()
|
| 781 |
-
monkeypatch.setattr(
|
| 782 |
from ctx.adapters.claude_code.install import mcp_install
|
| 783 |
monkeypatch.setattr(
|
| 784 |
mcp_install,
|
|
@@ -786,7 +875,7 @@ class TestPerformLoadByEntityType:
|
|
| 786 |
lambda slug, **kw: _FakeResult(slug=slug, status="installed"),
|
| 787 |
)
|
| 788 |
|
| 789 |
-
ok, msg =
|
| 790 |
|
| 791 |
assert ok, msg
|
| 792 |
audit = json.loads((claude / "ctx-audit.jsonl").read_text(encoding="utf-8"))
|
|
@@ -795,7 +884,7 @@ class TestPerformLoadByEntityType:
|
|
| 795 |
assert audit["meta"]["action"] == "loaded"
|
| 796 |
|
| 797 |
def test_harness_type_hands_off_to_cli(self):
|
| 798 |
-
ok, msg =
|
| 799 |
assert not ok
|
| 800 |
assert "ctx-harness-install langgraph --dry-run" in msg
|
| 801 |
|
|
@@ -807,10 +896,10 @@ class TestPerformLoadByEntityType:
|
|
| 807 |
|
| 808 |
class TestRenderGraphSidebar:
|
| 809 |
def test_sidebar_type_checkboxes_include_mcp_server(self, monkeypatch):
|
| 810 |
-
monkeypatch.setattr(
|
| 811 |
lambda: {"nodes": 10, "edges": 20, "available": True})
|
| 812 |
-
monkeypatch.setattr(
|
| 813 |
-
html =
|
| 814 |
# Four type checkboxes: skill, agent, mcp-server, harness.
|
| 815 |
assert "class='graph-type-filter' value='skill'" in html
|
| 816 |
assert "class='graph-type-filter' value='agent'" in html
|
|
@@ -818,20 +907,20 @@ class TestRenderGraphSidebar:
|
|
| 818 |
assert "class='graph-type-filter' value='harness'" in html
|
| 819 |
|
| 820 |
def test_sidebar_has_tag_filter(self, monkeypatch):
|
| 821 |
-
monkeypatch.setattr(
|
| 822 |
lambda: {"nodes": 0, "edges": 0, "available": False})
|
| 823 |
-
monkeypatch.setattr(
|
| 824 |
-
html =
|
| 825 |
assert "id='tag-filter'" in html
|
| 826 |
assert "filter_tokens" in html
|
| 827 |
assert "isFocus || !tagQ" in html
|
| 828 |
|
| 829 |
def test_graph_list_styles_mcp_and_harness_nodes_distinctly(self, monkeypatch):
|
| 830 |
"""The graph list view shows four types; each must be visually distinct."""
|
| 831 |
-
monkeypatch.setattr(
|
| 832 |
lambda: {"nodes": 0, "edges": 0, "available": False})
|
| 833 |
-
monkeypatch.setattr(
|
| 834 |
-
html =
|
| 835 |
assert ".entity-type-skill" in html
|
| 836 |
assert ".entity-type-agent" in html
|
| 837 |
assert ".entity-type-mcp-server" in html
|
|
@@ -842,10 +931,10 @@ class TestRenderGraphSidebar:
|
|
| 842 |
)
|
| 843 |
|
| 844 |
def test_graph_filters_fallback_rows_and_connected_edges(self, monkeypatch):
|
| 845 |
-
monkeypatch.setattr(
|
| 846 |
lambda: {"nodes": 0, "edges": 0, "available": False})
|
| 847 |
-
monkeypatch.setattr(
|
| 848 |
-
html =
|
| 849 |
|
| 850 |
assert "document.querySelectorAll('[data-testid=\"graph-fallback-node\"]')" in html
|
| 851 |
assert "n.style.display = hidden ? 'none' : 'flex'" in html
|
|
@@ -855,10 +944,10 @@ class TestRenderGraphSidebar:
|
|
| 855 |
def test_tap_handler_strips_mcp_server_prefix(self, monkeypatch):
|
| 856 |
"""Clicking an MCP node must route to /wiki/<slug> — the
|
| 857 |
prefix-stripping regex has to know all four types."""
|
| 858 |
-
monkeypatch.setattr(
|
| 859 |
lambda: {"nodes": 0, "edges": 0, "available": False})
|
| 860 |
-
monkeypatch.setattr(
|
| 861 |
-
html =
|
| 862 |
# Regex should include mcp-server and harness in the prefix alternation.
|
| 863 |
assert "(skill|agent|mcp-server|harness)" in html
|
| 864 |
|
|
@@ -868,9 +957,9 @@ class TestRenderGraphSidebar:
|
|
| 868 |
graph.add_node("harness:langgraph", label="langgraph", type="harness", tags=["agent"])
|
| 869 |
graph.add_node("skill:agent-patterns", label="agent-patterns", type="skill", tags=["agent"])
|
| 870 |
graph.add_edge("harness:langgraph", "skill:agent-patterns", weight=2, shared_tags=["agent"])
|
| 871 |
-
monkeypatch.setattr(
|
| 872 |
|
| 873 |
-
out =
|
| 874 |
|
| 875 |
assert out["center"] == "harness:langgraph"
|
| 876 |
assert any(n["data"]["type"] == "harness" for n in out["nodes"])
|
|
@@ -882,9 +971,9 @@ class TestRenderGraphSidebar:
|
|
| 882 |
graph.add_node("skill:c", label="c", type="skill", tags=[])
|
| 883 |
graph.add_edge("skill:a", "skill:b", weight=2)
|
| 884 |
graph.add_edge("skill:b", "skill:c", weight=1)
|
| 885 |
-
monkeypatch.setattr(
|
| 886 |
|
| 887 |
-
out =
|
| 888 |
|
| 889 |
edge_ids = [edge["data"]["id"] for edge in out["edges"]]
|
| 890 |
assert len(edge_ids) == len(set(edge_ids))
|
|
@@ -898,9 +987,9 @@ class TestRenderGraphSidebar:
|
|
| 898 |
graph.add_node("skill:a", label="a", type="skill", tags=[])
|
| 899 |
graph.add_node("skill:b", label="b", type="skill", tags=[])
|
| 900 |
graph.add_edge("skill:a", "skill:b", weight=1, shared_tags=["security"])
|
| 901 |
-
monkeypatch.setattr(
|
| 902 |
|
| 903 |
-
out =
|
| 904 |
|
| 905 |
by_id = {node["data"]["id"]: node["data"] for node in out["nodes"]}
|
| 906 |
assert "security" in by_id["skill:a"]["filter_tokens"]
|
|
@@ -922,11 +1011,16 @@ class TestMonitorRoutesPreserveEntityType:
|
|
| 922 |
handler._send_500 = lambda exc: sent.setdefault("500", exc)
|
| 923 |
handler._api_reads_enabled = lambda: True
|
| 924 |
handler._mutations_enabled = lambda: True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 925 |
if html_fn is not None:
|
| 926 |
handler._send_html = html_fn
|
| 927 |
if json_fn is not None:
|
| 928 |
handler._send_json = json_fn
|
| 929 |
-
|
| 930 |
return sent
|
| 931 |
|
| 932 |
def test_graph_route_passes_type_query(self, monkeypatch):
|
|
@@ -937,7 +1031,7 @@ class TestMonitorRoutesPreserveEntityType:
|
|
| 937 |
calls["focus_type"] = focus_type
|
| 938 |
return "graph"
|
| 939 |
|
| 940 |
-
monkeypatch.setattr(
|
| 941 |
|
| 942 |
sent = self._run_get("/graph?slug=langgraph&type=harness")
|
| 943 |
|
|
@@ -953,7 +1047,7 @@ class TestMonitorRoutesPreserveEntityType:
|
|
| 953 |
calls["mutations_enabled"] = mutations_enabled
|
| 954 |
return "wiki"
|
| 955 |
|
| 956 |
-
monkeypatch.setattr(
|
| 957 |
|
| 958 |
sent = self._run_get("/wiki/langgraph?type=harness")
|
| 959 |
|
|
@@ -974,7 +1068,7 @@ class TestMonitorRoutesPreserveEntityType:
|
|
| 974 |
calls["entity_type"] = entity_type
|
| 975 |
return {"center": "harness:langgraph", "nodes": [], "edges": []}
|
| 976 |
|
| 977 |
-
monkeypatch.setattr(
|
| 978 |
|
| 979 |
sent = self._run_get("/api/graph/langgraph.json?type=harness&hops=2&limit=55")
|
| 980 |
|
|
@@ -993,7 +1087,7 @@ class TestMonitorRoutesPreserveEntityType:
|
|
| 993 |
calls.append((args, kwargs))
|
| 994 |
return {"center": "skill:langgraph", "nodes": [], "edges": []}
|
| 995 |
|
| 996 |
-
monkeypatch.setattr(
|
| 997 |
|
| 998 |
sent = self._run_get("/api/graph/langgraph.json?type=bogus")
|
| 999 |
|
|
|
|
| 24 |
import json
|
| 25 |
import sys
|
| 26 |
from pathlib import Path
|
| 27 |
+
from typing import Any, cast
|
| 28 |
|
| 29 |
import networkx as nx
|
| 30 |
import pytest
|
| 31 |
|
| 32 |
sys.path.insert(0, str(Path(__file__).parents[1]))
|
| 33 |
|
| 34 |
+
from ctx.core import entity_types as _entity_types
|
| 35 |
+
from ctx.core.wiki.wiki_packs import write_wiki_base_pack
|
| 36 |
+
from ctx.monitor import testing as _mt
|
| 37 |
+
from ctx.monitor.services import wiki as _wiki_service
|
| 38 |
|
| 39 |
|
| 40 |
# ────────────────────────────────────────────────────────────────────
|
|
|
|
| 44 |
|
| 45 |
@pytest.fixture()
|
| 46 |
def wiki_3type(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
| 47 |
+
"""Build a minimal wiki and point monitor compat at it via ``_wiki_dir``."""
|
| 48 |
+
_wiki_service.reset_caches()
|
| 49 |
wiki = tmp_path / "skill-wiki"
|
| 50 |
for sub in ("skills", "agents", "harnesses"):
|
| 51 |
(wiki / "entities" / sub).mkdir(parents=True)
|
|
|
|
| 83 |
encoding="utf-8",
|
| 84 |
)
|
| 85 |
|
| 86 |
+
monkeypatch.setattr(_mt, "wiki_dir", lambda: wiki)
|
| 87 |
+
monkeypatch.setattr(_mt, "dashboard_graph_index_archives", lambda: [])
|
| 88 |
return wiki
|
| 89 |
|
| 90 |
|
|
|
|
| 95 |
|
| 96 |
class TestWikiStats:
|
| 97 |
def test_counts_include_mcps(self, wiki_3type):
|
| 98 |
+
s = _mt.wiki_stats()
|
| 99 |
+
direct = _wiki_service.wiki_stats(
|
| 100 |
+
wiki_3type,
|
| 101 |
+
_mt.dashboard_graph_index_path(),
|
| 102 |
+
index_matches_manifest=_mt.dashboard_index_matches_manifest,
|
| 103 |
+
graph_node_total=0,
|
| 104 |
+
)
|
| 105 |
assert s["skills"] == 2
|
| 106 |
assert s["agents"] == 1
|
| 107 |
assert s["mcps"] == 3
|
| 108 |
assert s["harnesses"] == 1
|
| 109 |
assert s["total"] == 7
|
| 110 |
+
assert direct == s
|
| 111 |
|
| 112 |
def test_mcps_sharded_dirs_scanned_recursively(self, wiki_3type):
|
| 113 |
"""MCPs live under entities/mcp-servers/<first-char>/<slug>.md —
|
| 114 |
the scan must walk the shard dirs, not just the top level."""
|
| 115 |
+
s = _mt.wiki_stats()
|
| 116 |
assert s["mcps"] == 3 # 2 under a/, 1 under p/
|
| 117 |
|
| 118 |
def test_no_mcp_dir_gracefully_zero(self, tmp_path, monkeypatch):
|
|
|
|
| 120 |
users who have only ingested skills."""
|
| 121 |
wiki = tmp_path / "wiki"
|
| 122 |
(wiki / "entities" / "skills").mkdir(parents=True)
|
| 123 |
+
monkeypatch.setattr(_mt, "wiki_dir", lambda: wiki)
|
| 124 |
+
s = _mt.wiki_stats()
|
| 125 |
assert s["mcps"] == 0
|
| 126 |
assert s["harnesses"] == 0
|
| 127 |
assert "mcps" in s # key present even at zero
|
|
|
|
| 139 |
"> Nodes: 102,697 | Edges: 2,900,910 | Communities: 52\n",
|
| 140 |
encoding="utf-8",
|
| 141 |
)
|
| 142 |
+
monkeypatch.setattr(_mt, "wiki_dir", lambda: wiki)
|
| 143 |
monkeypatch.setattr(
|
| 144 |
+
_mt,
|
| 145 |
+
"load_dashboard_graph",
|
| 146 |
lambda: (_ for _ in ()).throw(AssertionError("loaded graph.json")),
|
| 147 |
)
|
| 148 |
|
| 149 |
+
assert _mt.graph_stats() == {
|
| 150 |
"nodes": 102697,
|
| 151 |
"edges": 2900910,
|
| 152 |
"available": True,
|
|
|
|
| 160 |
|
| 161 |
class TestWikiIndexEntries:
|
| 162 |
def test_entries_include_mcp_servers(self, wiki_3type):
|
| 163 |
+
entries = _mt.wiki_index_entries()
|
| 164 |
types = {e["type"] for e in entries}
|
| 165 |
assert "mcp-server" in types
|
| 166 |
assert "harness" in types
|
|
|
|
| 168 |
assert "agent" in types
|
| 169 |
|
| 170 |
def test_mcp_slugs_surfaced_from_both_shards(self, wiki_3type):
|
| 171 |
+
entries = _mt.wiki_index_entries()
|
| 172 |
slugs = {e["slug"] for e in entries if e["type"] == "mcp-server"}
|
| 173 |
assert slugs == {"anthropic-python-sdk", "atlassian-cloud", "pulsemcp-meta"}
|
| 174 |
|
| 175 |
def test_wiki_entity_path_resolves_sharded_mcp_pages(self, wiki_3type):
|
| 176 |
+
assert _entity_types.normalize_entity_type("mcp") == "mcp-server"
|
| 177 |
+
assert _mt.DASHBOARD_ENTITY_SOURCES == _entity_types.entity_source_specs()
|
| 178 |
+
path = _mt.wiki_entity_path("anthropic-python-sdk")
|
| 179 |
assert path == (
|
| 180 |
wiki_3type / "entities" / "mcp-servers" / "a" / "anthropic-python-sdk.md"
|
| 181 |
)
|
| 182 |
|
| 183 |
def test_wiki_entity_path_resolves_harness_pages(self, wiki_3type):
|
| 184 |
+
path = _mt.wiki_entity_path("langgraph", entity_type="harness")
|
| 185 |
assert path == wiki_3type / "entities" / "harnesses" / "langgraph.md"
|
| 186 |
|
| 187 |
+
def test_wiki_pack_pages_override_physical_entity_pages(
|
| 188 |
+
self,
|
| 189 |
+
wiki_3type: Path,
|
| 190 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 191 |
+
) -> None:
|
| 192 |
+
_wiki_service.reset_caches()
|
| 193 |
+
monkeypatch.setattr(_mt, "render_entity_subgraph", lambda *_, **__: "")
|
| 194 |
+
(wiki_3type / "entities" / "skills" / "python-patterns.md").write_text(
|
| 195 |
+
"---\n"
|
| 196 |
+
"title: Stale Physical Page\n"
|
| 197 |
+
"type: skill\n"
|
| 198 |
+
"tags: [stale]\n"
|
| 199 |
+
"description: stale physical description\n"
|
| 200 |
+
"---\n"
|
| 201 |
+
"# Stale Physical Page\n",
|
| 202 |
+
encoding="utf-8",
|
| 203 |
+
)
|
| 204 |
+
write_wiki_base_pack(
|
| 205 |
+
pack_dir=wiki_3type / "wiki-packs" / "base-export-1",
|
| 206 |
+
pack_id="base-export-1",
|
| 207 |
+
base_export_id="export-1",
|
| 208 |
+
pages={
|
| 209 |
+
"entities/skills/python-patterns.md": (
|
| 210 |
+
"---\n"
|
| 211 |
+
"title: Fresh Pack Page\n"
|
| 212 |
+
"type: skill\n"
|
| 213 |
+
"tags: [pack, merged]\n"
|
| 214 |
+
"description: fresh pack description\n"
|
| 215 |
+
"---\n"
|
| 216 |
+
"# Fresh Pack Page\n\n"
|
| 217 |
+
"Merged wiki pack body.\n"
|
| 218 |
+
),
|
| 219 |
+
"entities/mcp-servers/g/github.md": (
|
| 220 |
+
"---\n"
|
| 221 |
+
"title: GitHub MCP\n"
|
| 222 |
+
"type: mcp-server\n"
|
| 223 |
+
"tags: [github, merged]\n"
|
| 224 |
+
"description: pack-only mcp\n"
|
| 225 |
+
"---\n"
|
| 226 |
+
"# GitHub MCP\n"
|
| 227 |
+
),
|
| 228 |
+
},
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
entries = _mt.wiki_index_entries(limit_per_type=None)
|
| 232 |
+
slugs = {entry["slug"] for entry in entries}
|
| 233 |
+
service_detail = _wiki_service.entity_detail(
|
| 234 |
+
wiki_3type,
|
| 235 |
+
"python-patterns",
|
| 236 |
+
entity_type="skill",
|
| 237 |
+
)
|
| 238 |
+
detail = _mt.wiki_entity_detail("python-patterns", entity_type="skill")
|
| 239 |
+
search = _mt.search_wiki_entities("merged body", entity_type="skill")
|
| 240 |
+
html = _mt.render_wiki_entity("python-patterns", entity_type="skill")
|
| 241 |
+
stats = _mt.wiki_stats()
|
| 242 |
+
|
| 243 |
+
assert slugs == {"python-patterns", "github"}
|
| 244 |
+
assert service_detail is not None
|
| 245 |
+
assert service_detail["frontmatter"]["title"] == "Fresh Pack Page"
|
| 246 |
+
assert "Merged wiki pack body" in service_detail["body"]
|
| 247 |
+
assert detail is not None
|
| 248 |
+
assert detail["frontmatter"]["title"] == "Fresh Pack Page"
|
| 249 |
+
assert "Merged wiki pack body" in detail["body"]
|
| 250 |
+
assert [row["slug"] for row in search] == ["python-patterns"]
|
| 251 |
+
assert "Fresh Pack Page" in html
|
| 252 |
+
assert "Stale Physical Page" not in html
|
| 253 |
+
assert stats == {
|
| 254 |
+
"skills": 1,
|
| 255 |
+
"agents": 0,
|
| 256 |
+
"mcps": 1,
|
| 257 |
+
"harnesses": 0,
|
| 258 |
+
"total": 2,
|
| 259 |
+
"split_known": True,
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
def test_wiki_search_indexes_tags_beyond_preview_limit(self, wiki_3type):
|
| 263 |
page = wiki_3type / "entities" / "skills" / "many-tags.md"
|
| 264 |
page.write_text(
|
|
|
|
| 270 |
encoding="utf-8",
|
| 271 |
)
|
| 272 |
|
| 273 |
+
entries = _mt.wiki_index_entries()
|
| 274 |
entry = next(e for e in entries if e["slug"] == "many-tags")
|
| 275 |
|
| 276 |
assert entry["tags"] == ["one", "two", "three", "four", "five", "six"]
|
| 277 |
assert "seventh" in entry["search_tags"]
|
| 278 |
|
| 279 |
def test_index_entries_can_sample_per_entity_type(self, wiki_3type):
|
| 280 |
+
entries = _mt.wiki_index_entries(limit_per_type=1)
|
| 281 |
counts: dict[str, int] = {}
|
| 282 |
for entry in entries:
|
| 283 |
counts[entry["type"]] = counts.get(entry["type"], 0) + 1
|
|
|
|
| 301 |
encoding="utf-8",
|
| 302 |
)
|
| 303 |
|
| 304 |
+
entries = _mt.wiki_index_entries(limit_per_type=1)
|
| 305 |
skill_entries = [entry for entry in entries if entry["type"] == "skill"]
|
| 306 |
|
| 307 |
assert [entry["slug"] for entry in skill_entries] == ["aaa-first"]
|
|
|
|
| 311 |
wiki_3type: Path,
|
| 312 |
monkeypatch: pytest.MonkeyPatch,
|
| 313 |
) -> None:
|
| 314 |
+
monkeypatch.setattr(_mt, "render_entity_subgraph", lambda *_, **__: "")
|
| 315 |
long_description = "x" * 160
|
| 316 |
long_body = "body-line\n" * 1400
|
| 317 |
(wiki_3type / "entities" / "skills" / "long-page.md").write_text(
|
|
|
|
| 323 |
encoding="utf-8",
|
| 324 |
)
|
| 325 |
|
| 326 |
+
html = _mt.render_wiki_entity("long-page", entity_type="skill")
|
| 327 |
|
| 328 |
assert "Body preview truncated at 12,000 characters." in html
|
| 329 |
assert "(truncated)" in html
|
|
|
|
| 333 |
def test_wiki_card_shows_mcp_count(self, wiki_3type, monkeypatch):
|
| 334 |
# Other dependencies of _render_home need shims that don't touch
|
| 335 |
# the real user dir. Empty manifests + empty audit log are fine.
|
| 336 |
+
monkeypatch.setattr(_mt, "read_manifest", lambda: {"load": [], "unload": []})
|
| 337 |
+
monkeypatch.setattr(_mt, "summarize_sessions", lambda: [])
|
| 338 |
+
monkeypatch.setattr(_mt, "grade_distribution", lambda: {})
|
| 339 |
+
monkeypatch.setattr(_mt, "graph_stats", lambda: {"nodes": 0, "edges": 0, "available": False})
|
| 340 |
+
monkeypatch.setattr(_mt, "audit_log_path", lambda: wiki_3type / "no-audit.log")
|
| 341 |
+
monkeypatch.setattr(_mt, "read_jsonl", lambda *a, **k: [])
|
| 342 |
+
|
| 343 |
+
html = _mt.render_home()
|
| 344 |
# The detail line inside the Wiki entities card must name MCPs.
|
| 345 |
assert "MCPs" in html
|
| 346 |
assert "2 skills" in html or "2 skill" in html
|
|
|
|
| 353 |
def test_agent_unload_and_mcp_actions_get_own_buckets(self, tmp_path, monkeypatch):
|
| 354 |
claude = tmp_path / ".claude"
|
| 355 |
claude.mkdir()
|
| 356 |
+
monkeypatch.setattr(_mt, "claude_dir", lambda: claude)
|
| 357 |
records = [
|
| 358 |
{
|
| 359 |
"ts": "2026-05-02T10:00:00Z",
|
|
|
|
| 396 |
encoding="utf-8",
|
| 397 |
)
|
| 398 |
|
| 399 |
+
session = _mt.summarize_sessions()[0]
|
| 400 |
|
| 401 |
assert session["agents_loaded"] == ["code-reviewer"]
|
| 402 |
assert session["skills_loaded"] == []
|
|
|
|
| 406 |
assert session["mcps_unloaded"] == ["anthropic-python-sdk"]
|
| 407 |
|
| 408 |
def test_sessions_index_renders_agent_and_mcp_columns(self, monkeypatch):
|
| 409 |
+
monkeypatch.setattr(_mt, "summarize_sessions", lambda: [{
|
| 410 |
"session_id": "S1",
|
| 411 |
"first_seen": "2026-05-02T10:00:00Z",
|
| 412 |
"last_seen": "2026-05-02T10:02:00Z",
|
|
|
|
| 419 |
"lifecycle_transitions": 0,
|
| 420 |
}])
|
| 421 |
|
| 422 |
+
html = _mt.render_sessions_index()
|
| 423 |
|
| 424 |
assert "Agents↓" in html
|
| 425 |
assert "MCPs↑" in html
|
|
|
|
| 434 |
|
| 435 |
class TestRenderWikiIndex3Type:
|
| 436 |
def test_mcp_server_checkbox_present(self, wiki_3type, monkeypatch):
|
| 437 |
+
monkeypatch.setattr(_mt, "all_sidecars", lambda: [])
|
| 438 |
+
html = _mt.render_wiki_index()
|
| 439 |
assert "value='mcp-server' checked" in html
|
| 440 |
assert "value='harness' checked" in html
|
| 441 |
# Count for the mcp-server bucket should render.
|
|
|
|
| 448 |
"---\ntype: skill\ntags: [one, two, three, four, five, six, seventh]\n---\n# many-tags\n",
|
| 449 |
encoding="utf-8",
|
| 450 |
)
|
| 451 |
+
monkeypatch.setattr(_mt, "all_sidecars", lambda: [])
|
| 452 |
|
| 453 |
+
html = _mt.render_wiki_index()
|
| 454 |
|
| 455 |
assert "data-tags='one two three four five six seventh'" in html
|
| 456 |
|
|
|
|
| 462 |
|
| 463 |
class TestRenderLoaded3Type:
|
| 464 |
def test_heading_names_all_three_types(self, monkeypatch):
|
| 465 |
+
monkeypatch.setattr(_mt, "read_manifest",
|
| 466 |
lambda: {"load": [], "unload": []})
|
| 467 |
+
html = _mt.render_loaded()
|
| 468 |
assert "skills, agents, MCPs & harnesses" in html or (
|
| 469 |
"skills, agents, MCPs & harnesses" in html
|
| 470 |
)
|
|
|
|
| 483 |
],
|
| 484 |
"unload": [],
|
| 485 |
}
|
| 486 |
+
monkeypatch.setattr(_mt, "read_manifest", lambda: manifest)
|
| 487 |
+
html = _mt.render_loaded()
|
| 488 |
# Four section headers render — one per type.
|
| 489 |
assert "<h3" in html
|
| 490 |
assert "Skills " in html or "Skills</h3" in html or "Skills " in html
|
|
|
|
| 509 |
],
|
| 510 |
"unload": [],
|
| 511 |
}
|
| 512 |
+
monkeypatch.setattr(_mt, "read_manifest", lambda: manifest)
|
| 513 |
+
html = _mt.render_loaded()
|
| 514 |
assert "data-etype='skill'" in html
|
| 515 |
assert "data-etype='agent'" in html
|
| 516 |
assert "data-etype='mcp-server'" in html
|
|
|
|
| 521 |
"""Pre-install_utils manifest entries had no entity_type field.
|
| 522 |
Those must default to skill (what the implicit contract was)
|
| 523 |
and still render in the Skills section without crashing."""
|
| 524 |
+
monkeypatch.setattr(_mt, "read_manifest",
|
| 525 |
lambda: {"load": [{"skill": "legacy"}], "unload": []})
|
| 526 |
+
html = _mt.render_loaded()
|
| 527 |
assert "legacy" in html
|
| 528 |
assert "data-etype='skill'" in html
|
| 529 |
|
|
|
|
| 539 |
},
|
| 540 |
],
|
| 541 |
}
|
| 542 |
+
monkeypatch.setattr(_mt, "read_manifest", lambda: manifest)
|
| 543 |
+
html = _mt.render_loaded()
|
| 544 |
assert "data-slug='code-reviewer' data-etype='agent'" in html
|
| 545 |
assert (
|
| 546 |
"data-slug='anthropic-python-sdk' data-etype='mcp-server'"
|
|
|
|
| 567 |
from ctx.adapters.claude_code.install import skill_unload
|
| 568 |
monkeypatch.setattr(skill_unload, "unload_from_session",
|
| 569 |
fake_unload_from_session)
|
| 570 |
+
ok, msg = _mt.perform_unload("python-patterns", entity_type="skill")
|
| 571 |
assert ok
|
| 572 |
assert calls["slugs"] == ["python-patterns"]
|
| 573 |
assert calls["entity_type"] == "skill"
|
|
|
|
| 593 |
from ctx.adapters.claude_code.install import mcp_install
|
| 594 |
monkeypatch.setattr(mcp_install, "uninstall_mcp", fake_uninstall)
|
| 595 |
|
| 596 |
+
ok, msg = _mt.perform_unload("anthropic-python-sdk",
|
| 597 |
entity_type="mcp-server")
|
| 598 |
assert ok
|
| 599 |
assert calls["slug"] == "anthropic-python-sdk"
|
|
|
|
| 606 |
):
|
| 607 |
claude = tmp_path / ".claude"
|
| 608 |
claude.mkdir()
|
| 609 |
+
monkeypatch.setattr(_mt, "claude_dir", lambda: claude)
|
| 610 |
(claude / "skill-manifest.json").write_text(
|
| 611 |
json.dumps({
|
| 612 |
"load": [{
|
|
|
|
| 620 |
encoding="utf-8",
|
| 621 |
)
|
| 622 |
|
| 623 |
+
ok, msg = _mt.perform_unload("code-reviewer", entity_type="agent")
|
| 624 |
|
| 625 |
assert ok, msg
|
| 626 |
manifest = json.loads(
|
|
|
|
| 647 |
message="claude mcp remove failed"),
|
| 648 |
)
|
| 649 |
|
| 650 |
+
ok, msg = _mt.perform_unload("bad-mcp", entity_type="mcp-server")
|
| 651 |
assert not ok
|
| 652 |
assert "claude mcp remove failed" in msg
|
| 653 |
|
|
|
|
| 662 |
|
| 663 |
claude = tmp_path / ".claude"
|
| 664 |
claude.mkdir()
|
| 665 |
+
monkeypatch.setattr(_mt, "claude_dir", lambda: claude)
|
| 666 |
from ctx.adapters.claude_code.install import mcp_install
|
| 667 |
monkeypatch.setattr(
|
| 668 |
mcp_install,
|
|
|
|
| 670 |
lambda slug, **kw: _FakeResult(slug=slug, status="uninstalled"),
|
| 671 |
)
|
| 672 |
|
| 673 |
+
ok, msg = _mt.perform_unload("anthropic-python-sdk", "mcp-server")
|
| 674 |
|
| 675 |
assert ok, msg
|
| 676 |
audit = json.loads((claude / "ctx-audit.jsonl").read_text(encoding="utf-8"))
|
|
|
|
| 680 |
assert audit["meta"]["action"] == "unloaded"
|
| 681 |
|
| 682 |
def test_invalid_slug_rejected(self):
|
| 683 |
+
ok, msg = _mt.perform_unload("../etc/passwd", entity_type="skill")
|
| 684 |
assert not ok
|
| 685 |
assert "invalid slug" in msg
|
| 686 |
|
|
|
|
| 692 |
|
| 693 |
monkeypatch.setattr(skill_unload, "unload_from_session", fail_if_called)
|
| 694 |
|
| 695 |
+
ok, msg = _mt.perform_unload("python-patterns", entity_type="weird")
|
| 696 |
|
| 697 |
assert not ok
|
| 698 |
assert "unsupported entity_type" in msg
|
|
|
|
| 701 |
class TestRenderSidecarDetail3Type:
|
| 702 |
def test_sidecar_timeline_filters_duplicate_slug_by_entity_type(self, monkeypatch):
|
| 703 |
monkeypatch.setattr(
|
| 704 |
+
_mt,
|
| 705 |
+
"load_sidecar",
|
| 706 |
lambda slug, entity_type=None: {
|
| 707 |
"slug": slug,
|
| 708 |
"subject_type": "harness",
|
|
|
|
| 711 |
},
|
| 712 |
)
|
| 713 |
monkeypatch.setattr(
|
| 714 |
+
_mt,
|
| 715 |
+
"read_jsonl",
|
| 716 |
lambda *args, **kwargs: [
|
| 717 |
{
|
| 718 |
"ts": "t1",
|
|
|
|
| 738 |
],
|
| 739 |
)
|
| 740 |
|
| 741 |
+
html = _mt.render_skill_detail("langgraph", entity_type="harness")
|
| 742 |
|
| 743 |
assert "harness.installed" in html
|
| 744 |
assert "Audit timeline (1 entries)" in html
|
|
|
|
| 766 |
from ctx.adapters.claude_code.install import skill_install
|
| 767 |
monkeypatch.setattr(skill_install, "install_skill", fake_install)
|
| 768 |
|
| 769 |
+
ok, msg = _mt.perform_load("python-patterns", entity_type="skill")
|
| 770 |
|
| 771 |
assert ok
|
| 772 |
assert msg == "ok"
|
| 773 |
assert calls["slug"] == "python-patterns"
|
| 774 |
+
assert calls["kw"]["wiki_dir"] == _mt.wiki_dir()
|
| 775 |
|
| 776 |
def test_agent_type_calls_agent_install(self, monkeypatch):
|
| 777 |
from dataclasses import dataclass
|
|
|
|
| 792 |
from ctx.adapters.claude_code.install import agent_install
|
| 793 |
monkeypatch.setattr(agent_install, "install_agent", fake_install)
|
| 794 |
|
| 795 |
+
ok, msg = _mt.perform_load("code-reviewer", entity_type="agent")
|
| 796 |
|
| 797 |
assert ok
|
| 798 |
assert msg == "ok"
|
| 799 |
assert calls["slug"] == "code-reviewer"
|
| 800 |
+
assert calls["kw"]["agents_dir"] == _mt.claude_dir() / "agents"
|
| 801 |
|
| 802 |
def test_mcp_type_calls_mcp_install_auto(self, monkeypatch):
|
| 803 |
from dataclasses import dataclass
|
|
|
|
| 818 |
from ctx.adapters.claude_code.install import mcp_install
|
| 819 |
monkeypatch.setattr(mcp_install, "install_mcp", fake_install)
|
| 820 |
|
| 821 |
+
ok, msg = _mt.perform_load("anthropic-python-sdk",
|
| 822 |
entity_type="mcp-server")
|
| 823 |
|
| 824 |
assert ok
|
|
|
|
| 845 |
from ctx.adapters.claude_code.install import mcp_install
|
| 846 |
monkeypatch.setattr(mcp_install, "install_mcp", fake_install)
|
| 847 |
|
| 848 |
+
ok, msg = _mt.perform_load(
|
| 849 |
"anthropic-python-sdk",
|
| 850 |
entity_type="mcp-server",
|
| 851 |
command="npx -y @anthropic/sdk",
|
|
|
|
| 867 |
|
| 868 |
claude = tmp_path / ".claude"
|
| 869 |
claude.mkdir()
|
| 870 |
+
monkeypatch.setattr(_mt, "claude_dir", lambda: claude)
|
| 871 |
from ctx.adapters.claude_code.install import mcp_install
|
| 872 |
monkeypatch.setattr(
|
| 873 |
mcp_install,
|
|
|
|
| 875 |
lambda slug, **kw: _FakeResult(slug=slug, status="installed"),
|
| 876 |
)
|
| 877 |
|
| 878 |
+
ok, msg = _mt.perform_load("anthropic-python-sdk", "mcp-server")
|
| 879 |
|
| 880 |
assert ok, msg
|
| 881 |
audit = json.loads((claude / "ctx-audit.jsonl").read_text(encoding="utf-8"))
|
|
|
|
| 884 |
assert audit["meta"]["action"] == "loaded"
|
| 885 |
|
| 886 |
def test_harness_type_hands_off_to_cli(self):
|
| 887 |
+
ok, msg = _mt.perform_load("langgraph", entity_type="harness")
|
| 888 |
assert not ok
|
| 889 |
assert "ctx-harness-install langgraph --dry-run" in msg
|
| 890 |
|
|
|
|
| 896 |
|
| 897 |
class TestRenderGraphSidebar:
|
| 898 |
def test_sidebar_type_checkboxes_include_mcp_server(self, monkeypatch):
|
| 899 |
+
monkeypatch.setattr(_mt, "graph_stats",
|
| 900 |
lambda: {"nodes": 10, "edges": 20, "available": True})
|
| 901 |
+
monkeypatch.setattr(_mt, "top_degree_seeds", lambda **_: [])
|
| 902 |
+
html = _mt.render_graph()
|
| 903 |
# Four type checkboxes: skill, agent, mcp-server, harness.
|
| 904 |
assert "class='graph-type-filter' value='skill'" in html
|
| 905 |
assert "class='graph-type-filter' value='agent'" in html
|
|
|
|
| 907 |
assert "class='graph-type-filter' value='harness'" in html
|
| 908 |
|
| 909 |
def test_sidebar_has_tag_filter(self, monkeypatch):
|
| 910 |
+
monkeypatch.setattr(_mt, "graph_stats",
|
| 911 |
lambda: {"nodes": 0, "edges": 0, "available": False})
|
| 912 |
+
monkeypatch.setattr(_mt, "top_degree_seeds", lambda **_: [])
|
| 913 |
+
html = _mt.render_graph()
|
| 914 |
assert "id='tag-filter'" in html
|
| 915 |
assert "filter_tokens" in html
|
| 916 |
assert "isFocus || !tagQ" in html
|
| 917 |
|
| 918 |
def test_graph_list_styles_mcp_and_harness_nodes_distinctly(self, monkeypatch):
|
| 919 |
"""The graph list view shows four types; each must be visually distinct."""
|
| 920 |
+
monkeypatch.setattr(_mt, "graph_stats",
|
| 921 |
lambda: {"nodes": 0, "edges": 0, "available": False})
|
| 922 |
+
monkeypatch.setattr(_mt, "top_degree_seeds", lambda **_: [])
|
| 923 |
+
html = _mt.render_graph()
|
| 924 |
assert ".entity-type-skill" in html
|
| 925 |
assert ".entity-type-agent" in html
|
| 926 |
assert ".entity-type-mcp-server" in html
|
|
|
|
| 931 |
)
|
| 932 |
|
| 933 |
def test_graph_filters_fallback_rows_and_connected_edges(self, monkeypatch):
|
| 934 |
+
monkeypatch.setattr(_mt, "graph_stats",
|
| 935 |
lambda: {"nodes": 0, "edges": 0, "available": False})
|
| 936 |
+
monkeypatch.setattr(_mt, "top_degree_seeds", lambda **_: [])
|
| 937 |
+
html = _mt.render_graph()
|
| 938 |
|
| 939 |
assert "document.querySelectorAll('[data-testid=\"graph-fallback-node\"]')" in html
|
| 940 |
assert "n.style.display = hidden ? 'none' : 'flex'" in html
|
|
|
|
| 944 |
def test_tap_handler_strips_mcp_server_prefix(self, monkeypatch):
|
| 945 |
"""Clicking an MCP node must route to /wiki/<slug> — the
|
| 946 |
prefix-stripping regex has to know all four types."""
|
| 947 |
+
monkeypatch.setattr(_mt, "graph_stats",
|
| 948 |
lambda: {"nodes": 0, "edges": 0, "available": False})
|
| 949 |
+
monkeypatch.setattr(_mt, "top_degree_seeds", lambda **_: [])
|
| 950 |
+
html = _mt.render_graph()
|
| 951 |
# Regex should include mcp-server and harness in the prefix alternation.
|
| 952 |
assert "(skill|agent|mcp-server|harness)" in html
|
| 953 |
|
|
|
|
| 957 |
graph.add_node("harness:langgraph", label="langgraph", type="harness", tags=["agent"])
|
| 958 |
graph.add_node("skill:agent-patterns", label="agent-patterns", type="skill", tags=["agent"])
|
| 959 |
graph.add_edge("harness:langgraph", "skill:agent-patterns", weight=2, shared_tags=["agent"])
|
| 960 |
+
monkeypatch.setattr(_mt, "load_dashboard_graph", lambda: graph)
|
| 961 |
|
| 962 |
+
out = _mt.graph_neighborhood("langgraph", entity_type="harness")
|
| 963 |
|
| 964 |
assert out["center"] == "harness:langgraph"
|
| 965 |
assert any(n["data"]["type"] == "harness" for n in out["nodes"])
|
|
|
|
| 971 |
graph.add_node("skill:c", label="c", type="skill", tags=[])
|
| 972 |
graph.add_edge("skill:a", "skill:b", weight=2)
|
| 973 |
graph.add_edge("skill:b", "skill:c", weight=1)
|
| 974 |
+
monkeypatch.setattr(_mt, "load_dashboard_graph", lambda: graph)
|
| 975 |
|
| 976 |
+
out = _mt.graph_neighborhood("a", hops=2, entity_type="skill")
|
| 977 |
|
| 978 |
edge_ids = [edge["data"]["id"] for edge in out["edges"]]
|
| 979 |
assert len(edge_ids) == len(set(edge_ids))
|
|
|
|
| 987 |
graph.add_node("skill:a", label="a", type="skill", tags=[])
|
| 988 |
graph.add_node("skill:b", label="b", type="skill", tags=[])
|
| 989 |
graph.add_edge("skill:a", "skill:b", weight=1, shared_tags=["security"])
|
| 990 |
+
monkeypatch.setattr(_mt, "load_dashboard_graph", lambda: graph)
|
| 991 |
|
| 992 |
+
out = _mt.graph_neighborhood("a", entity_type="skill")
|
| 993 |
|
| 994 |
by_id = {node["data"]["id"]: node["data"] for node in out["nodes"]}
|
| 995 |
assert "security" in by_id["skill:a"]["filter_tokens"]
|
|
|
|
| 1011 |
handler._send_500 = lambda exc: sent.setdefault("500", exc)
|
| 1012 |
handler._api_reads_enabled = lambda: True
|
| 1013 |
handler._mutations_enabled = lambda: True
|
| 1014 |
+
monitor_handler = cast(Any, _mt.MonitorHandler)
|
| 1015 |
+
handler._handle_get_route = monitor_handler._handle_get_route.__get__(
|
| 1016 |
+
handler,
|
| 1017 |
+
type(handler),
|
| 1018 |
+
)
|
| 1019 |
if html_fn is not None:
|
| 1020 |
handler._send_html = html_fn
|
| 1021 |
if json_fn is not None:
|
| 1022 |
handler._send_json = json_fn
|
| 1023 |
+
monitor_handler.do_GET(handler)
|
| 1024 |
return sent
|
| 1025 |
|
| 1026 |
def test_graph_route_passes_type_query(self, monkeypatch):
|
|
|
|
| 1031 |
calls["focus_type"] = focus_type
|
| 1032 |
return "graph"
|
| 1033 |
|
| 1034 |
+
monkeypatch.setattr(_mt, "render_graph", fake_render_graph)
|
| 1035 |
|
| 1036 |
sent = self._run_get("/graph?slug=langgraph&type=harness")
|
| 1037 |
|
|
|
|
| 1047 |
calls["mutations_enabled"] = mutations_enabled
|
| 1048 |
return "wiki"
|
| 1049 |
|
| 1050 |
+
monkeypatch.setattr(_mt, "render_wiki_entity", fake_render_wiki_entity)
|
| 1051 |
|
| 1052 |
sent = self._run_get("/wiki/langgraph?type=harness")
|
| 1053 |
|
|
|
|
| 1068 |
calls["entity_type"] = entity_type
|
| 1069 |
return {"center": "harness:langgraph", "nodes": [], "edges": []}
|
| 1070 |
|
| 1071 |
+
monkeypatch.setattr(_mt, "graph_neighborhood", fake_graph_neighborhood)
|
| 1072 |
|
| 1073 |
sent = self._run_get("/api/graph/langgraph.json?type=harness&hops=2&limit=55")
|
| 1074 |
|
|
|
|
| 1087 |
calls.append((args, kwargs))
|
| 1088 |
return {"center": "skill:langgraph", "nodes": [], "edges": []}
|
| 1089 |
|
| 1090 |
+
monkeypatch.setattr(_mt, "graph_neighborhood", fake_graph_neighborhood)
|
| 1091 |
|
| 1092 |
sent = self._run_get("/api/graph/langgraph.json?type=bogus")
|
| 1093 |
|
src/tests/test_ctx_monitor_browser.py
CHANGED
|
@@ -13,7 +13,9 @@ from typing import Any, Iterator
|
|
| 13 |
import networkx as nx
|
| 14 |
import pytest
|
| 15 |
|
| 16 |
-
import
|
|
|
|
|
|
|
| 17 |
|
| 18 |
playwright_sync: Any = pytest.importorskip("playwright.sync_api")
|
| 19 |
|
|
@@ -38,8 +40,10 @@ class MonitorHarness:
|
|
| 38 |
def fake_claude(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
| 39 |
claude = tmp_path / ".claude"
|
| 40 |
(claude / "skill-quality").mkdir(parents=True)
|
| 41 |
-
monkeypatch.setattr(
|
| 42 |
-
monkeypatch.setattr(
|
|
|
|
|
|
|
| 43 |
return claude
|
| 44 |
|
| 45 |
|
|
@@ -64,16 +68,16 @@ def _start_monitor(
|
|
| 64 |
*,
|
| 65 |
fake_load: bool,
|
| 66 |
) -> MonitorHarness:
|
| 67 |
-
monkeypatch.setattr(
|
| 68 |
calls: list[tuple[str, str]] = []
|
| 69 |
if fake_load:
|
| 70 |
def perform_load(slug: str, entity_type: str = "skill") -> tuple[bool, str]:
|
| 71 |
calls.append((slug, entity_type))
|
| 72 |
return True, "loaded"
|
| 73 |
|
| 74 |
-
monkeypatch.setattr(
|
| 75 |
|
| 76 |
-
server =
|
| 77 |
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
| 78 |
thread.start()
|
| 79 |
port = int(server.server_port)
|
|
@@ -98,6 +102,20 @@ def _write_wiki_entity(root: Path, entity_type: str, slug: str, body: str) -> No
|
|
| 98 |
path.write_text(body, encoding="utf-8")
|
| 99 |
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
def _wait_for_browser_state(page: Any, expression: str, *, timeout: float = 5.0) -> None:
|
| 102 |
deadline = time.monotonic() + timeout
|
| 103 |
while time.monotonic() < deadline:
|
|
@@ -112,6 +130,7 @@ def test_graph_page_uses_builtin_svg_renderer(
|
|
| 112 |
monkeypatch: pytest.MonkeyPatch,
|
| 113 |
page: Any,
|
| 114 |
) -> None:
|
|
|
|
| 115 |
G = nx.Graph()
|
| 116 |
G.add_node("skill:python-patterns", label="python-patterns", type="skill", tags=["python"])
|
| 117 |
G.add_node(
|
|
@@ -119,9 +138,23 @@ def test_graph_page_uses_builtin_svg_renderer(
|
|
| 119 |
label="code-reviewer",
|
| 120 |
type="agent",
|
| 121 |
tags=["review"],
|
| 122 |
-
quality_score=
|
| 123 |
usage_score=0.8,
|
| 124 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
G.add_node(
|
| 126 |
"mcp-server:github-mcp-server",
|
| 127 |
label="github-mcp-server",
|
|
@@ -131,10 +164,12 @@ def test_graph_page_uses_builtin_svg_renderer(
|
|
| 131 |
usage_score=0.0,
|
| 132 |
)
|
| 133 |
G.add_node("harness:langgraph", label="langgraph", type="harness", tags=["agent"])
|
| 134 |
-
G.add_edge("skill:python-patterns", "agent:code-reviewer", weight=0.9, shared_tags=["review"])
|
| 135 |
G.add_edge("skill:python-patterns", "mcp-server:github-mcp-server", weight=0.8, shared_tags=["github"])
|
| 136 |
G.add_edge("skill:python-patterns", "harness:langgraph", weight=0.7, shared_tags=["agent"])
|
| 137 |
-
|
|
|
|
|
|
|
| 138 |
_write_wiki_entity(fake_claude, "skill", "python-patterns", "# python-patterns\n")
|
| 139 |
_write_wiki_entity(fake_claude, "agent", "code-reviewer", "# code-reviewer\n")
|
| 140 |
|
|
@@ -142,25 +177,237 @@ def test_graph_page_uses_builtin_svg_renderer(
|
|
| 142 |
try:
|
| 143 |
page.goto(f"{harness.base_url}/graph?slug=python-patterns&type=skill")
|
| 144 |
page.wait_for_selector("[data-testid='graph-renderer']", timeout=5000)
|
| 145 |
-
assert "
|
| 146 |
-
assert page.locator("[data-testid='graph-svg-node']").count() ==
|
| 147 |
-
assert page.locator("[data-testid='graph-fallback-node']").count() ==
|
|
|
|
| 148 |
assert "Graph renderer unavailable" not in page.locator("#cy").inner_text()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
reviewer_radius = float(page.locator(
|
| 150 |
"[data-3d-node-id='agent:code-reviewer'] [data-testid='graph-svg-node']",
|
| 151 |
-
).get_attribute("
|
| 152 |
mcp_radius = float(page.locator(
|
| 153 |
"[data-3d-node-id='mcp-server:github-mcp-server'] [data-testid='graph-svg-node']",
|
| 154 |
-
).get_attribute("
|
| 155 |
assert reviewer_radius > mcp_radius
|
| 156 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
page.fill("#tag-filter", "review")
|
| 158 |
_wait_for_browser_state(
|
| 159 |
page,
|
| 160 |
"() => document.getElementById('graph-match-count').textContent === '2 visible'",
|
| 161 |
timeout=5.0,
|
| 162 |
)
|
| 163 |
-
page.locator("[data-testid='graph-
|
| 164 |
page.wait_for_url("**/wiki/code-reviewer?type=agent", timeout=5000)
|
| 165 |
assert "code-reviewer" in page.locator("h1").inner_text()
|
| 166 |
finally:
|
|
@@ -187,10 +434,10 @@ def test_docs_page_search_jumps_to_cross_tab_result(
|
|
| 187 |
"body": "# Graph Guide\n\n## Runtime Graph\n\nSearch the runtime graph.\n",
|
| 188 |
},
|
| 189 |
]
|
| 190 |
-
monkeypatch.setattr(
|
| 191 |
monkeypatch.setattr(
|
| 192 |
-
|
| 193 |
-
"
|
| 194 |
lambda _entries: [
|
| 195 |
{"label": "Home", "slug": "home", "pages": [entries[0]]},
|
| 196 |
{"label": "Repo", "slug": "repo", "pages": [entries[1]]},
|
|
@@ -269,6 +516,213 @@ def test_wiki_page_autocomplete_and_type_filters_update_visible_tiles(
|
|
| 269 |
harness.close()
|
| 270 |
|
| 271 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
def test_events_page_shows_backlog_and_appends_live_events(
|
| 273 |
fake_claude: Path,
|
| 274 |
monkeypatch: pytest.MonkeyPatch,
|
|
|
|
| 13 |
import networkx as nx
|
| 14 |
import pytest
|
| 15 |
|
| 16 |
+
from ctx.monitor import testing as mt
|
| 17 |
+
from ctx.monitor.services import kpi as kpi_service
|
| 18 |
+
from ctx.monitor.services import sidecars as sidecar_service
|
| 19 |
|
| 20 |
playwright_sync: Any = pytest.importorskip("playwright.sync_api")
|
| 21 |
|
|
|
|
| 40 |
def fake_claude(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
| 41 |
claude = tmp_path / ".claude"
|
| 42 |
(claude / "skill-quality").mkdir(parents=True)
|
| 43 |
+
monkeypatch.setattr(mt, "claude_dir", lambda: claude)
|
| 44 |
+
monkeypatch.setattr(mt, "dashboard_graph_index_archives", lambda: [])
|
| 45 |
+
sidecar_service.reset_caches()
|
| 46 |
+
kpi_service.reset_cache()
|
| 47 |
return claude
|
| 48 |
|
| 49 |
|
|
|
|
| 68 |
*,
|
| 69 |
fake_load: bool,
|
| 70 |
) -> MonitorHarness:
|
| 71 |
+
monkeypatch.setattr(mt, "MONITOR_TOKEN", "browser-token")
|
| 72 |
calls: list[tuple[str, str]] = []
|
| 73 |
if fake_load:
|
| 74 |
def perform_load(slug: str, entity_type: str = "skill") -> tuple[bool, str]:
|
| 75 |
calls.append((slug, entity_type))
|
| 76 |
return True, "loaded"
|
| 77 |
|
| 78 |
+
monkeypatch.setattr(mt, "perform_load", perform_load)
|
| 79 |
|
| 80 |
+
server = mt.make_monitor_server("127.0.0.1", 0)
|
| 81 |
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
| 82 |
thread.start()
|
| 83 |
port = int(server.server_port)
|
|
|
|
| 102 |
path.write_text(body, encoding="utf-8")
|
| 103 |
|
| 104 |
|
| 105 |
+
def _write_quality_sidecar(root: Path, slug: str, body: dict[str, Any]) -> None:
|
| 106 |
+
path = root / "skill-quality" / f"{slug}.json"
|
| 107 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 108 |
+
path.write_text(json.dumps(body), encoding="utf-8")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _write_runtime_events(path: Path, records: list[dict[str, Any]]) -> None:
|
| 112 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 113 |
+
path.write_text(
|
| 114 |
+
"\n".join(json.dumps(record) for record in records) + "\n",
|
| 115 |
+
encoding="utf-8",
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
def _wait_for_browser_state(page: Any, expression: str, *, timeout: float = 5.0) -> None:
|
| 120 |
deadline = time.monotonic() + timeout
|
| 121 |
while time.monotonic() < deadline:
|
|
|
|
| 130 |
monkeypatch: pytest.MonkeyPatch,
|
| 131 |
page: Any,
|
| 132 |
) -> None:
|
| 133 |
+
monkeypatch.setattr(mt, "graph_match_default_min_percent", lambda: 3)
|
| 134 |
G = nx.Graph()
|
| 135 |
G.add_node("skill:python-patterns", label="python-patterns", type="skill", tags=["python"])
|
| 136 |
G.add_node(
|
|
|
|
| 138 |
label="code-reviewer",
|
| 139 |
type="agent",
|
| 140 |
tags=["review"],
|
| 141 |
+
quality_score=18.0,
|
| 142 |
usage_score=0.8,
|
| 143 |
)
|
| 144 |
+
G.add_node(
|
| 145 |
+
"skill:weak-graph-link",
|
| 146 |
+
label="weak-graph-link",
|
| 147 |
+
type="skill",
|
| 148 |
+
tags=["noise"],
|
| 149 |
+
quality_score=0.2,
|
| 150 |
+
)
|
| 151 |
+
G.add_node(
|
| 152 |
+
"skill:medium-graph-link",
|
| 153 |
+
label="medium-graph-link",
|
| 154 |
+
type="skill",
|
| 155 |
+
tags=["noise"],
|
| 156 |
+
quality_score=0.2,
|
| 157 |
+
)
|
| 158 |
G.add_node(
|
| 159 |
"mcp-server:github-mcp-server",
|
| 160 |
label="github-mcp-server",
|
|
|
|
| 164 |
usage_score=0.0,
|
| 165 |
)
|
| 166 |
G.add_node("harness:langgraph", label="langgraph", type="harness", tags=["agent"])
|
| 167 |
+
G.add_edge("skill:python-patterns", "agent:code-reviewer", weight=0.9, shared_tags=["review"], tag_sim=0.3333)
|
| 168 |
G.add_edge("skill:python-patterns", "mcp-server:github-mcp-server", weight=0.8, shared_tags=["github"])
|
| 169 |
G.add_edge("skill:python-patterns", "harness:langgraph", weight=0.7, shared_tags=["agent"])
|
| 170 |
+
G.add_edge("skill:python-patterns", "skill:medium-graph-link", weight=0.43, tag_sim=0.0)
|
| 171 |
+
G.add_edge("agent:code-reviewer", "skill:weak-graph-link", weight=0.05)
|
| 172 |
+
monkeypatch.setattr(mt, "load_dashboard_graph", lambda: G)
|
| 173 |
_write_wiki_entity(fake_claude, "skill", "python-patterns", "# python-patterns\n")
|
| 174 |
_write_wiki_entity(fake_claude, "agent", "code-reviewer", "# code-reviewer\n")
|
| 175 |
|
|
|
|
| 177 |
try:
|
| 178 |
page.goto(f"{harness.base_url}/graph?slug=python-patterns&type=skill")
|
| 179 |
page.wait_for_selector("[data-testid='graph-renderer']", timeout=5000)
|
| 180 |
+
assert "5 nodes" in page.locator("#msg").inner_text()
|
| 181 |
+
assert page.locator("[data-testid='graph-svg-node']").count() == 5
|
| 182 |
+
assert page.locator("[data-testid='graph-fallback-node']").count() == 0
|
| 183 |
+
assert page.locator("[data-testid='graph-list']").evaluate("node => node.hidden")
|
| 184 |
assert "Graph renderer unavailable" not in page.locator("#cy").inner_text()
|
| 185 |
+
resize_handle = page.locator("[data-testid='graph-inspector-resize']")
|
| 186 |
+
assert resize_handle.count() == 1
|
| 187 |
+
assert page.locator("[data-testid='graph-node-detail']").evaluate(
|
| 188 |
+
"node => getComputedStyle(node).overflowY",
|
| 189 |
+
) == "auto"
|
| 190 |
+
assert page.locator("[data-testid='graph-edge-detail']").evaluate(
|
| 191 |
+
"node => node.parentElement?.getAttribute('data-testid')",
|
| 192 |
+
) == "graph-node-detail"
|
| 193 |
+
before_resize = page.locator(".graph-inspector-grid").bounding_box()
|
| 194 |
+
assert before_resize is not None
|
| 195 |
+
node_detail_box = page.locator("[data-testid='graph-node-detail']").bounding_box()
|
| 196 |
+
assert node_detail_box is not None
|
| 197 |
+
grid_padding = page.locator(".graph-inspector-grid").evaluate(
|
| 198 |
+
"node => parseFloat(getComputedStyle(node).paddingLeft) + parseFloat(getComputedStyle(node).paddingRight)",
|
| 199 |
+
)
|
| 200 |
+
assert abs(node_detail_box["width"] - (before_resize["width"] - grid_padding)) < 4
|
| 201 |
+
resize_handle.focus()
|
| 202 |
+
page.keyboard.press("ArrowUp")
|
| 203 |
+
_wait_for_browser_state(
|
| 204 |
+
page,
|
| 205 |
+
f"() => document.querySelector('.graph-inspector-grid')"
|
| 206 |
+
f"?.getBoundingClientRect().height > {before_resize['height'] + 10}",
|
| 207 |
+
timeout=5.0,
|
| 208 |
+
)
|
| 209 |
+
after_resize = page.locator(".graph-inspector-grid").bounding_box()
|
| 210 |
+
assert after_resize is not None
|
| 211 |
+
assert after_resize["height"] > before_resize["height"]
|
| 212 |
+
skill_shape = page.locator(
|
| 213 |
+
"[data-3d-node-id='skill:python-patterns'] [data-testid='graph-svg-node']",
|
| 214 |
+
)
|
| 215 |
+
agent_shape = page.locator(
|
| 216 |
+
"[data-3d-node-id='agent:code-reviewer'] [data-testid='graph-svg-node']",
|
| 217 |
+
)
|
| 218 |
+
mcp_shape = page.locator(
|
| 219 |
+
"[data-3d-node-id='mcp-server:github-mcp-server'] [data-testid='graph-svg-node']",
|
| 220 |
+
)
|
| 221 |
+
assert skill_shape.evaluate("node => node.tagName.toLowerCase()") == "circle"
|
| 222 |
+
assert agent_shape.evaluate("node => node.tagName.toLowerCase()") == "polygon"
|
| 223 |
+
assert mcp_shape.evaluate("node => node.tagName.toLowerCase()") == "rect"
|
| 224 |
+
assert skill_shape.get_attribute("data-node-shape") == "skill"
|
| 225 |
+
assert agent_shape.get_attribute("data-node-shape") == "agent"
|
| 226 |
+
assert mcp_shape.get_attribute("data-node-shape") == "mcp-server"
|
| 227 |
+
|
| 228 |
+
assert page.locator("[data-testid='match-range-control']").count() == 1
|
| 229 |
+
assert page.locator("#match-histogram .graph-match-bar").count() == 10
|
| 230 |
+
assert page.locator("#match-filter-min").get_attribute("max") == "100"
|
| 231 |
+
assert page.locator("#match-filter-max").get_attribute("max") == "100"
|
| 232 |
+
assert page.locator("#match-filter-min").input_value() == "3"
|
| 233 |
+
assert page.locator("#match-filter-min-value").inner_text() == "3%"
|
| 234 |
+
assert page.locator("#match-filter-max").input_value() == "100"
|
| 235 |
+
assert page.locator("#match-filter-max-value").inner_text() == "100%"
|
| 236 |
+
page.locator("#match-filter-min").evaluate(
|
| 237 |
+
"node => { node.value = '50'; node.dispatchEvent(new Event('input', {bubbles: true})); }",
|
| 238 |
+
)
|
| 239 |
+
_wait_for_browser_state(
|
| 240 |
+
page,
|
| 241 |
+
"() => document.getElementById('match-filter-min-value').textContent === '50%'",
|
| 242 |
+
timeout=5.0,
|
| 243 |
+
)
|
| 244 |
+
_wait_for_browser_state(
|
| 245 |
+
page,
|
| 246 |
+
"() => document.getElementById('graph-match-count').textContent === '4 visible'",
|
| 247 |
+
timeout=5.0,
|
| 248 |
+
)
|
| 249 |
+
assert page.locator("#match-histogram .graph-match-bar.active").count() >= 1
|
| 250 |
+
page.locator("#match-histogram [data-match-bin-min='70']").click()
|
| 251 |
+
_wait_for_browser_state(
|
| 252 |
+
page,
|
| 253 |
+
"() => document.getElementById('match-filter-min-value').textContent === '70%'",
|
| 254 |
+
timeout=5.0,
|
| 255 |
+
)
|
| 256 |
+
_wait_for_browser_state(
|
| 257 |
+
page,
|
| 258 |
+
"() => document.getElementById('match-filter-max-value').textContent === '79%'",
|
| 259 |
+
timeout=5.0,
|
| 260 |
+
)
|
| 261 |
+
_wait_for_browser_state(
|
| 262 |
+
page,
|
| 263 |
+
"() => document.getElementById('graph-match-count').textContent === '2 visible'",
|
| 264 |
+
timeout=5.0,
|
| 265 |
+
)
|
| 266 |
+
page.locator("#match-filter-min").evaluate(
|
| 267 |
+
"node => { node.value = '50'; node.dispatchEvent(new Event('input', {bubbles: true})); }",
|
| 268 |
+
)
|
| 269 |
+
page.locator("#match-filter-max").evaluate(
|
| 270 |
+
"node => { node.value = '100'; node.dispatchEvent(new Event('input', {bubbles: true})); }",
|
| 271 |
+
)
|
| 272 |
+
assert page.locator("[data-3d-node-id='skill:medium-graph-link']").evaluate(
|
| 273 |
+
"node => getComputedStyle(node).display",
|
| 274 |
+
) == "none"
|
| 275 |
+
assert page.locator("[data-testid='graph-svg-edge'][data-edge-weight='0.4300']").evaluate(
|
| 276 |
+
"node => getComputedStyle(node).display",
|
| 277 |
+
) == "none"
|
| 278 |
+
page.locator("#match-filter-max").evaluate(
|
| 279 |
+
"node => { node.value = '80'; node.dispatchEvent(new Event('input', {bubbles: true})); }",
|
| 280 |
+
)
|
| 281 |
+
_wait_for_browser_state(
|
| 282 |
+
page,
|
| 283 |
+
"() => document.getElementById('match-filter-max-value').textContent === '80%'",
|
| 284 |
+
timeout=5.0,
|
| 285 |
+
)
|
| 286 |
+
_wait_for_browser_state(
|
| 287 |
+
page,
|
| 288 |
+
"() => document.getElementById('graph-match-count').textContent === '3 visible'",
|
| 289 |
+
timeout=5.0,
|
| 290 |
+
)
|
| 291 |
+
assert page.locator("[data-3d-node-id='agent:code-reviewer']").evaluate(
|
| 292 |
+
"node => getComputedStyle(node).display",
|
| 293 |
+
) == "none"
|
| 294 |
+
assert page.locator("[data-testid='graph-svg-edge'][data-edge-weight='0.9000']").evaluate(
|
| 295 |
+
"node => getComputedStyle(node).display",
|
| 296 |
+
) == "none"
|
| 297 |
+
page.locator("#match-filter-min").evaluate(
|
| 298 |
+
"node => { node.value = '0'; node.dispatchEvent(new Event('input', {bubbles: true})); }",
|
| 299 |
+
)
|
| 300 |
+
page.locator("#match-filter-max").evaluate(
|
| 301 |
+
"node => { node.value = '100'; node.dispatchEvent(new Event('input', {bubbles: true})); }",
|
| 302 |
+
)
|
| 303 |
+
_wait_for_browser_state(
|
| 304 |
+
page,
|
| 305 |
+
"() => document.getElementById('graph-match-count').textContent === '5 visible'",
|
| 306 |
+
timeout=5.0,
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
reviewer_radius = float(page.locator(
|
| 310 |
"[data-3d-node-id='agent:code-reviewer'] [data-testid='graph-svg-node']",
|
| 311 |
+
).get_attribute("data-radius") or "0")
|
| 312 |
mcp_radius = float(page.locator(
|
| 313 |
"[data-3d-node-id='mcp-server:github-mcp-server'] [data-testid='graph-svg-node']",
|
| 314 |
+
).get_attribute("data-radius") or "0")
|
| 315 |
assert reviewer_radius > mcp_radius
|
| 316 |
|
| 317 |
+
center_node = page.locator(
|
| 318 |
+
"[data-3d-node-id='skill:python-patterns'] [data-testid='graph-svg-node']",
|
| 319 |
+
)
|
| 320 |
+
center_node.click()
|
| 321 |
+
_wait_for_browser_state(
|
| 322 |
+
page,
|
| 323 |
+
"() => document.querySelector('[data-testid=\"graph-node-detail-tree\"]')"
|
| 324 |
+
"?.innerText.includes('python-patterns')",
|
| 325 |
+
timeout=5.0,
|
| 326 |
+
)
|
| 327 |
+
center_detail_text = page.locator("[data-testid='graph-node-detail-tree']").inner_text()
|
| 328 |
+
assert "medium-graph-link" in center_detail_text
|
| 329 |
+
assert "match 43%" in center_detail_text
|
| 330 |
+
assert "graph-only links hidden" not in center_detail_text
|
| 331 |
+
assert "tag 0.000" not in center_detail_text
|
| 332 |
+
assert "evidence: none" not in center_detail_text
|
| 333 |
+
|
| 334 |
+
graph_node = page.locator(
|
| 335 |
+
"[data-3d-node-id='agent:code-reviewer'] [data-testid='graph-svg-node']",
|
| 336 |
+
)
|
| 337 |
+
graph_node.click()
|
| 338 |
+
_wait_for_browser_state(
|
| 339 |
+
page,
|
| 340 |
+
"() => document.getElementById('focus').value === 'code-reviewer'",
|
| 341 |
+
timeout=5.0,
|
| 342 |
+
)
|
| 343 |
+
_wait_for_browser_state(
|
| 344 |
+
page,
|
| 345 |
+
"() => document.querySelector('[data-3d-node-id=\"agent:code-reviewer\"]')"
|
| 346 |
+
"?.getAttribute('data-depth') === '0'",
|
| 347 |
+
timeout=5.0,
|
| 348 |
+
)
|
| 349 |
+
detail_text = page.locator("[data-testid='graph-node-detail-tree']").inner_text()
|
| 350 |
+
assert "Neighbors" in detail_text
|
| 351 |
+
assert "strength 90% relation strength" in detail_text
|
| 352 |
+
assert "tag 33%" in detail_text
|
| 353 |
+
assert "quality: 100%" in detail_text
|
| 354 |
+
assert "raw score clamped" not in detail_text
|
| 355 |
+
assert "graph-only links hidden" not in detail_text
|
| 356 |
+
assert "weak-graph-link" in detail_text
|
| 357 |
+
assert "match 5%" in detail_text
|
| 358 |
+
assert "tag 0.000" not in detail_text
|
| 359 |
+
assert "evidence: none" not in detail_text
|
| 360 |
+
assert "0.333" not in detail_text
|
| 361 |
+
assert page.locator("[data-3d-node-id='agent:code-reviewer']").evaluate(
|
| 362 |
+
"node => node.classList.contains('graph-node-selected')",
|
| 363 |
+
)
|
| 364 |
+
selected_fill = page.locator(
|
| 365 |
+
"[data-3d-node-id='agent:code-reviewer'] [data-testid='graph-svg-node']",
|
| 366 |
+
).evaluate("node => getComputedStyle(node).fill")
|
| 367 |
+
assert selected_fill == "rgb(250, 204, 21)"
|
| 368 |
+
selected_visible_edges = page.locator(
|
| 369 |
+
"[data-testid='graph-svg-edge'].graph-edge-selected",
|
| 370 |
+
).count()
|
| 371 |
+
selected_hit_edges = page.locator(
|
| 372 |
+
"[data-testid='graph-3d-edge'].graph-edge-selected",
|
| 373 |
+
).count()
|
| 374 |
+
assert selected_visible_edges >= 1
|
| 375 |
+
assert selected_hit_edges == 0
|
| 376 |
+
_wait_for_browser_state(
|
| 377 |
+
page,
|
| 378 |
+
"() => document.getElementById('focus').value === 'code-reviewer'",
|
| 379 |
+
timeout=5.0,
|
| 380 |
+
)
|
| 381 |
+
_wait_for_browser_state(
|
| 382 |
+
page,
|
| 383 |
+
"() => document.querySelector('[data-3d-node-id=\"agent:code-reviewer\"]')"
|
| 384 |
+
"?.getAttribute('data-depth') === '0'",
|
| 385 |
+
timeout=5.0,
|
| 386 |
+
)
|
| 387 |
+
page.locator("[data-3d-node-id='agent:code-reviewer']").dblclick()
|
| 388 |
+
_wait_for_browser_state(
|
| 389 |
+
page,
|
| 390 |
+
"() => document.getElementById('focus').value === 'python-patterns'",
|
| 391 |
+
timeout=5.0,
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
page.select_option("#focus-type", "agent")
|
| 395 |
+
page.fill("#focus", "code")
|
| 396 |
+
page.wait_for_selector("[data-testid='graph-live-results'] [data-live-slug='code-reviewer']", timeout=5000)
|
| 397 |
+
page.locator("[data-live-slug='code-reviewer']").click()
|
| 398 |
+
_wait_for_browser_state(
|
| 399 |
+
page,
|
| 400 |
+
"() => document.getElementById('focus').value === 'code-reviewer'",
|
| 401 |
+
timeout=5.0,
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
page.fill("#tag-filter", "review")
|
| 405 |
_wait_for_browser_state(
|
| 406 |
page,
|
| 407 |
"() => document.getElementById('graph-match-count').textContent === '2 visible'",
|
| 408 |
timeout=5.0,
|
| 409 |
)
|
| 410 |
+
page.locator("[data-testid='graph-node-detail-tree'] a[href='/wiki/code-reviewer?type=agent']").click()
|
| 411 |
page.wait_for_url("**/wiki/code-reviewer?type=agent", timeout=5000)
|
| 412 |
assert "code-reviewer" in page.locator("h1").inner_text()
|
| 413 |
finally:
|
|
|
|
| 434 |
"body": "# Graph Guide\n\n## Runtime Graph\n\nSearch the runtime graph.\n",
|
| 435 |
},
|
| 436 |
]
|
| 437 |
+
monkeypatch.setattr(mt, "docs_index_entries", lambda: entries)
|
| 438 |
monkeypatch.setattr(
|
| 439 |
+
mt,
|
| 440 |
+
"docs_tabs",
|
| 441 |
lambda _entries: [
|
| 442 |
{"label": "Home", "slug": "home", "pages": [entries[0]]},
|
| 443 |
{"label": "Repo", "slug": "repo", "pages": [entries[1]]},
|
|
|
|
| 516 |
harness.close()
|
| 517 |
|
| 518 |
|
| 519 |
+
def test_manage_page_supports_create_search_update_and_delete(
|
| 520 |
+
fake_claude: Path,
|
| 521 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 522 |
+
page: Any,
|
| 523 |
+
) -> None:
|
| 524 |
+
harness = _start_monitor(monkeypatch, fake_load=False)
|
| 525 |
+
entity_path = fake_claude / "skill-wiki" / "entities" / "agents" / "custom-reviewer.md"
|
| 526 |
+
try:
|
| 527 |
+
page.goto(f"{harness.base_url}/manage")
|
| 528 |
+
page.wait_for_selector("#entity-editor-form", timeout=5000)
|
| 529 |
+
|
| 530 |
+
page.fill("input[name='slug']", "custom-reviewer")
|
| 531 |
+
page.select_option("select[name='entity_type']", "agent")
|
| 532 |
+
page.fill("input[name='title']", "Custom Reviewer")
|
| 533 |
+
page.fill("input[name='tags']", "python, review, policy")
|
| 534 |
+
page.fill("input[name='description']", "Reviews Python changes with local policy.")
|
| 535 |
+
page.fill("textarea[name='body']", "# Custom Reviewer\n\nUse before merging Python changes.\n")
|
| 536 |
+
page.locator("#entity-editor-form button[type='submit']").click()
|
| 537 |
+
_wait_for_browser_state(
|
| 538 |
+
page,
|
| 539 |
+
"() => document.getElementById('entity-editor-status').textContent.includes('saved agent:custom-reviewer')",
|
| 540 |
+
timeout=5.0,
|
| 541 |
+
)
|
| 542 |
+
assert entity_path.is_file()
|
| 543 |
+
|
| 544 |
+
page.fill("#manage-search", "custom")
|
| 545 |
+
_wait_for_browser_state(
|
| 546 |
+
page,
|
| 547 |
+
"() => document.getElementById('manage-search-status').textContent === '1 result'",
|
| 548 |
+
timeout=5.0,
|
| 549 |
+
)
|
| 550 |
+
page.locator(".manage-result[data-slug='custom-reviewer']").click()
|
| 551 |
+
_wait_for_browser_state(
|
| 552 |
+
page,
|
| 553 |
+
"() => document.getElementById('entity-editor-status').textContent.includes('editing agent:custom-reviewer')",
|
| 554 |
+
timeout=5.0,
|
| 555 |
+
)
|
| 556 |
+
assert page.locator("input[name='title']").input_value() == "Custom Reviewer"
|
| 557 |
+
|
| 558 |
+
page.once("dialog", lambda dialog: dialog.accept())
|
| 559 |
+
page.fill("input[name='title']", "Custom Reviewer Updated")
|
| 560 |
+
page.locator("#entity-editor-form button[type='submit']").click()
|
| 561 |
+
_wait_for_browser_state(
|
| 562 |
+
page,
|
| 563 |
+
"() => document.getElementById('entity-editor-status').textContent.includes('saved agent:custom-reviewer')",
|
| 564 |
+
timeout=5.0,
|
| 565 |
+
)
|
| 566 |
+
assert "title: Custom Reviewer Updated" in entity_path.read_text(encoding="utf-8")
|
| 567 |
+
|
| 568 |
+
page.once("dialog", lambda dialog: dialog.accept())
|
| 569 |
+
page.locator("[data-testid='entity-delete-button']").click()
|
| 570 |
+
_wait_for_browser_state(
|
| 571 |
+
page,
|
| 572 |
+
"() => document.getElementById('entity-editor-status').textContent.includes('deleted agent:custom-reviewer')",
|
| 573 |
+
timeout=5.0,
|
| 574 |
+
)
|
| 575 |
+
assert not entity_path.exists()
|
| 576 |
+
finally:
|
| 577 |
+
harness.close()
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def test_config_and_harness_pages_support_browser_wizard_flows(
|
| 581 |
+
fake_claude: Path,
|
| 582 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 583 |
+
page: Any,
|
| 584 |
+
) -> None:
|
| 585 |
+
_write_wiki_entity(
|
| 586 |
+
fake_claude,
|
| 587 |
+
"harness",
|
| 588 |
+
"langgraph",
|
| 589 |
+
"---\n"
|
| 590 |
+
"title: LangGraph harness\n"
|
| 591 |
+
"type: harness\n"
|
| 592 |
+
"description: Durable Python agent workflows with tool routing.\n"
|
| 593 |
+
"tags: [python, api, local, verification]\n"
|
| 594 |
+
"repo_url: https://github.com/langchain-ai/langgraph\n"
|
| 595 |
+
"---\n"
|
| 596 |
+
"# LangGraph harness\n",
|
| 597 |
+
)
|
| 598 |
+
_write_quality_sidecar(fake_claude, "langgraph-harness", {
|
| 599 |
+
"slug": "langgraph",
|
| 600 |
+
"subject_type": "harness",
|
| 601 |
+
"grade": "A",
|
| 602 |
+
"raw_score": 0.93,
|
| 603 |
+
})
|
| 604 |
+
|
| 605 |
+
harness = _start_monitor(monkeypatch, fake_load=False)
|
| 606 |
+
try:
|
| 607 |
+
page.goto(f"{harness.base_url}/config")
|
| 608 |
+
page.wait_for_selector("#config-form", timeout=5000)
|
| 609 |
+
page.fill("input[name='skill_transformer.line_threshold']", "240")
|
| 610 |
+
page.locator("#config-form button[type='submit']").click()
|
| 611 |
+
_wait_for_browser_state(
|
| 612 |
+
page,
|
| 613 |
+
"() => document.getElementById('config-msg').textContent.includes('saved 1 config keys')",
|
| 614 |
+
timeout=5.0,
|
| 615 |
+
)
|
| 616 |
+
config = json.loads((fake_claude / "skill-system-config.json").read_text(encoding="utf-8"))
|
| 617 |
+
assert config["skill_transformer"]["line_threshold"] == 240
|
| 618 |
+
|
| 619 |
+
page.goto(f"{harness.base_url}/harness")
|
| 620 |
+
page.wait_for_selector("#harness-wizard-form", timeout=5000)
|
| 621 |
+
page.select_option("select[name='model_provider']", "huggingface")
|
| 622 |
+
page.fill("input[name='model']", "HuggingFaceTB/SmolLM2-135M-Instruct")
|
| 623 |
+
page.fill(
|
| 624 |
+
"textarea[name='goal']",
|
| 625 |
+
"Build a local Python code-review harness with pytest verification.",
|
| 626 |
+
)
|
| 627 |
+
page.fill("input[name='verify']", "pytest")
|
| 628 |
+
_wait_for_browser_state(
|
| 629 |
+
page,
|
| 630 |
+
"() => document.querySelector('[data-testid=\"harness-command-output\"]').textContent.includes('--model-provider \"huggingface\"')",
|
| 631 |
+
timeout=5.0,
|
| 632 |
+
)
|
| 633 |
+
command = page.locator("[data-testid='harness-command-output']").inner_text()
|
| 634 |
+
assert "--model \"HuggingFaceTB/SmolLM2-135M-Instruct\"" in command
|
| 635 |
+
assert "--plan-on-no-fit" in command
|
| 636 |
+
assert page.locator(".harness-card[data-harness-slug='langgraph']").count() == 1
|
| 637 |
+
|
| 638 |
+
page.locator("[data-select-harness='langgraph']").click()
|
| 639 |
+
selected = page.locator("#selected-harness-command").inner_text()
|
| 640 |
+
assert "ctx-harness-install langgraph --dry-run" in selected
|
| 641 |
+
assert "ctx-scan-repo --repo . --recommend" in selected
|
| 642 |
+
finally:
|
| 643 |
+
harness.close()
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
def test_sessions_kpi_and_runtime_pages_render_populated_browser_data(
|
| 647 |
+
fake_claude: Path,
|
| 648 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 649 |
+
page: Any,
|
| 650 |
+
tmp_path: Path,
|
| 651 |
+
) -> None:
|
| 652 |
+
(fake_claude / "ctx-audit.jsonl").write_text(
|
| 653 |
+
json.dumps({
|
| 654 |
+
"ts": "2026-06-16T10:00:00Z",
|
| 655 |
+
"event": "skill.loaded",
|
| 656 |
+
"subject": "python-patterns",
|
| 657 |
+
"subject_type": "skill",
|
| 658 |
+
"actor": "hook",
|
| 659 |
+
"session_id": "browser-session",
|
| 660 |
+
}) + "\n",
|
| 661 |
+
encoding="utf-8",
|
| 662 |
+
)
|
| 663 |
+
(fake_claude / "skill-events.jsonl").write_text(
|
| 664 |
+
json.dumps({
|
| 665 |
+
"timestamp": "2026-06-16T10:00:01Z",
|
| 666 |
+
"event": "load",
|
| 667 |
+
"skill": "python-patterns",
|
| 668 |
+
"session_id": "browser-session",
|
| 669 |
+
}) + "\n",
|
| 670 |
+
encoding="utf-8",
|
| 671 |
+
)
|
| 672 |
+
_write_quality_sidecar(fake_claude, "alpha", {
|
| 673 |
+
"slug": "alpha",
|
| 674 |
+
"subject_type": "skill",
|
| 675 |
+
"grade": "A",
|
| 676 |
+
"raw_score": 0.92,
|
| 677 |
+
"score": 0.92,
|
| 678 |
+
"computed_at": "2026-06-16T10:00:00Z",
|
| 679 |
+
})
|
| 680 |
+
runtime_path = tmp_path / "runtime" / "events.jsonl"
|
| 681 |
+
monkeypatch.setattr(mt, "runtime_lifecycle_path", lambda: runtime_path)
|
| 682 |
+
_write_runtime_events(runtime_path, [
|
| 683 |
+
{
|
| 684 |
+
"action": "validation",
|
| 685 |
+
"session_id": "browser-session",
|
| 686 |
+
"check_name": "pytest",
|
| 687 |
+
"status": "failed",
|
| 688 |
+
"summary": "one failing test",
|
| 689 |
+
"created_at": "2026-06-16T10:02:00Z",
|
| 690 |
+
},
|
| 691 |
+
{
|
| 692 |
+
"action": "escalation",
|
| 693 |
+
"session_id": "browser-session",
|
| 694 |
+
"trigger": "validation-failed",
|
| 695 |
+
"reason": "pytest failed",
|
| 696 |
+
"status": "open",
|
| 697 |
+
"severity": "blocking",
|
| 698 |
+
"created_at": "2026-06-16T10:03:00Z",
|
| 699 |
+
},
|
| 700 |
+
])
|
| 701 |
+
|
| 702 |
+
harness = _start_monitor(monkeypatch, fake_load=False)
|
| 703 |
+
try:
|
| 704 |
+
page.goto(f"{harness.base_url}/sessions")
|
| 705 |
+
page.wait_for_selector("table", timeout=5000)
|
| 706 |
+
assert "browser-session" in page.locator("body").inner_text()
|
| 707 |
+
assert "1 unique sessions observed" in page.locator("body").inner_text()
|
| 708 |
+
|
| 709 |
+
page.goto(f"{harness.base_url}/kpi")
|
| 710 |
+
page.wait_for_selector("h1", timeout=5000)
|
| 711 |
+
kpi_text = page.locator("body").inner_text()
|
| 712 |
+
assert "Total entities: 1" in kpi_text
|
| 713 |
+
assert "Grade distribution" in kpi_text
|
| 714 |
+
assert "A: 1" in kpi_text
|
| 715 |
+
|
| 716 |
+
page.goto(f"{harness.base_url}/runtime")
|
| 717 |
+
page.wait_for_selector("h1", timeout=5000)
|
| 718 |
+
runtime_text = page.locator("body").inner_text()
|
| 719 |
+
assert "1 validations / 1 failed / 1 open escalations" in runtime_text
|
| 720 |
+
assert "pytest" in runtime_text
|
| 721 |
+
assert "validation-failed" in runtime_text
|
| 722 |
+
finally:
|
| 723 |
+
harness.close()
|
| 724 |
+
|
| 725 |
+
|
| 726 |
def test_events_page_shows_backlog_and_appends_live_events(
|
| 727 |
fake_claude: Path,
|
| 728 |
monkeypatch: pytest.MonkeyPatch,
|
src/tests/test_dashboard_entities.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Literal
|
| 5 |
+
|
| 6 |
+
from ctx import dashboard_entities
|
| 7 |
+
from ctx.core.quality.skillspector_service import SkillSpectorResult
|
| 8 |
+
from ctx.monitor import testing as monitor_testing
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class _NoopLock:
|
| 12 |
+
def __enter__(self) -> None:
|
| 13 |
+
return None
|
| 14 |
+
|
| 15 |
+
def __exit__(self, *_exc: object) -> Literal[False]:
|
| 16 |
+
return False
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_skill_upsert_requires_security_gate_before_write(tmp_path: Path) -> None:
|
| 20 |
+
writes: list[tuple[Path, str]] = []
|
| 21 |
+
queued: list[tuple[str, str, Path, str, str]] = []
|
| 22 |
+
|
| 23 |
+
def fail_scan(_slug: str, _content: str) -> tuple[bool, str]:
|
| 24 |
+
return False, "SkillSpector security scan did not pass: findings"
|
| 25 |
+
|
| 26 |
+
deps = dashboard_entities.EntityCrudDeps(
|
| 27 |
+
is_safe_slug=lambda value: value == "unsafe-skill",
|
| 28 |
+
normalize_entity_type=lambda value: "skill" if value == "skill" else None,
|
| 29 |
+
wiki_entity_detail=lambda _slug, _etype: None,
|
| 30 |
+
wiki_entity_target_path=lambda slug, _etype: tmp_path / f"{slug}.md",
|
| 31 |
+
wiki_entity_path=lambda _slug, _etype: None,
|
| 32 |
+
iter_wiki_entity_paths=lambda _etype: [],
|
| 33 |
+
read_manifest=lambda: {"load": []},
|
| 34 |
+
perform_unload=lambda _slug, _etype: (True, "unloaded"),
|
| 35 |
+
queue_entity_refresh=lambda *args: queued.append(args), # type: ignore[arg-type]
|
| 36 |
+
file_lock=lambda _path: _NoopLock(),
|
| 37 |
+
write_entity_text=lambda path, content: writes.append((path, content)),
|
| 38 |
+
parse_frontmatter=lambda text: ({}, text),
|
| 39 |
+
frontmatter_tags=lambda _value: [],
|
| 40 |
+
frontmatter_text=lambda value: str(value or ""),
|
| 41 |
+
display_slug=lambda value: value,
|
| 42 |
+
display_label=lambda value: str(value),
|
| 43 |
+
entity_wiki_href=lambda slug, _etype: f"/wiki/{slug}?type=skill",
|
| 44 |
+
scan_skill_content=fail_scan,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
ok, detail = dashboard_entities.upsert_wiki_entity(
|
| 48 |
+
{
|
| 49 |
+
"slug": "unsafe-skill",
|
| 50 |
+
"entity_type": "skill",
|
| 51 |
+
"title": "Unsafe Skill",
|
| 52 |
+
"body": "# Unsafe\n",
|
| 53 |
+
},
|
| 54 |
+
deps=deps,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
assert ok is False
|
| 58 |
+
assert "SkillSpector" in detail
|
| 59 |
+
assert writes == []
|
| 60 |
+
assert queued == []
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_monitor_entity_deps_scan_manual_skill_upserts(monkeypatch) -> None:
|
| 64 |
+
seen: list[tuple[str, str]] = []
|
| 65 |
+
|
| 66 |
+
def fake_scan(slug: str, content: str) -> SkillSpectorResult:
|
| 67 |
+
seen.append((slug, content))
|
| 68 |
+
return SkillSpectorResult(
|
| 69 |
+
status="findings",
|
| 70 |
+
command=["skillspector", "scan"],
|
| 71 |
+
exit_code=1,
|
| 72 |
+
output="prompt injection",
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
monkeypatch.setattr(monitor_testing, "run_skillspector_scan_text", fake_scan)
|
| 76 |
+
|
| 77 |
+
ok, detail = monitor_testing.scan_skill_entity_content("unsafe-skill", "# Unsafe\n")
|
| 78 |
+
|
| 79 |
+
assert ok is False
|
| 80 |
+
assert "SkillSpector security scan did not pass: findings" in detail
|
| 81 |
+
assert seen == [("unsafe-skill", "# Unsafe\n")]
|
src/tests/test_dashboard_smoke.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from collections.abc import Iterator
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
from scripts import dashboard_smoke as smoke
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class FakeResponse:
|
| 12 |
+
def __init__(self, status: int, body: str) -> None:
|
| 13 |
+
self.status = status
|
| 14 |
+
self._body = body.encode("utf-8")
|
| 15 |
+
|
| 16 |
+
def __enter__(self) -> "FakeResponse":
|
| 17 |
+
return self
|
| 18 |
+
|
| 19 |
+
def __exit__(self, *args: object) -> None:
|
| 20 |
+
return None
|
| 21 |
+
|
| 22 |
+
def read(self) -> bytes:
|
| 23 |
+
return self._body
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _urlopen_for(bodies: dict[str, str]):
|
| 27 |
+
def fake_urlopen(url: str, timeout: float) -> FakeResponse:
|
| 28 |
+
path = url.replace("http://127.0.0.1:8765", "")
|
| 29 |
+
return FakeResponse(200, bodies[path])
|
| 30 |
+
|
| 31 |
+
return fake_urlopen
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_run_smoke_checks_dashboard_routes(monkeypatch: pytest.MonkeyPatch) -> None:
|
| 35 |
+
bodies = {spec.path: spec.marker for spec in smoke.DEFAULT_CHECKS}
|
| 36 |
+
seen: list[str] = []
|
| 37 |
+
|
| 38 |
+
def fake_urlopen(url: str, timeout: float) -> FakeResponse:
|
| 39 |
+
path = url.replace("http://127.0.0.1:8765", "")
|
| 40 |
+
seen.append(path)
|
| 41 |
+
return FakeResponse(200, bodies[path])
|
| 42 |
+
|
| 43 |
+
times: Iterator[float] = iter(range(0, len(smoke.DEFAULT_CHECKS) * 2))
|
| 44 |
+
monkeypatch.setattr(smoke.urllib.request, "urlopen", fake_urlopen)
|
| 45 |
+
monkeypatch.setattr(smoke.time, "perf_counter", lambda: next(times))
|
| 46 |
+
|
| 47 |
+
results = smoke.run_smoke("http://127.0.0.1:8765", timeout=5)
|
| 48 |
+
|
| 49 |
+
assert seen == [spec.path for spec in smoke.DEFAULT_CHECKS]
|
| 50 |
+
assert all(result.ok for result in results)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_run_smoke_fails_when_marker_is_missing(monkeypatch: pytest.MonkeyPatch) -> None:
|
| 54 |
+
bodies = {spec.path: spec.marker for spec in smoke.DEFAULT_CHECKS}
|
| 55 |
+
bodies["/manage"] = "wrong page"
|
| 56 |
+
times: Iterator[float] = iter(range(0, len(smoke.DEFAULT_CHECKS) * 2))
|
| 57 |
+
monkeypatch.setattr(smoke.urllib.request, "urlopen", _urlopen_for(bodies))
|
| 58 |
+
monkeypatch.setattr(smoke.time, "perf_counter", lambda: next(times))
|
| 59 |
+
|
| 60 |
+
results = smoke.run_smoke("http://127.0.0.1:8765", timeout=5)
|
| 61 |
+
|
| 62 |
+
failed = [result for result in results if not result.ok]
|
| 63 |
+
assert [result.name for result in failed] == ["manage"]
|
| 64 |
+
assert failed[0].reason == "missing marker 'Manage catalog'"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def test_apply_latency_thresholds_marks_slow_warm_graph() -> None:
|
| 68 |
+
results = [
|
| 69 |
+
smoke.CheckResult(
|
| 70 |
+
name="graph-api-warm",
|
| 71 |
+
path="/api/graph/github.json?type=mcp-server&limit=20",
|
| 72 |
+
status=200,
|
| 73 |
+
elapsed=1.2,
|
| 74 |
+
ok=True,
|
| 75 |
+
reason="ok",
|
| 76 |
+
bytes_read=123,
|
| 77 |
+
),
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
smoke.apply_latency_thresholds(results, {"graph-api-warm": 0.5})
|
| 81 |
+
|
| 82 |
+
assert not results[0].ok
|
| 83 |
+
assert results[0].reason == "slow: 1.20s > 0.50s"
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_emit_jsonl_outputs_structured_rows() -> None:
|
| 87 |
+
result = smoke.CheckResult(
|
| 88 |
+
name="home",
|
| 89 |
+
path="/",
|
| 90 |
+
status=200,
|
| 91 |
+
elapsed=0.1,
|
| 92 |
+
ok=True,
|
| 93 |
+
reason="ok",
|
| 94 |
+
bytes_read=50,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
rows = smoke.results_to_jsonl([result]).splitlines()
|
| 98 |
+
|
| 99 |
+
assert json.loads(rows[0]) == {
|
| 100 |
+
"name": "home",
|
| 101 |
+
"path": "/",
|
| 102 |
+
"status": 200,
|
| 103 |
+
"elapsed": 0.1,
|
| 104 |
+
"ok": True,
|
| 105 |
+
"reason": "ok",
|
| 106 |
+
"bytes": 50,
|
| 107 |
+
}
|
src/tests/test_dashboard_user_story_tracker.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import csv
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
repo_root = Path(__file__).resolve().parents[2]
|
| 8 |
+
sys.path.insert(0, str(repo_root / "src"))
|
| 9 |
+
|
| 10 |
+
from ctx.monitor import routes as monitor_routes # noqa: E402
|
| 11 |
+
|
| 12 |
+
TRACKER = repo_root / "docs" / "qa" / "dashboard-user-story-status.csv"
|
| 13 |
+
PASS_STATUSES = {"Tested Pass", "Retested Pass"}
|
| 14 |
+
VALIDATION_STATUSES = {"Needs Validation"}
|
| 15 |
+
FIX_STATUSES = {"Needs Fix"}
|
| 16 |
+
ACTIONABLE_STATUSES = PASS_STATUSES | VALIDATION_STATUSES | FIX_STATUSES
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _tracker_rows() -> list[dict[str, str]]:
|
| 20 |
+
with TRACKER.open(newline="", encoding="utf-8") as f:
|
| 21 |
+
return list(csv.DictReader(f))
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _tracker_text() -> str:
|
| 25 |
+
return "\n".join(" ".join(row.values()) for row in _tracker_rows())
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_dashboard_user_story_tracker_has_valid_rows() -> None:
|
| 29 |
+
rows = _tracker_rows()
|
| 30 |
+
assert rows
|
| 31 |
+
required = (
|
| 32 |
+
"dashboard_id",
|
| 33 |
+
"surface",
|
| 34 |
+
"page_or_api",
|
| 35 |
+
"route_or_control",
|
| 36 |
+
"source_evidence",
|
| 37 |
+
"user_story",
|
| 38 |
+
"expected_behavior",
|
| 39 |
+
"test_command_or_steps",
|
| 40 |
+
"status",
|
| 41 |
+
"first_test_result",
|
| 42 |
+
"last_verified_at",
|
| 43 |
+
)
|
| 44 |
+
for row in rows:
|
| 45 |
+
assert None not in row, f"{row.get('dashboard_id', '<unknown>')} has extra CSV columns"
|
| 46 |
+
for key in required:
|
| 47 |
+
assert row[key].strip(), f"{row.get('dashboard_id', '<unknown>')} missing {key}"
|
| 48 |
+
assert row["status"] in ACTIONABLE_STATUSES
|
| 49 |
+
if row["status"] in FIX_STATUSES:
|
| 50 |
+
for key in ("error_id", "error_summary", "fix_status"):
|
| 51 |
+
assert row[key].strip(), (
|
| 52 |
+
f"{row.get('dashboard_id', '<unknown>')} has "
|
| 53 |
+
f"{row['status']} without {key}"
|
| 54 |
+
)
|
| 55 |
+
if row["status"] in VALIDATION_STATUSES:
|
| 56 |
+
assert row["notes"].strip(), (
|
| 57 |
+
f"{row.get('dashboard_id', '<unknown>')} needs validation "
|
| 58 |
+
"without a validation note"
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_dashboard_user_story_tracker_covers_all_monitor_routes() -> None:
|
| 63 |
+
route_patterns: list[str] = []
|
| 64 |
+
route_patterns.extend(href for _key, _label, href in monitor_routes.NAV_ROUTES)
|
| 65 |
+
route_patterns.extend(sorted(monitor_routes.PAGE_ROUTES))
|
| 66 |
+
route_patterns.extend(sorted(monitor_routes.GET_API_ROUTES))
|
| 67 |
+
route_patterns.extend(monitor_routes.GET_API_PATTERNS)
|
| 68 |
+
route_patterns.extend(sorted(monitor_routes.POST_API_ROUTES))
|
| 69 |
+
route_patterns.extend(("/session/<session_id>", "/skill/<slug>", "/wiki/<slug>"))
|
| 70 |
+
route_patterns = list(dict.fromkeys(route_patterns))
|
| 71 |
+
tracker = _tracker_text()
|
| 72 |
+
|
| 73 |
+
assert route_patterns
|
| 74 |
+
assert [route for route in route_patterns if route not in tracker] == []
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_dashboard_user_story_tracker_records_verified_graph_counts() -> None:
|
| 78 |
+
rows = {row["dashboard_id"]: row for row in _tracker_rows()}
|
| 79 |
+
graph_count = rows["DASH-NUM-001"]
|
| 80 |
+
|
| 81 |
+
assert graph_count["status"] == "Tested Pass"
|
| 82 |
+
assert "79,958 nodes" in graph_count["first_test_result"]
|
| 83 |
+
assert "1,778,069 edges" in graph_count["first_test_result"]
|
src/tests/test_dedup_check.py
CHANGED
|
@@ -21,6 +21,7 @@ if str(SRC_DIR) not in sys.path:
|
|
| 21 |
sys.path.insert(0, str(SRC_DIR))
|
| 22 |
|
| 23 |
from ctx.core.quality import dedup_check as dc # noqa: E402
|
|
|
|
| 24 |
|
| 25 |
|
| 26 |
# ── Allowlist ──────────────────────────────────────────────────────────
|
|
@@ -58,6 +59,56 @@ def test_allowlist_skips_malformed_lines(tmp_path: Path) -> None:
|
|
| 58 |
assert dc.load_allowlist(p) == set()
|
| 59 |
|
| 60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
# ── State ──────────────────────────────────────────────────────────────
|
| 62 |
|
| 63 |
|
|
|
|
| 21 |
sys.path.insert(0, str(SRC_DIR))
|
| 22 |
|
| 23 |
from ctx.core.quality import dedup_check as dc # noqa: E402
|
| 24 |
+
from ctx.core.wiki.wiki_packs import write_wiki_base_pack # noqa: E402
|
| 25 |
|
| 26 |
|
| 27 |
# ── Allowlist ──────────────────────────────────────────────────────────
|
|
|
|
| 59 |
assert dc.load_allowlist(p) == set()
|
| 60 |
|
| 61 |
|
| 62 |
+
def test_discover_entities_reads_wiki_packs_before_physical_pages(tmp_path: Path) -> None:
|
| 63 |
+
stale_dir = tmp_path / "entities" / "skills"
|
| 64 |
+
stale_dir.mkdir(parents=True)
|
| 65 |
+
(stale_dir / "stale.md").write_text(
|
| 66 |
+
"---\n"
|
| 67 |
+
"description: stale physical page\n"
|
| 68 |
+
"---\n"
|
| 69 |
+
"# stale\n",
|
| 70 |
+
encoding="utf-8",
|
| 71 |
+
)
|
| 72 |
+
write_wiki_base_pack(
|
| 73 |
+
pack_dir=tmp_path / "wiki-packs" / "base-export-1",
|
| 74 |
+
pack_id="base-export-1",
|
| 75 |
+
base_export_id="export-1",
|
| 76 |
+
pages={
|
| 77 |
+
"entities/skills/pack-skill.md": (
|
| 78 |
+
"---\n"
|
| 79 |
+
"description: pack skill description\n"
|
| 80 |
+
"tags:\n"
|
| 81 |
+
" - pack\n"
|
| 82 |
+
"---\n"
|
| 83 |
+
"# pack skill\n"
|
| 84 |
+
),
|
| 85 |
+
"entities/agents/reviewer.md": (
|
| 86 |
+
"---\n"
|
| 87 |
+
"description: review agent\n"
|
| 88 |
+
"---\n"
|
| 89 |
+
"# reviewer\n"
|
| 90 |
+
),
|
| 91 |
+
"entities/mcp-servers/g/github.md": (
|
| 92 |
+
"---\n"
|
| 93 |
+
"description: github mcp\n"
|
| 94 |
+
"---\n"
|
| 95 |
+
"# github\n"
|
| 96 |
+
),
|
| 97 |
+
},
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
entities = dc.discover_entities(tmp_path)
|
| 101 |
+
|
| 102 |
+
assert [entity.node_id for entity in entities] == [
|
| 103 |
+
"agent:reviewer",
|
| 104 |
+
"mcp-server:github",
|
| 105 |
+
"skill:pack-skill",
|
| 106 |
+
]
|
| 107 |
+
pack_skill = next(entity for entity in entities if entity.node_id == "skill:pack-skill")
|
| 108 |
+
assert pack_skill.description == "pack skill description"
|
| 109 |
+
assert pack_skill.tags == ("pack",)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
# ── State ──────────────────────────────────────────────────────────────
|
| 113 |
|
| 114 |
|
src/tests/test_docs_catalog_page.py
CHANGED
|
@@ -54,16 +54,16 @@ def test_public_catalog_page_does_not_link_to_local_dashboard() -> None:
|
|
| 54 |
assert "../dashboard/#catalog-badge-links" in text
|
| 55 |
|
| 56 |
|
| 57 |
-
def
|
| 58 |
text = (repo_root / ".github" / "workflows" / "docs.yml").read_text(
|
| 59 |
encoding="utf-8"
|
| 60 |
)
|
| 61 |
|
| 62 |
-
assert "actions/upload-pages-artifact"
|
| 63 |
-
assert "actions/upload-artifact@v4" in text
|
| 64 |
-
assert "
|
| 65 |
-
assert "artifact.tar" in text
|
| 66 |
-
assert "overwrite: true" in text
|
| 67 |
|
| 68 |
|
| 69 |
def test_public_docs_render_current_graph_contract_totals() -> None:
|
|
|
|
| 54 |
assert "../dashboard/#catalog-badge-links" in text
|
| 55 |
|
| 56 |
|
| 57 |
+
def test_docs_pages_workflow_uses_node24_pages_artifact_action() -> None:
|
| 58 |
text = (repo_root / ".github" / "workflows" / "docs.yml").read_text(
|
| 59 |
encoding="utf-8"
|
| 60 |
)
|
| 61 |
|
| 62 |
+
assert "actions/upload-pages-artifact@v5" in text
|
| 63 |
+
assert "actions/upload-artifact@v4" not in text
|
| 64 |
+
assert "path: site" in text
|
| 65 |
+
assert "artifact.tar" not in text
|
| 66 |
+
assert "overwrite: true" not in text
|
| 67 |
|
| 68 |
|
| 69 |
def test_public_docs_render_current_graph_contract_totals() -> None:
|
src/tests/test_enterprise_telemetry.py
ADDED
|
@@ -0,0 +1,2000 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import asdict
|
| 4 |
+
from io import BytesIO
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import stat
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import pytest
|
| 12 |
+
|
| 13 |
+
import ctx.api as ctx_api
|
| 14 |
+
from ctx.cli import telemetry as telemetry_cli
|
| 15 |
+
import ctx.telemetry as telemetry
|
| 16 |
+
from ctx.adapters.generic.ctx_core_tools import CtxCoreToolbox
|
| 17 |
+
from ctx.mcp_server import server as mcp_server
|
| 18 |
+
from ctx.telemetry import (
|
| 19 |
+
EXPORT_STATUS_SCHEMA_VERSION,
|
| 20 |
+
METRIC_SCHEMA_VERSION,
|
| 21 |
+
RETENTION_STATUS_SCHEMA_VERSION,
|
| 22 |
+
SCHEMA_VERSION,
|
| 23 |
+
TelemetryEvent,
|
| 24 |
+
TelemetryMetric,
|
| 25 |
+
enforce_telemetry_retention,
|
| 26 |
+
exception_payload,
|
| 27 |
+
export_events,
|
| 28 |
+
export_metrics,
|
| 29 |
+
hash_identifier,
|
| 30 |
+
plan_telemetry_retention,
|
| 31 |
+
read_events,
|
| 32 |
+
read_metrics,
|
| 33 |
+
record_counter,
|
| 34 |
+
record_event,
|
| 35 |
+
record_exception,
|
| 36 |
+
record_histogram,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _redirect_real_event_telemetry(
|
| 41 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 42 |
+
path: Path,
|
| 43 |
+
) -> None:
|
| 44 |
+
config = {"path": str(path), "export": {"enabled": False}}
|
| 45 |
+
|
| 46 |
+
def config_get(key: str, default: Any) -> Any:
|
| 47 |
+
return config if key == "telemetry" else default
|
| 48 |
+
|
| 49 |
+
monkeypatch.setattr(telemetry, "_config_get", config_get)
|
| 50 |
+
monkeypatch.setattr(telemetry, "record_event", record_event)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_record_event_writes_local_redacted_envelope(tmp_path: Path) -> None:
|
| 54 |
+
path = tmp_path / "events.jsonl"
|
| 55 |
+
|
| 56 |
+
event = record_event(
|
| 57 |
+
"recommendation.returned",
|
| 58 |
+
source="ctx-core",
|
| 59 |
+
session_id="sess-1",
|
| 60 |
+
transport="python-api",
|
| 61 |
+
actor="cli",
|
| 62 |
+
duration_ms=12.5,
|
| 63 |
+
repo="/Users/example/private-repo",
|
| 64 |
+
cwd="/Users/example/private-repo/service",
|
| 65 |
+
payload={
|
| 66 |
+
"query": "debug failing checkout for customer acme",
|
| 67 |
+
"result_count": 2,
|
| 68 |
+
"token": "sk-secret-token-value",
|
| 69 |
+
"ranked": [{"slug": "python-patterns", "score": 0.91}],
|
| 70 |
+
},
|
| 71 |
+
path=path,
|
| 72 |
+
trusted_root=tmp_path,
|
| 73 |
+
config={"mode": "local_redacted", "path": str(path)},
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
assert event is not None
|
| 77 |
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
| 78 |
+
assert raw["schema_version"] == SCHEMA_VERSION
|
| 79 |
+
assert raw["event_name"] == "recommendation.returned"
|
| 80 |
+
assert raw["source"] == "ctx-core"
|
| 81 |
+
assert raw["session_id"] == "sess-1"
|
| 82 |
+
assert raw["session_hash"].startswith("sha256:")
|
| 83 |
+
assert len(raw["trace_id"]) == 32
|
| 84 |
+
assert len(raw["span_id"]) == 16
|
| 85 |
+
assert raw["ctx_version"]
|
| 86 |
+
assert raw["privacy_mode"] == "local_redacted"
|
| 87 |
+
assert raw["repo_hash"].startswith("sha256:")
|
| 88 |
+
assert raw["cwd_hash"].startswith("sha256:")
|
| 89 |
+
assert raw["payload"]["result_count"] == 2
|
| 90 |
+
assert raw["payload"]["token"] == "[redacted]"
|
| 91 |
+
assert "query" not in raw["payload"]
|
| 92 |
+
assert raw["payload"]["query_hash"].startswith("sha256:")
|
| 93 |
+
|
| 94 |
+
got = list(read_events(path, trusted_root=tmp_path))
|
| 95 |
+
assert len(got) == 1
|
| 96 |
+
assert got[0].event_id == event.event_id
|
| 97 |
+
assert got[0].session_hash == event.session_hash
|
| 98 |
+
assert got[0].trace_id == event.trace_id
|
| 99 |
+
assert got[0].span_id == event.span_id
|
| 100 |
+
assert got[0].ctx_version == event.ctx_version
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def test_telemetry_span_propagates_trace_to_nested_events(tmp_path: Path) -> None:
|
| 104 |
+
path = tmp_path / "events.jsonl"
|
| 105 |
+
|
| 106 |
+
with telemetry.telemetry_span():
|
| 107 |
+
parent = record_event(
|
| 108 |
+
"ctx.api.recommend_bundle",
|
| 109 |
+
source="ctx-api",
|
| 110 |
+
path=path,
|
| 111 |
+
trusted_root=tmp_path,
|
| 112 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 113 |
+
)
|
| 114 |
+
with telemetry.telemetry_span():
|
| 115 |
+
child = record_event(
|
| 116 |
+
"ctx.core.recommend_bundle",
|
| 117 |
+
source="ctx-core",
|
| 118 |
+
path=path,
|
| 119 |
+
trusted_root=tmp_path,
|
| 120 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
assert parent is not None
|
| 124 |
+
assert child is not None
|
| 125 |
+
assert parent.trace_id == child.trace_id
|
| 126 |
+
assert parent.span_id != child.span_id
|
| 127 |
+
assert parent.parent_span_id is None
|
| 128 |
+
assert child.parent_span_id == parent.span_id
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def test_record_event_explicit_trace_ids_override_active_span(tmp_path: Path) -> None:
|
| 132 |
+
path = tmp_path / "events.jsonl"
|
| 133 |
+
|
| 134 |
+
with telemetry.telemetry_span():
|
| 135 |
+
event = record_event(
|
| 136 |
+
"ctx.api.recommend_bundle",
|
| 137 |
+
source="ctx-api",
|
| 138 |
+
trace_id="1" * 32,
|
| 139 |
+
span_id="2" * 16,
|
| 140 |
+
parent_span_id="3" * 16,
|
| 141 |
+
path=path,
|
| 142 |
+
trusted_root=tmp_path,
|
| 143 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
assert event is not None
|
| 147 |
+
assert event.trace_id == "1" * 32
|
| 148 |
+
assert event.span_id == "2" * 16
|
| 149 |
+
assert event.parent_span_id == "3" * 16
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def test_record_metrics_writes_local_redacted_spool(tmp_path: Path) -> None:
|
| 153 |
+
path = tmp_path / "metrics.jsonl"
|
| 154 |
+
config = {
|
| 155 |
+
"metrics": {
|
| 156 |
+
"enabled": True,
|
| 157 |
+
"path": str(path),
|
| 158 |
+
"export": {"enabled": False},
|
| 159 |
+
},
|
| 160 |
+
"privacy": {"hash_salt": "tenant-a"},
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
with telemetry.telemetry_span():
|
| 164 |
+
counter = record_counter(
|
| 165 |
+
"ctx.api.requests",
|
| 166 |
+
value=2,
|
| 167 |
+
attributes={"query": "private acme query", "ctx.operation": "recommend"},
|
| 168 |
+
source="ctx-api",
|
| 169 |
+
session_id="sess-private",
|
| 170 |
+
path=path,
|
| 171 |
+
trusted_root=tmp_path,
|
| 172 |
+
config=config,
|
| 173 |
+
)
|
| 174 |
+
histogram = record_histogram(
|
| 175 |
+
"ctx.api.duration",
|
| 176 |
+
value=42.5,
|
| 177 |
+
unit="ms",
|
| 178 |
+
attributes={"path": "/Users/example/private-repo", "ctx.operation": "recommend"},
|
| 179 |
+
source="ctx-api",
|
| 180 |
+
session_id="sess-private",
|
| 181 |
+
path=path,
|
| 182 |
+
trusted_root=tmp_path,
|
| 183 |
+
config=config,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
assert counter is not None
|
| 187 |
+
assert histogram is not None
|
| 188 |
+
assert counter.schema_version == METRIC_SCHEMA_VERSION
|
| 189 |
+
assert counter.instrument == "counter"
|
| 190 |
+
assert histogram.instrument == "histogram"
|
| 191 |
+
assert counter.trace_id == histogram.trace_id
|
| 192 |
+
assert counter.session_hash == histogram.session_hash
|
| 193 |
+
assert counter.session_hash is not None
|
| 194 |
+
assert counter.session_hash.startswith("sha256:")
|
| 195 |
+
raw = path.read_text(encoding="utf-8")
|
| 196 |
+
assert "private acme query" not in raw
|
| 197 |
+
assert "/Users/example/private-repo" not in raw
|
| 198 |
+
assert "sess-private" not in raw
|
| 199 |
+
assert "query_hash" in raw
|
| 200 |
+
assert "path_hash" in raw
|
| 201 |
+
if os.name != "nt":
|
| 202 |
+
assert stat.S_IMODE(path.stat().st_mode) == 0o600
|
| 203 |
+
|
| 204 |
+
metrics = list(read_metrics(path, trusted_root=tmp_path))
|
| 205 |
+
assert [metric.name for metric in metrics] == [
|
| 206 |
+
"ctx.api.requests",
|
| 207 |
+
"ctx.api.duration",
|
| 208 |
+
]
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def test_metrics_disabled_unless_metrics_config_present(tmp_path: Path) -> None:
|
| 212 |
+
path = tmp_path / "metrics.jsonl"
|
| 213 |
+
|
| 214 |
+
missing = record_counter(
|
| 215 |
+
"ctx.api.requests",
|
| 216 |
+
path=path,
|
| 217 |
+
trusted_root=tmp_path,
|
| 218 |
+
config={"path": str(tmp_path / "events.jsonl")},
|
| 219 |
+
)
|
| 220 |
+
disabled = record_counter(
|
| 221 |
+
"ctx.api.requests",
|
| 222 |
+
path=path,
|
| 223 |
+
trusted_root=tmp_path,
|
| 224 |
+
config={"metrics": {"enabled": False, "path": str(path)}},
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
assert missing is None
|
| 228 |
+
assert disabled is None
|
| 229 |
+
assert not path.exists()
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def test_export_metrics_posts_otlp_resource_metrics(
|
| 233 |
+
tmp_path: Path,
|
| 234 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 235 |
+
) -> None:
|
| 236 |
+
path = tmp_path / "metrics.jsonl"
|
| 237 |
+
config = {
|
| 238 |
+
"metrics": {
|
| 239 |
+
"enabled": True,
|
| 240 |
+
"path": str(path),
|
| 241 |
+
"export": {"enabled": False},
|
| 242 |
+
},
|
| 243 |
+
"privacy": {"hash_salt": "tenant-a"},
|
| 244 |
+
}
|
| 245 |
+
counter = record_counter(
|
| 246 |
+
"ctx.api.requests",
|
| 247 |
+
value=3,
|
| 248 |
+
attributes={"query": "private acme query"},
|
| 249 |
+
source="ctx-api",
|
| 250 |
+
session_id="sess-raw-private",
|
| 251 |
+
path=path,
|
| 252 |
+
trusted_root=tmp_path,
|
| 253 |
+
config=config,
|
| 254 |
+
)
|
| 255 |
+
histogram = record_histogram(
|
| 256 |
+
"ctx.api.duration",
|
| 257 |
+
value=42,
|
| 258 |
+
attributes={"ctx.operation": "recommend"},
|
| 259 |
+
source="ctx-api",
|
| 260 |
+
session_id="sess-raw-private",
|
| 261 |
+
path=path,
|
| 262 |
+
trusted_root=tmp_path,
|
| 263 |
+
config=config,
|
| 264 |
+
)
|
| 265 |
+
assert counter is not None
|
| 266 |
+
assert histogram is not None
|
| 267 |
+
calls: list[tuple[dict[str, Any], dict[str, Any]]] = []
|
| 268 |
+
|
| 269 |
+
def fake_post_otlp_http(
|
| 270 |
+
payload: dict[str, Any],
|
| 271 |
+
settings: dict[str, Any],
|
| 272 |
+
) -> None:
|
| 273 |
+
calls.append((payload, settings))
|
| 274 |
+
|
| 275 |
+
monkeypatch.setattr(telemetry, "_post_otlp_http", fake_post_otlp_http)
|
| 276 |
+
|
| 277 |
+
result = export_metrics(
|
| 278 |
+
path,
|
| 279 |
+
trusted_root=tmp_path,
|
| 280 |
+
config={
|
| 281 |
+
"metrics": {
|
| 282 |
+
"enabled": True,
|
| 283 |
+
"path": str(path),
|
| 284 |
+
"export": {
|
| 285 |
+
"enabled": True,
|
| 286 |
+
"sink": "otlp_http",
|
| 287 |
+
"otlp": {
|
| 288 |
+
"endpoint": "https://collector.example:4318/v1/metrics",
|
| 289 |
+
"allowed_hosts": ["collector.example"],
|
| 290 |
+
"service_name": "ctx-test",
|
| 291 |
+
},
|
| 292 |
+
},
|
| 293 |
+
},
|
| 294 |
+
"privacy": {"hash_salt": "tenant-a"},
|
| 295 |
+
},
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
assert result.exported == 2
|
| 299 |
+
assert result.failed == 0
|
| 300 |
+
assert result.status == "ok"
|
| 301 |
+
assert result.checkpoint_advanced is True
|
| 302 |
+
assert len(calls) == 1
|
| 303 |
+
payload, settings = calls[0]
|
| 304 |
+
assert settings["otlp_endpoint"] == "https://collector.example:4318/v1/metrics"
|
| 305 |
+
metric_records = payload["resourceMetrics"][0]["scopeMetrics"][0]["metrics"]
|
| 306 |
+
by_name = {record["name"]: record for record in metric_records}
|
| 307 |
+
assert by_name["ctx.api.requests"]["sum"]["aggregationTemporality"] == 1
|
| 308 |
+
assert by_name["ctx.api.requests"]["sum"]["isMonotonic"] is True
|
| 309 |
+
assert by_name["ctx.api.requests"]["sum"]["dataPoints"][0]["asInt"] == "3"
|
| 310 |
+
histogram_point = by_name["ctx.api.duration"]["histogram"]["dataPoints"][0]
|
| 311 |
+
assert by_name["ctx.api.duration"]["histogram"]["aggregationTemporality"] == 1
|
| 312 |
+
assert histogram_point["count"] == "1"
|
| 313 |
+
assert histogram_point["sum"] == 42.0
|
| 314 |
+
assert histogram_point["min"] == 42.0
|
| 315 |
+
assert histogram_point["max"] == 42.0
|
| 316 |
+
assert sum(int(count) for count in histogram_point["bucketCounts"]) == 1
|
| 317 |
+
text = json.dumps(payload)
|
| 318 |
+
assert "private acme query" not in text
|
| 319 |
+
assert "sess-raw-private" not in text
|
| 320 |
+
assert "ctx.session.hash" in text
|
| 321 |
+
assert "ctx.metric.query_hash" in text
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def test_metrics_export_checkpoint_is_independent_from_event_checkpoint(
|
| 325 |
+
tmp_path: Path,
|
| 326 |
+
) -> None:
|
| 327 |
+
event_path = tmp_path / "events.jsonl"
|
| 328 |
+
metric_path = tmp_path / "metrics.jsonl"
|
| 329 |
+
event_export_path = tmp_path / "exported-events.jsonl"
|
| 330 |
+
metric_export_path = tmp_path / "exported-metrics.jsonl"
|
| 331 |
+
event = record_event(
|
| 332 |
+
"ctx.api.recommend_bundle",
|
| 333 |
+
source="ctx-api",
|
| 334 |
+
path=event_path,
|
| 335 |
+
trusted_root=tmp_path,
|
| 336 |
+
config={"path": str(event_path), "export": {"enabled": False}},
|
| 337 |
+
)
|
| 338 |
+
metric = record_counter(
|
| 339 |
+
"ctx.api.requests",
|
| 340 |
+
path=metric_path,
|
| 341 |
+
trusted_root=tmp_path,
|
| 342 |
+
config={
|
| 343 |
+
"metrics": {
|
| 344 |
+
"enabled": True,
|
| 345 |
+
"path": str(metric_path),
|
| 346 |
+
"export": {"enabled": False},
|
| 347 |
+
},
|
| 348 |
+
},
|
| 349 |
+
)
|
| 350 |
+
assert event is not None
|
| 351 |
+
assert metric is not None
|
| 352 |
+
|
| 353 |
+
event_result = export_events(
|
| 354 |
+
event_path,
|
| 355 |
+
trusted_root=tmp_path,
|
| 356 |
+
config={
|
| 357 |
+
"path": str(event_path),
|
| 358 |
+
"export": {
|
| 359 |
+
"enabled": True,
|
| 360 |
+
"sink": "local_jsonl",
|
| 361 |
+
"path": str(event_export_path),
|
| 362 |
+
},
|
| 363 |
+
},
|
| 364 |
+
)
|
| 365 |
+
metric_result = export_metrics(
|
| 366 |
+
metric_path,
|
| 367 |
+
trusted_root=tmp_path,
|
| 368 |
+
config={
|
| 369 |
+
"metrics": {
|
| 370 |
+
"enabled": True,
|
| 371 |
+
"path": str(metric_path),
|
| 372 |
+
"export": {
|
| 373 |
+
"enabled": True,
|
| 374 |
+
"sink": "local_jsonl",
|
| 375 |
+
"path": str(metric_export_path),
|
| 376 |
+
},
|
| 377 |
+
},
|
| 378 |
+
},
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
assert event_result.checkpoint_path == str(event_path) + ".export-checkpoint.json"
|
| 382 |
+
assert metric_result.checkpoint_path == str(metric_path) + ".export-checkpoint.json"
|
| 383 |
+
event_checkpoint = json.loads(Path(event_result.checkpoint_path).read_text(encoding="utf-8"))
|
| 384 |
+
metric_checkpoint = json.loads(Path(metric_result.checkpoint_path).read_text(encoding="utf-8"))
|
| 385 |
+
assert event_checkpoint["last_event_id"] == event.event_id
|
| 386 |
+
assert "last_metric_id" not in event_checkpoint
|
| 387 |
+
assert metric_checkpoint["last_metric_id"] == metric.metric_id
|
| 388 |
+
assert "last_event_id" not in metric_checkpoint
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def test_export_metrics_degraded_on_malformed_pending_records(
|
| 392 |
+
tmp_path: Path,
|
| 393 |
+
capsys: pytest.CaptureFixture[str],
|
| 394 |
+
) -> None:
|
| 395 |
+
path = tmp_path / "metrics.jsonl"
|
| 396 |
+
export_path = tmp_path / "exported-metrics.jsonl"
|
| 397 |
+
metric = record_counter(
|
| 398 |
+
"ctx.api.requests",
|
| 399 |
+
path=path,
|
| 400 |
+
trusted_root=tmp_path,
|
| 401 |
+
config={
|
| 402 |
+
"metrics": {
|
| 403 |
+
"enabled": True,
|
| 404 |
+
"path": str(path),
|
| 405 |
+
"export": {"enabled": False},
|
| 406 |
+
},
|
| 407 |
+
},
|
| 408 |
+
)
|
| 409 |
+
assert metric is not None
|
| 410 |
+
with path.open("a", encoding="utf-8") as fh:
|
| 411 |
+
fh.write("{not valid json}\n")
|
| 412 |
+
|
| 413 |
+
result = export_metrics(
|
| 414 |
+
path,
|
| 415 |
+
trusted_root=tmp_path,
|
| 416 |
+
config={
|
| 417 |
+
"metrics": {
|
| 418 |
+
"enabled": True,
|
| 419 |
+
"path": str(path),
|
| 420 |
+
"export": {
|
| 421 |
+
"enabled": True,
|
| 422 |
+
"sink": "local_jsonl",
|
| 423 |
+
"path": str(export_path),
|
| 424 |
+
},
|
| 425 |
+
},
|
| 426 |
+
},
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
assert result.attempted == 1
|
| 430 |
+
assert result.exported == 1
|
| 431 |
+
assert result.failed == 0
|
| 432 |
+
assert result.status == "degraded"
|
| 433 |
+
assert result.malformed_records == 1
|
| 434 |
+
assert result.malformed_pending_records == 1
|
| 435 |
+
assert result.checkpoint_advanced is False
|
| 436 |
+
assert not Path(str(path) + ".export-checkpoint.json").exists()
|
| 437 |
+
status = json.loads(Path(str(path) + ".export-status.json").read_text(encoding="utf-8"))
|
| 438 |
+
assert status["status"] == "degraded"
|
| 439 |
+
assert status["malformed_pending_records"] == 1
|
| 440 |
+
assert status["checkpoint_advanced"] is False
|
| 441 |
+
assert "skipping malformed metric" in capsys.readouterr().err
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def test_api_core_events_share_trace_context(
|
| 445 |
+
tmp_path: Path,
|
| 446 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 447 |
+
) -> None:
|
| 448 |
+
import ctx.adapters.generic.ctx_core_tools as core_tools
|
| 449 |
+
|
| 450 |
+
spans: dict[str, telemetry.TelemetrySpan] = {}
|
| 451 |
+
|
| 452 |
+
def capture_api_event(*args: Any, **kwargs: Any) -> None:
|
| 453 |
+
span = telemetry.current_telemetry_span()
|
| 454 |
+
assert span is not None
|
| 455 |
+
spans["api"] = span
|
| 456 |
+
|
| 457 |
+
def capture_core_event(*args: Any, **kwargs: Any) -> None:
|
| 458 |
+
span = telemetry.current_telemetry_span()
|
| 459 |
+
assert span is not None
|
| 460 |
+
spans["core"] = span
|
| 461 |
+
|
| 462 |
+
monkeypatch.setattr(ctx_api, "_record_api_event", capture_api_event)
|
| 463 |
+
monkeypatch.setattr(core_tools, "_record_core_tool_event", capture_core_event)
|
| 464 |
+
monkeypatch.setattr(
|
| 465 |
+
ctx_api,
|
| 466 |
+
"_get_toolbox",
|
| 467 |
+
lambda: CtxCoreToolbox(wiki_dir=tmp_path / "wiki", graph_path=tmp_path / "graph.json"),
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
with pytest.raises(ValueError, match="unknown ctx-core tool"):
|
| 471 |
+
ctx_api._call("ctx__missing", {})
|
| 472 |
+
|
| 473 |
+
assert set(spans) == {"api", "core"}
|
| 474 |
+
assert spans["core"].trace_id == spans["api"].trace_id
|
| 475 |
+
assert spans["core"].span_id != spans["api"].span_id
|
| 476 |
+
assert spans["core"].parent_span_id == spans["api"].span_id
|
| 477 |
+
assert spans["api"].parent_span_id is None
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
def test_mcp_core_events_share_trace_context(
|
| 481 |
+
tmp_path: Path,
|
| 482 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 483 |
+
) -> None:
|
| 484 |
+
import ctx.adapters.generic.ctx_core_tools as core_tools
|
| 485 |
+
|
| 486 |
+
spans: dict[str, telemetry.TelemetrySpan] = {}
|
| 487 |
+
|
| 488 |
+
def capture_mcp_event(*args: Any, **kwargs: Any) -> None:
|
| 489 |
+
span = telemetry.current_telemetry_span()
|
| 490 |
+
assert span is not None
|
| 491 |
+
spans["mcp"] = span
|
| 492 |
+
|
| 493 |
+
def capture_core_event(*args: Any, **kwargs: Any) -> None:
|
| 494 |
+
span = telemetry.current_telemetry_span()
|
| 495 |
+
assert span is not None
|
| 496 |
+
spans["core"] = span
|
| 497 |
+
|
| 498 |
+
monkeypatch.setattr(mcp_server, "_record_mcp_request", capture_mcp_event)
|
| 499 |
+
monkeypatch.setattr(core_tools, "_record_core_tool_event", capture_core_event)
|
| 500 |
+
out = BytesIO()
|
| 501 |
+
frame = {
|
| 502 |
+
"jsonrpc": "2.0",
|
| 503 |
+
"id": 1,
|
| 504 |
+
"method": "tools/call",
|
| 505 |
+
"params": {"name": "ctx__missing", "arguments": {}},
|
| 506 |
+
}
|
| 507 |
+
|
| 508 |
+
mcp_server._process_line(json.dumps(frame), mcp_server._ServerState(), out)
|
| 509 |
+
|
| 510 |
+
response = json.loads(out.getvalue().decode("utf-8"))
|
| 511 |
+
assert response["result"]["isError"] is True
|
| 512 |
+
assert set(spans) == {"core", "mcp"}
|
| 513 |
+
assert spans["core"].trace_id == spans["mcp"].trace_id
|
| 514 |
+
assert spans["core"].span_id != spans["mcp"].span_id
|
| 515 |
+
assert spans["core"].parent_span_id == spans["mcp"].span_id
|
| 516 |
+
assert spans["mcp"].parent_span_id is None
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def test_record_event_returns_none_when_disabled(tmp_path: Path) -> None:
|
| 520 |
+
path = tmp_path / "events.jsonl"
|
| 521 |
+
|
| 522 |
+
event = record_event(
|
| 523 |
+
"session.started",
|
| 524 |
+
source="ctx-run",
|
| 525 |
+
path=path,
|
| 526 |
+
trusted_root=tmp_path,
|
| 527 |
+
config={"enabled": False, "path": str(path)},
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
assert event is None
|
| 531 |
+
assert not path.exists()
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def test_record_event_fails_closed_for_unknown_privacy_mode(
|
| 535 |
+
tmp_path: Path,
|
| 536 |
+
capsys: pytest.CaptureFixture[str],
|
| 537 |
+
) -> None:
|
| 538 |
+
path = tmp_path / "events.jsonl"
|
| 539 |
+
|
| 540 |
+
event = record_event(
|
| 541 |
+
"ctx.api.recommend_bundle",
|
| 542 |
+
source="ctx-api",
|
| 543 |
+
payload={"query": "private acme query"},
|
| 544 |
+
path=path,
|
| 545 |
+
trusted_root=tmp_path,
|
| 546 |
+
config={"mode": "debug_raw", "path": str(path)},
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
assert event is None
|
| 550 |
+
assert not path.exists()
|
| 551 |
+
assert "telemetry.mode must be one of" in capsys.readouterr().err
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
def test_record_event_can_export_to_local_jsonl(tmp_path: Path) -> None:
|
| 555 |
+
path = tmp_path / "events.jsonl"
|
| 556 |
+
export_path = tmp_path / "exported-events.jsonl"
|
| 557 |
+
|
| 558 |
+
event = record_event(
|
| 559 |
+
"ctx.api.recommend_bundle",
|
| 560 |
+
source="ctx-api",
|
| 561 |
+
payload={"query": "private acme query", "ctx.result.count": 1},
|
| 562 |
+
path=path,
|
| 563 |
+
trusted_root=tmp_path,
|
| 564 |
+
config={
|
| 565 |
+
"path": str(path),
|
| 566 |
+
"export": {
|
| 567 |
+
"enabled": True,
|
| 568 |
+
"sink": "local_jsonl",
|
| 569 |
+
"path": str(export_path),
|
| 570 |
+
},
|
| 571 |
+
},
|
| 572 |
+
)
|
| 573 |
+
|
| 574 |
+
assert event is not None
|
| 575 |
+
exported = json.loads(export_path.read_text(encoding="utf-8"))
|
| 576 |
+
assert exported["event_id"] == event.event_id
|
| 577 |
+
assert exported["event_name"] == "ctx.api.recommend_bundle"
|
| 578 |
+
assert "query" not in exported["payload"]
|
| 579 |
+
assert exported["payload"]["query_hash"].startswith("sha256:")
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
def test_record_event_creates_owner_only_local_files(tmp_path: Path) -> None:
|
| 583 |
+
if os.name == "nt":
|
| 584 |
+
pytest.skip("POSIX mode bits are not portable on Windows")
|
| 585 |
+
path = tmp_path / "events.jsonl"
|
| 586 |
+
export_path = tmp_path / "exported-events.jsonl"
|
| 587 |
+
|
| 588 |
+
record_event(
|
| 589 |
+
"ctx.api.recommend_bundle",
|
| 590 |
+
source="ctx-api",
|
| 591 |
+
path=path,
|
| 592 |
+
trusted_root=tmp_path,
|
| 593 |
+
config={
|
| 594 |
+
"path": str(path),
|
| 595 |
+
"export": {
|
| 596 |
+
"enabled": True,
|
| 597 |
+
"sink": "local_jsonl",
|
| 598 |
+
"path": str(export_path),
|
| 599 |
+
},
|
| 600 |
+
},
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
assert stat.S_IMODE(path.stat().st_mode) == 0o600
|
| 604 |
+
assert stat.S_IMODE(export_path.stat().st_mode) == 0o600
|
| 605 |
+
checkpoint_path = Path(str(path) + ".export-checkpoint.json")
|
| 606 |
+
assert stat.S_IMODE(checkpoint_path.stat().st_mode) == 0o600
|
| 607 |
+
status_path = Path(str(path) + ".export-status.json")
|
| 608 |
+
assert stat.S_IMODE(status_path.stat().st_mode) == 0o600
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def test_telemetry_export_cli_rejects_unknown_privacy_mode(
|
| 612 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 613 |
+
capsys: pytest.CaptureFixture[str],
|
| 614 |
+
) -> None:
|
| 615 |
+
monkeypatch.setattr(
|
| 616 |
+
telemetry_cli,
|
| 617 |
+
"_base_telemetry_config",
|
| 618 |
+
lambda: {"mode": "debug_raw", "export": {"enabled": True, "sink": "local_jsonl"}},
|
| 619 |
+
)
|
| 620 |
+
|
| 621 |
+
rc = telemetry_cli.main(["--dry-run", "--json"])
|
| 622 |
+
|
| 623 |
+
assert rc == 1
|
| 624 |
+
payload = json.loads(capsys.readouterr().out)
|
| 625 |
+
assert payload["failed"] == 1
|
| 626 |
+
assert "telemetry.mode must be one of" in payload["error"]
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def test_export_events_posts_otlp_http_payload(
|
| 630 |
+
tmp_path: Path,
|
| 631 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 632 |
+
) -> None:
|
| 633 |
+
path = tmp_path / "events.jsonl"
|
| 634 |
+
record_event(
|
| 635 |
+
"ctx.mcp.request",
|
| 636 |
+
source="ctx-mcp-server",
|
| 637 |
+
outcome="error",
|
| 638 |
+
session_id="sess-otlp-private",
|
| 639 |
+
error_kind="method_not_found",
|
| 640 |
+
payload={"rpc.method": "tools/call", "query": "private acme query"},
|
| 641 |
+
path=path,
|
| 642 |
+
trusted_root=tmp_path,
|
| 643 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 644 |
+
)
|
| 645 |
+
calls: list[tuple[dict[str, Any], dict[str, Any]]] = []
|
| 646 |
+
|
| 647 |
+
def fake_post_otlp_http(
|
| 648 |
+
payload: dict[str, Any],
|
| 649 |
+
settings: dict[str, Any],
|
| 650 |
+
) -> None:
|
| 651 |
+
calls.append((payload, settings))
|
| 652 |
+
|
| 653 |
+
monkeypatch.setattr(telemetry, "_post_otlp_http", fake_post_otlp_http)
|
| 654 |
+
|
| 655 |
+
result = export_events(
|
| 656 |
+
path,
|
| 657 |
+
trusted_root=tmp_path,
|
| 658 |
+
config={
|
| 659 |
+
"path": str(path),
|
| 660 |
+
"export": {
|
| 661 |
+
"enabled": True,
|
| 662 |
+
"sink": "otlp_http",
|
| 663 |
+
"otlp": {
|
| 664 |
+
"endpoint": "https://collector.example:4318/v1/logs",
|
| 665 |
+
"allowed_hosts": ["collector.example"],
|
| 666 |
+
"headers": {"Authorization": "Bearer token"},
|
| 667 |
+
"service_name": "ctx-test",
|
| 668 |
+
"service_namespace": "ctx",
|
| 669 |
+
"deployment_environment": "test",
|
| 670 |
+
},
|
| 671 |
+
},
|
| 672 |
+
},
|
| 673 |
+
)
|
| 674 |
+
|
| 675 |
+
assert result.exported == 1
|
| 676 |
+
assert result.failed == 0
|
| 677 |
+
assert result.sink == "otlp_http"
|
| 678 |
+
assert len(calls) == 1
|
| 679 |
+
payload, settings = calls[0]
|
| 680 |
+
assert settings["otlp_endpoint"] == "https://collector.example:4318/v1/logs"
|
| 681 |
+
assert settings["otlp_allowed_hosts"] == ["collector.example"]
|
| 682 |
+
resource_logs = payload["resourceLogs"]
|
| 683 |
+
assert isinstance(resource_logs, list)
|
| 684 |
+
log_record = resource_logs[0]["scopeLogs"][0]["logRecords"][0]
|
| 685 |
+
assert log_record["body"] == {"stringValue": "ctx.mcp.request"}
|
| 686 |
+
assert len(log_record["traceId"]) == 32
|
| 687 |
+
assert len(log_record["spanId"]) == 16
|
| 688 |
+
attributes = {
|
| 689 |
+
item["key"]: item["value"]
|
| 690 |
+
for item in log_record["attributes"]
|
| 691 |
+
}
|
| 692 |
+
assert attributes["event.name"] == {"stringValue": "ctx.mcp.request"}
|
| 693 |
+
assert attributes["ctx.outcome"] == {"stringValue": "error"}
|
| 694 |
+
assert attributes["error.type"] == {"stringValue": "method_not_found"}
|
| 695 |
+
assert "ctx.session_id" not in attributes
|
| 696 |
+
assert attributes["ctx.session.hash"]["stringValue"].startswith("sha256:")
|
| 697 |
+
assert attributes["ctx.version"]["stringValue"]
|
| 698 |
+
assert "ctx.payload.query_hash" in attributes
|
| 699 |
+
assert "private acme query" not in json.dumps(payload)
|
| 700 |
+
assert "sess-otlp-private" not in json.dumps(payload)
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
def test_export_events_hashes_legacy_session_id_for_otlp(
|
| 704 |
+
tmp_path: Path,
|
| 705 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 706 |
+
) -> None:
|
| 707 |
+
path = tmp_path / "events.jsonl"
|
| 708 |
+
path.write_text(
|
| 709 |
+
json.dumps(
|
| 710 |
+
{
|
| 711 |
+
"schema_version": SCHEMA_VERSION,
|
| 712 |
+
"event_id": "legacy-event",
|
| 713 |
+
"ts": "2026-06-28T00:00:00Z",
|
| 714 |
+
"event_name": "ctx.mcp.request",
|
| 715 |
+
"source": "ctx-mcp-server",
|
| 716 |
+
"outcome": "ok",
|
| 717 |
+
"session_id": "legacy-session-private",
|
| 718 |
+
"privacy_mode": "local_redacted",
|
| 719 |
+
"payload": {},
|
| 720 |
+
}
|
| 721 |
+
)
|
| 722 |
+
+ "\n",
|
| 723 |
+
encoding="utf-8",
|
| 724 |
+
)
|
| 725 |
+
calls: list[dict[str, Any]] = []
|
| 726 |
+
|
| 727 |
+
def fake_post_otlp_http(
|
| 728 |
+
payload: dict[str, Any],
|
| 729 |
+
settings: dict[str, Any],
|
| 730 |
+
) -> None:
|
| 731 |
+
calls.append(payload)
|
| 732 |
+
|
| 733 |
+
monkeypatch.setattr(telemetry, "_post_otlp_http", fake_post_otlp_http)
|
| 734 |
+
|
| 735 |
+
result = export_events(
|
| 736 |
+
path,
|
| 737 |
+
trusted_root=tmp_path,
|
| 738 |
+
config={
|
| 739 |
+
"path": str(path),
|
| 740 |
+
"privacy": {"hash_salt": "tenant-a"},
|
| 741 |
+
"export": {
|
| 742 |
+
"enabled": True,
|
| 743 |
+
"sink": "otlp_http",
|
| 744 |
+
"otlp": {
|
| 745 |
+
"endpoint": "https://collector.example:4318/v1/logs",
|
| 746 |
+
"allowed_hosts": ["collector.example"],
|
| 747 |
+
},
|
| 748 |
+
},
|
| 749 |
+
},
|
| 750 |
+
)
|
| 751 |
+
|
| 752 |
+
assert result.exported == 1
|
| 753 |
+
assert result.failed == 0
|
| 754 |
+
payload = calls[0]
|
| 755 |
+
log_record = payload["resourceLogs"][0]["scopeLogs"][0]["logRecords"][0]
|
| 756 |
+
attributes = {
|
| 757 |
+
item["key"]: item["value"]
|
| 758 |
+
for item in log_record["attributes"]
|
| 759 |
+
}
|
| 760 |
+
assert "ctx.session_id" not in attributes
|
| 761 |
+
assert attributes["ctx.session.hash"] == {
|
| 762 |
+
"stringValue": hash_identifier("legacy-session-private", salt="tenant-a")
|
| 763 |
+
}
|
| 764 |
+
assert "legacy-session-private" not in json.dumps(payload)
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
@pytest.mark.parametrize(
|
| 768 |
+
("endpoint", "match"),
|
| 769 |
+
[
|
| 770 |
+
("http://collector.example:4318/v1/logs", "must use https"),
|
| 771 |
+
("https://collector.example:4318/v1/logs", "allowed_hosts"),
|
| 772 |
+
("https://user:pass@collector.example/v1/logs", "must not include userinfo"),
|
| 773 |
+
("https://collector.example/v1/logs?token=x", "must not include query"),
|
| 774 |
+
("https://collector.example/v1/logs#fragment", "must not include query"),
|
| 775 |
+
("https://collector.example:bad/v1/logs", "invalid port"),
|
| 776 |
+
("ftp://collector.example/v1/logs", "must use http or https"),
|
| 777 |
+
("/v1/logs", "must use http or https"),
|
| 778 |
+
("https:///v1/logs", "must include a host"),
|
| 779 |
+
("https://169.254.169.254/v1/logs", "host is not allowed"),
|
| 780 |
+
("https://10.0.0.1/v1/logs", "host is not allowed"),
|
| 781 |
+
],
|
| 782 |
+
)
|
| 783 |
+
def test_export_events_rejects_unsafe_otlp_endpoints(
|
| 784 |
+
tmp_path: Path,
|
| 785 |
+
endpoint: str,
|
| 786 |
+
match: str,
|
| 787 |
+
) -> None:
|
| 788 |
+
path = tmp_path / "events.jsonl"
|
| 789 |
+
record_event(
|
| 790 |
+
"ctx.mcp.request",
|
| 791 |
+
source="ctx-mcp-server",
|
| 792 |
+
path=path,
|
| 793 |
+
trusted_root=tmp_path,
|
| 794 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 795 |
+
)
|
| 796 |
+
|
| 797 |
+
with pytest.raises(ValueError, match=match):
|
| 798 |
+
export_events(
|
| 799 |
+
path,
|
| 800 |
+
trusted_root=tmp_path,
|
| 801 |
+
config={
|
| 802 |
+
"path": str(path),
|
| 803 |
+
"export": {
|
| 804 |
+
"enabled": True,
|
| 805 |
+
"sink": "otlp_http",
|
| 806 |
+
"otlp": {"endpoint": endpoint},
|
| 807 |
+
},
|
| 808 |
+
},
|
| 809 |
+
)
|
| 810 |
+
|
| 811 |
+
|
| 812 |
+
@pytest.mark.parametrize(
|
| 813 |
+
"endpoint",
|
| 814 |
+
[
|
| 815 |
+
"http://localhost:4318/v1/logs",
|
| 816 |
+
"http://127.0.0.1:4318/v1/logs",
|
| 817 |
+
"http://[::1]:4318/v1/logs",
|
| 818 |
+
],
|
| 819 |
+
)
|
| 820 |
+
def test_export_events_allows_loopback_http_otlp(
|
| 821 |
+
tmp_path: Path,
|
| 822 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 823 |
+
endpoint: str,
|
| 824 |
+
) -> None:
|
| 825 |
+
path = tmp_path / "events.jsonl"
|
| 826 |
+
record_event(
|
| 827 |
+
"ctx.mcp.request",
|
| 828 |
+
source="ctx-mcp-server",
|
| 829 |
+
path=path,
|
| 830 |
+
trusted_root=tmp_path,
|
| 831 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 832 |
+
)
|
| 833 |
+
calls: list[tuple[dict[str, Any], dict[str, Any]]] = []
|
| 834 |
+
|
| 835 |
+
def fake_post_otlp_http(
|
| 836 |
+
payload: dict[str, Any],
|
| 837 |
+
settings: dict[str, Any],
|
| 838 |
+
) -> None:
|
| 839 |
+
calls.append((payload, settings))
|
| 840 |
+
|
| 841 |
+
monkeypatch.setattr(telemetry, "_post_otlp_http", fake_post_otlp_http)
|
| 842 |
+
|
| 843 |
+
result = export_events(
|
| 844 |
+
path,
|
| 845 |
+
trusted_root=tmp_path,
|
| 846 |
+
config={
|
| 847 |
+
"path": str(path),
|
| 848 |
+
"export": {
|
| 849 |
+
"enabled": True,
|
| 850 |
+
"sink": "otlp_http",
|
| 851 |
+
"otlp": {"endpoint": endpoint},
|
| 852 |
+
},
|
| 853 |
+
},
|
| 854 |
+
)
|
| 855 |
+
|
| 856 |
+
assert result.exported == 1
|
| 857 |
+
assert result.failed == 0
|
| 858 |
+
assert calls[0][1]["otlp_endpoint"] == endpoint
|
| 859 |
+
|
| 860 |
+
|
| 861 |
+
def test_export_events_applies_otlp_policy_to_env_overrides(
|
| 862 |
+
tmp_path: Path,
|
| 863 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 864 |
+
) -> None:
|
| 865 |
+
path = tmp_path / "events.jsonl"
|
| 866 |
+
record_event(
|
| 867 |
+
"ctx.mcp.request",
|
| 868 |
+
source="ctx-mcp-server",
|
| 869 |
+
path=path,
|
| 870 |
+
trusted_root=tmp_path,
|
| 871 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 872 |
+
)
|
| 873 |
+
|
| 874 |
+
monkeypatch.setenv("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", "http://collector.example/v1/logs")
|
| 875 |
+
|
| 876 |
+
with pytest.raises(ValueError, match="must use https"):
|
| 877 |
+
export_events(
|
| 878 |
+
path,
|
| 879 |
+
trusted_root=tmp_path,
|
| 880 |
+
config={
|
| 881 |
+
"path": str(path),
|
| 882 |
+
"export": {
|
| 883 |
+
"enabled": True,
|
| 884 |
+
"sink": "otlp_http",
|
| 885 |
+
"otlp": {
|
| 886 |
+
"endpoint": "https://collector.example/v1/logs",
|
| 887 |
+
"allowed_hosts": ["collector.example"],
|
| 888 |
+
},
|
| 889 |
+
},
|
| 890 |
+
},
|
| 891 |
+
)
|
| 892 |
+
|
| 893 |
+
|
| 894 |
+
def test_export_events_appends_logs_path_for_otlp_base_env(
|
| 895 |
+
tmp_path: Path,
|
| 896 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 897 |
+
) -> None:
|
| 898 |
+
path = tmp_path / "events.jsonl"
|
| 899 |
+
record_event(
|
| 900 |
+
"ctx.mcp.request",
|
| 901 |
+
source="ctx-mcp-server",
|
| 902 |
+
path=path,
|
| 903 |
+
trusted_root=tmp_path,
|
| 904 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 905 |
+
)
|
| 906 |
+
calls: list[tuple[dict[str, Any], dict[str, Any]]] = []
|
| 907 |
+
|
| 908 |
+
def fake_post_otlp_http(
|
| 909 |
+
payload: dict[str, Any],
|
| 910 |
+
settings: dict[str, Any],
|
| 911 |
+
) -> None:
|
| 912 |
+
calls.append((payload, settings))
|
| 913 |
+
|
| 914 |
+
monkeypatch.setattr(telemetry, "_post_otlp_http", fake_post_otlp_http)
|
| 915 |
+
monkeypatch.delenv("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", raising=False)
|
| 916 |
+
monkeypatch.setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "https://collector.example")
|
| 917 |
+
|
| 918 |
+
result = export_events(
|
| 919 |
+
path,
|
| 920 |
+
trusted_root=tmp_path,
|
| 921 |
+
config={
|
| 922 |
+
"path": str(path),
|
| 923 |
+
"export": {
|
| 924 |
+
"enabled": True,
|
| 925 |
+
"sink": "otlp_http",
|
| 926 |
+
"otlp": {"allowed_hosts": ["collector.example"]},
|
| 927 |
+
},
|
| 928 |
+
},
|
| 929 |
+
)
|
| 930 |
+
|
| 931 |
+
assert result.exported == 1
|
| 932 |
+
assert result.failed == 0
|
| 933 |
+
assert calls[0][1]["otlp_endpoint"] == "https://collector.example/v1/logs"
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
def test_local_jsonl_export_ignores_unused_invalid_otlp_endpoint(tmp_path: Path) -> None:
|
| 937 |
+
path = tmp_path / "events.jsonl"
|
| 938 |
+
export_path = tmp_path / "exported-events.jsonl"
|
| 939 |
+
record_event(
|
| 940 |
+
"ctx.mcp.request",
|
| 941 |
+
source="ctx-mcp-server",
|
| 942 |
+
path=path,
|
| 943 |
+
trusted_root=tmp_path,
|
| 944 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 945 |
+
)
|
| 946 |
+
|
| 947 |
+
result = export_events(
|
| 948 |
+
path,
|
| 949 |
+
trusted_root=tmp_path,
|
| 950 |
+
config={
|
| 951 |
+
"path": str(path),
|
| 952 |
+
"export": {
|
| 953 |
+
"enabled": True,
|
| 954 |
+
"sink": "local_jsonl",
|
| 955 |
+
"path": str(export_path),
|
| 956 |
+
"otlp": {"endpoint": "ftp://collector.example/v1/logs"},
|
| 957 |
+
},
|
| 958 |
+
},
|
| 959 |
+
)
|
| 960 |
+
|
| 961 |
+
assert result.exported == 1
|
| 962 |
+
assert result.failed == 0
|
| 963 |
+
assert export_path.is_file()
|
| 964 |
+
|
| 965 |
+
|
| 966 |
+
def test_otlp_redirect_handler_rejects_redirects() -> None:
|
| 967 |
+
handler = telemetry._NoRedirectHandler()
|
| 968 |
+
redirect_request: Any = handler.redirect_request
|
| 969 |
+
|
| 970 |
+
assert redirect_request(None, None, 302, "Found", {}, "https://collector.example") is None
|
| 971 |
+
|
| 972 |
+
|
| 973 |
+
def test_export_events_checkpoint_skips_already_exported_events(tmp_path: Path) -> None:
|
| 974 |
+
path = tmp_path / "events.jsonl"
|
| 975 |
+
export_path = tmp_path / "exported-events.jsonl"
|
| 976 |
+
checkpoint_path = tmp_path / "checkpoint.json"
|
| 977 |
+
config = {
|
| 978 |
+
"path": str(path),
|
| 979 |
+
"export": {
|
| 980 |
+
"enabled": True,
|
| 981 |
+
"sink": "local_jsonl",
|
| 982 |
+
"path": str(export_path),
|
| 983 |
+
"checkpoint_path": str(checkpoint_path),
|
| 984 |
+
},
|
| 985 |
+
}
|
| 986 |
+
for name in ("ctx.api.recommend_bundle", "ctx.mcp.request"):
|
| 987 |
+
record_event(
|
| 988 |
+
name,
|
| 989 |
+
source="ctx-test",
|
| 990 |
+
path=path,
|
| 991 |
+
trusted_root=tmp_path,
|
| 992 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 993 |
+
)
|
| 994 |
+
|
| 995 |
+
first = export_events(path, trusted_root=tmp_path, config=config)
|
| 996 |
+
|
| 997 |
+
assert first.attempted == 2
|
| 998 |
+
assert first.exported == 2
|
| 999 |
+
assert first.status == "ok"
|
| 1000 |
+
assert first.checkpoint_advanced is True
|
| 1001 |
+
assert first.last_event_id is not None
|
| 1002 |
+
assert checkpoint_path.is_file()
|
| 1003 |
+
assert len(export_path.read_text(encoding="utf-8").splitlines()) == 2
|
| 1004 |
+
|
| 1005 |
+
second = export_events(path, trusted_root=tmp_path, config=config)
|
| 1006 |
+
|
| 1007 |
+
assert second.attempted == 0
|
| 1008 |
+
assert second.exported == 0
|
| 1009 |
+
assert second.status == "noop"
|
| 1010 |
+
assert second.checkpoint_advanced is False
|
| 1011 |
+
assert second.checkpoint_before_event_id == first.last_event_id
|
| 1012 |
+
assert second.checkpoint_after_event_id == first.last_event_id
|
| 1013 |
+
assert second.last_event_id == first.last_event_id
|
| 1014 |
+
assert len(export_path.read_text(encoding="utf-8").splitlines()) == 2
|
| 1015 |
+
status_path = Path(str(path) + ".export-status.json")
|
| 1016 |
+
status = json.loads(status_path.read_text(encoding="utf-8"))
|
| 1017 |
+
assert status["schema_version"] == EXPORT_STATUS_SCHEMA_VERSION
|
| 1018 |
+
assert status["status"] == "noop"
|
| 1019 |
+
assert status["checkpoint_advanced"] is False
|
| 1020 |
+
assert status["checkpoint_before_event_id"] == first.last_event_id
|
| 1021 |
+
assert status["checkpoint_after_event_id"] == first.last_event_id
|
| 1022 |
+
|
| 1023 |
+
record_event(
|
| 1024 |
+
"ctx.cli.run",
|
| 1025 |
+
source="ctx-test",
|
| 1026 |
+
path=path,
|
| 1027 |
+
trusted_root=tmp_path,
|
| 1028 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 1029 |
+
)
|
| 1030 |
+
third = export_events(path, trusted_root=tmp_path, config=config)
|
| 1031 |
+
|
| 1032 |
+
assert third.attempted == 1
|
| 1033 |
+
assert third.exported == 1
|
| 1034 |
+
assert third.last_event_id != first.last_event_id
|
| 1035 |
+
assert len(export_path.read_text(encoding="utf-8").splitlines()) == 3
|
| 1036 |
+
|
| 1037 |
+
replay = export_events(
|
| 1038 |
+
path,
|
| 1039 |
+
trusted_root=tmp_path,
|
| 1040 |
+
config=config,
|
| 1041 |
+
include_exported=True,
|
| 1042 |
+
)
|
| 1043 |
+
|
| 1044 |
+
assert replay.attempted == 3
|
| 1045 |
+
assert replay.exported == 3
|
| 1046 |
+
assert len(export_path.read_text(encoding="utf-8").splitlines()) == 6
|
| 1047 |
+
|
| 1048 |
+
|
| 1049 |
+
def test_export_events_ignores_checkpoint_for_different_destination(tmp_path: Path) -> None:
|
| 1050 |
+
path = tmp_path / "events.jsonl"
|
| 1051 |
+
export_path_a = tmp_path / "exported-a.jsonl"
|
| 1052 |
+
export_path_b = tmp_path / "exported-b.jsonl"
|
| 1053 |
+
checkpoint_path = tmp_path / "checkpoint.json"
|
| 1054 |
+
record_event(
|
| 1055 |
+
"ctx.api.recommend_bundle",
|
| 1056 |
+
source="ctx-api",
|
| 1057 |
+
path=path,
|
| 1058 |
+
trusted_root=tmp_path,
|
| 1059 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 1060 |
+
)
|
| 1061 |
+
config_a = {
|
| 1062 |
+
"path": str(path),
|
| 1063 |
+
"export": {
|
| 1064 |
+
"enabled": True,
|
| 1065 |
+
"sink": "local_jsonl",
|
| 1066 |
+
"path": str(export_path_a),
|
| 1067 |
+
"checkpoint_path": str(checkpoint_path),
|
| 1068 |
+
},
|
| 1069 |
+
}
|
| 1070 |
+
config_b = {
|
| 1071 |
+
"path": str(path),
|
| 1072 |
+
"export": {
|
| 1073 |
+
"enabled": True,
|
| 1074 |
+
"sink": "local_jsonl",
|
| 1075 |
+
"path": str(export_path_b),
|
| 1076 |
+
"checkpoint_path": str(checkpoint_path),
|
| 1077 |
+
},
|
| 1078 |
+
}
|
| 1079 |
+
|
| 1080 |
+
first = export_events(path, trusted_root=tmp_path, config=config_a)
|
| 1081 |
+
second = export_events(path, trusted_root=tmp_path, config=config_b)
|
| 1082 |
+
|
| 1083 |
+
assert first.exported == 1
|
| 1084 |
+
assert second.attempted == 1
|
| 1085 |
+
assert second.exported == 1
|
| 1086 |
+
assert second.checkpoint_before_event_id is None
|
| 1087 |
+
assert second.checkpoint_advanced is True
|
| 1088 |
+
assert len(export_path_b.read_text(encoding="utf-8").splitlines()) == 1
|
| 1089 |
+
|
| 1090 |
+
|
| 1091 |
+
def test_export_events_writes_status_with_malformed_count(
|
| 1092 |
+
tmp_path: Path,
|
| 1093 |
+
capsys: pytest.CaptureFixture[str],
|
| 1094 |
+
) -> None:
|
| 1095 |
+
path = tmp_path / "events.jsonl"
|
| 1096 |
+
export_path = tmp_path / "exported-events.jsonl"
|
| 1097 |
+
event = record_event(
|
| 1098 |
+
"ctx.api.recommend_bundle",
|
| 1099 |
+
source="ctx-api",
|
| 1100 |
+
path=path,
|
| 1101 |
+
trusted_root=tmp_path,
|
| 1102 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 1103 |
+
)
|
| 1104 |
+
assert event is not None
|
| 1105 |
+
with path.open("a", encoding="utf-8") as fh:
|
| 1106 |
+
fh.write("{not valid json}\n")
|
| 1107 |
+
status_path = Path(str(path) + ".export-status.json")
|
| 1108 |
+
|
| 1109 |
+
result = export_events(
|
| 1110 |
+
path,
|
| 1111 |
+
trusted_root=tmp_path,
|
| 1112 |
+
config={
|
| 1113 |
+
"path": str(path),
|
| 1114 |
+
"export": {
|
| 1115 |
+
"enabled": True,
|
| 1116 |
+
"sink": "local_jsonl",
|
| 1117 |
+
"path": str(export_path),
|
| 1118 |
+
},
|
| 1119 |
+
},
|
| 1120 |
+
)
|
| 1121 |
+
|
| 1122 |
+
assert result.attempted == 1
|
| 1123 |
+
assert result.exported == 1
|
| 1124 |
+
assert result.failed == 0
|
| 1125 |
+
assert result.status == "degraded"
|
| 1126 |
+
assert result.malformed_records == 1
|
| 1127 |
+
assert result.malformed_pending_records == 1
|
| 1128 |
+
assert result.malformed_first_line == 2
|
| 1129 |
+
assert result.malformed_last_line == 2
|
| 1130 |
+
assert result.checkpoint_advanced is False
|
| 1131 |
+
assert result.last_event_id is None
|
| 1132 |
+
assert result.last_success_event_id == event.event_id
|
| 1133 |
+
assert result.status_path == str(status_path)
|
| 1134 |
+
assert not Path(str(path) + ".export-checkpoint.json").exists()
|
| 1135 |
+
status = json.loads(status_path.read_text(encoding="utf-8"))
|
| 1136 |
+
assert status["schema_version"] == EXPORT_STATUS_SCHEMA_VERSION
|
| 1137 |
+
assert status["status"] == "degraded"
|
| 1138 |
+
assert status["attempted"] == 1
|
| 1139 |
+
assert status["exported"] == 1
|
| 1140 |
+
assert status["failed"] == 0
|
| 1141 |
+
assert status["malformed_records"] == 1
|
| 1142 |
+
assert status["malformed_total_records"] == 1
|
| 1143 |
+
assert status["malformed_pending_records"] == 1
|
| 1144 |
+
assert status["malformed_first_line"] == 2
|
| 1145 |
+
assert status["malformed_last_line"] == 2
|
| 1146 |
+
assert status["checkpoint_advanced"] is False
|
| 1147 |
+
assert status["checkpoint_before_event_id"] is None
|
| 1148 |
+
assert status["checkpoint_after_event_id"] is None
|
| 1149 |
+
assert status["last_success_event_id"] == event.event_id
|
| 1150 |
+
assert status["destination_hash"].startswith("sha256:")
|
| 1151 |
+
assert "skipping malformed event" in capsys.readouterr().err
|
| 1152 |
+
|
| 1153 |
+
|
| 1154 |
+
def test_export_events_writes_failure_status_without_checkpoint(
|
| 1155 |
+
tmp_path: Path,
|
| 1156 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 1157 |
+
) -> None:
|
| 1158 |
+
path = tmp_path / "events.jsonl"
|
| 1159 |
+
event = record_event(
|
| 1160 |
+
"ctx.mcp.request",
|
| 1161 |
+
source="ctx-mcp-server",
|
| 1162 |
+
path=path,
|
| 1163 |
+
trusted_root=tmp_path,
|
| 1164 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 1165 |
+
)
|
| 1166 |
+
assert event is not None
|
| 1167 |
+
checkpoint_path = Path(str(path) + ".export-checkpoint.json")
|
| 1168 |
+
status_path = Path(str(path) + ".export-status.json")
|
| 1169 |
+
|
| 1170 |
+
def fake_post_otlp_http(
|
| 1171 |
+
payload: dict[str, Any],
|
| 1172 |
+
settings: dict[str, Any],
|
| 1173 |
+
) -> None:
|
| 1174 |
+
raise RuntimeError("collector unavailable")
|
| 1175 |
+
|
| 1176 |
+
monkeypatch.setattr(telemetry, "_post_otlp_http", fake_post_otlp_http)
|
| 1177 |
+
|
| 1178 |
+
result = export_events(
|
| 1179 |
+
path,
|
| 1180 |
+
trusted_root=tmp_path,
|
| 1181 |
+
config={
|
| 1182 |
+
"path": str(path),
|
| 1183 |
+
"export": {
|
| 1184 |
+
"enabled": True,
|
| 1185 |
+
"sink": "otlp_http",
|
| 1186 |
+
"otlp": {"endpoint": "http://127.0.0.1:4318/v1/logs"},
|
| 1187 |
+
},
|
| 1188 |
+
},
|
| 1189 |
+
)
|
| 1190 |
+
|
| 1191 |
+
assert result.attempted == 1
|
| 1192 |
+
assert result.exported == 0
|
| 1193 |
+
assert result.failed == 1
|
| 1194 |
+
assert result.status == "failed"
|
| 1195 |
+
assert result.error_kind == "RuntimeError"
|
| 1196 |
+
assert result.checkpoint_advanced is False
|
| 1197 |
+
assert result.malformed_pending_records == 0
|
| 1198 |
+
assert result.status_path == str(status_path)
|
| 1199 |
+
assert not checkpoint_path.exists()
|
| 1200 |
+
status = json.loads(status_path.read_text(encoding="utf-8"))
|
| 1201 |
+
assert status["schema_version"] == EXPORT_STATUS_SCHEMA_VERSION
|
| 1202 |
+
assert status["status"] == "failed"
|
| 1203 |
+
assert status["attempted"] == 1
|
| 1204 |
+
assert status["exported"] == 0
|
| 1205 |
+
assert status["failed"] == 1
|
| 1206 |
+
assert status["error_kind"] == "RuntimeError"
|
| 1207 |
+
assert status["last_event_id"] is None
|
| 1208 |
+
assert status["checkpoint_advanced"] is False
|
| 1209 |
+
assert status["malformed_pending_records"] == 0
|
| 1210 |
+
assert status["destination_hash"].startswith("sha256:")
|
| 1211 |
+
|
| 1212 |
+
|
| 1213 |
+
def test_telemetry_export_cli_writes_local_jsonl(
|
| 1214 |
+
tmp_path: Path,
|
| 1215 |
+
capsys: pytest.CaptureFixture[str],
|
| 1216 |
+
) -> None:
|
| 1217 |
+
path = tmp_path / "events.jsonl"
|
| 1218 |
+
export_path = tmp_path / "exported-events.jsonl"
|
| 1219 |
+
record_event(
|
| 1220 |
+
"ctx.api.recommend_bundle",
|
| 1221 |
+
source="ctx-api",
|
| 1222 |
+
payload={"query": "private acme query", "ctx.result.count": 1},
|
| 1223 |
+
path=path,
|
| 1224 |
+
trusted_root=tmp_path,
|
| 1225 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 1226 |
+
)
|
| 1227 |
+
|
| 1228 |
+
rc = telemetry_cli.main(
|
| 1229 |
+
[
|
| 1230 |
+
"--path",
|
| 1231 |
+
str(path),
|
| 1232 |
+
"--trusted-root",
|
| 1233 |
+
str(tmp_path),
|
| 1234 |
+
"--sink",
|
| 1235 |
+
"local_jsonl",
|
| 1236 |
+
"--output",
|
| 1237 |
+
str(export_path),
|
| 1238 |
+
"--json",
|
| 1239 |
+
]
|
| 1240 |
+
)
|
| 1241 |
+
|
| 1242 |
+
assert rc == 0
|
| 1243 |
+
summary = json.loads(capsys.readouterr().out)
|
| 1244 |
+
assert summary["attempted"] == 1
|
| 1245 |
+
assert summary["error_kind"] is None
|
| 1246 |
+
assert summary["exported"] == 1
|
| 1247 |
+
assert summary["failed"] == 0
|
| 1248 |
+
assert summary["sink"] == "local_jsonl"
|
| 1249 |
+
assert summary["status"] == "ok"
|
| 1250 |
+
assert summary["checkpoint_path"] == str(path) + ".export-checkpoint.json"
|
| 1251 |
+
assert summary["checkpoint_before_event_id"] is None
|
| 1252 |
+
assert summary["checkpoint_after_event_id"] == summary["last_event_id"]
|
| 1253 |
+
assert summary["checkpoint_advanced"] is True
|
| 1254 |
+
assert summary["checkpoint_found"] is False
|
| 1255 |
+
assert summary["malformed_records"] == 0
|
| 1256 |
+
assert summary["malformed_pending_records"] == 0
|
| 1257 |
+
assert summary["destination_hash"].startswith("sha256:")
|
| 1258 |
+
assert summary["last_success_event_id"] == summary["last_event_id"]
|
| 1259 |
+
assert summary["status_path"] == str(path) + ".export-status.json"
|
| 1260 |
+
exported = json.loads(export_path.read_text(encoding="utf-8"))
|
| 1261 |
+
assert summary["last_event_id"] == exported["event_id"]
|
| 1262 |
+
assert exported["event_name"] == "ctx.api.recommend_bundle"
|
| 1263 |
+
assert "query" not in exported["payload"]
|
| 1264 |
+
assert "private acme query" not in json.dumps(exported)
|
| 1265 |
+
|
| 1266 |
+
|
| 1267 |
+
def test_telemetry_export_cli_writes_metric_local_jsonl(
|
| 1268 |
+
tmp_path: Path,
|
| 1269 |
+
capsys: pytest.CaptureFixture[str],
|
| 1270 |
+
) -> None:
|
| 1271 |
+
path = tmp_path / "metrics.jsonl"
|
| 1272 |
+
export_path = tmp_path / "exported-metrics.jsonl"
|
| 1273 |
+
metric = record_counter(
|
| 1274 |
+
"ctx.api.requests",
|
| 1275 |
+
attributes={"ctx.source": "api", "query": "private acme query"},
|
| 1276 |
+
path=path,
|
| 1277 |
+
trusted_root=tmp_path,
|
| 1278 |
+
config={"metrics": {"enabled": True, "path": str(path)}},
|
| 1279 |
+
)
|
| 1280 |
+
assert metric is not None
|
| 1281 |
+
|
| 1282 |
+
rc = telemetry_cli.main(
|
| 1283 |
+
[
|
| 1284 |
+
"--signal",
|
| 1285 |
+
"metrics",
|
| 1286 |
+
"--path",
|
| 1287 |
+
str(path),
|
| 1288 |
+
"--trusted-root",
|
| 1289 |
+
str(tmp_path),
|
| 1290 |
+
"--sink",
|
| 1291 |
+
"local_jsonl",
|
| 1292 |
+
"--output",
|
| 1293 |
+
str(export_path),
|
| 1294 |
+
"--json",
|
| 1295 |
+
]
|
| 1296 |
+
)
|
| 1297 |
+
|
| 1298 |
+
assert rc == 0
|
| 1299 |
+
summary = json.loads(capsys.readouterr().out)
|
| 1300 |
+
assert summary["signal"] == "metrics"
|
| 1301 |
+
assert summary["attempted"] == 1
|
| 1302 |
+
assert summary["exported"] == 1
|
| 1303 |
+
assert summary["failed"] == 0
|
| 1304 |
+
assert summary["status"] == "ok"
|
| 1305 |
+
assert summary["checkpoint_path"] == str(path) + ".export-checkpoint.json"
|
| 1306 |
+
assert summary["checkpoint_after_metric_id"] == summary["last_metric_id"]
|
| 1307 |
+
assert summary["last_success_metric_id"] == summary["last_metric_id"]
|
| 1308 |
+
assert summary["status_path"] == str(path) + ".export-status.json"
|
| 1309 |
+
exported = json.loads(export_path.read_text(encoding="utf-8"))
|
| 1310 |
+
assert exported["schema_version"] == METRIC_SCHEMA_VERSION
|
| 1311 |
+
assert exported["metric_id"] == summary["last_metric_id"]
|
| 1312 |
+
assert "query" not in exported["attributes"]
|
| 1313 |
+
assert "private acme query" not in json.dumps(exported)
|
| 1314 |
+
|
| 1315 |
+
|
| 1316 |
+
def test_telemetry_export_cli_allows_remote_otlp_host(
|
| 1317 |
+
tmp_path: Path,
|
| 1318 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 1319 |
+
capsys: pytest.CaptureFixture[str],
|
| 1320 |
+
) -> None:
|
| 1321 |
+
path = tmp_path / "events.jsonl"
|
| 1322 |
+
record_event(
|
| 1323 |
+
"ctx.mcp.request",
|
| 1324 |
+
source="ctx-mcp-server",
|
| 1325 |
+
path=path,
|
| 1326 |
+
trusted_root=tmp_path,
|
| 1327 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 1328 |
+
)
|
| 1329 |
+
calls: list[dict[str, Any]] = []
|
| 1330 |
+
|
| 1331 |
+
def fake_post_otlp_http(
|
| 1332 |
+
payload: dict[str, Any],
|
| 1333 |
+
settings: dict[str, Any],
|
| 1334 |
+
) -> None:
|
| 1335 |
+
calls.append(settings)
|
| 1336 |
+
|
| 1337 |
+
monkeypatch.setattr(telemetry, "_post_otlp_http", fake_post_otlp_http)
|
| 1338 |
+
|
| 1339 |
+
rc = telemetry_cli.main(
|
| 1340 |
+
[
|
| 1341 |
+
"--path",
|
| 1342 |
+
str(path),
|
| 1343 |
+
"--trusted-root",
|
| 1344 |
+
str(tmp_path),
|
| 1345 |
+
"--sink",
|
| 1346 |
+
"otlp_http",
|
| 1347 |
+
"--otlp-endpoint",
|
| 1348 |
+
"https://collector.example:4318/v1/logs",
|
| 1349 |
+
"--otlp-allowed-host",
|
| 1350 |
+
"collector.example",
|
| 1351 |
+
"--json",
|
| 1352 |
+
]
|
| 1353 |
+
)
|
| 1354 |
+
|
| 1355 |
+
assert rc == 0
|
| 1356 |
+
summary = json.loads(capsys.readouterr().out)
|
| 1357 |
+
assert summary["exported"] == 1
|
| 1358 |
+
assert summary["failed"] == 0
|
| 1359 |
+
assert summary["sink"] == "otlp_http"
|
| 1360 |
+
assert summary["status"] == "ok"
|
| 1361 |
+
assert len(calls) == 1
|
| 1362 |
+
assert calls[0]["otlp_endpoint"] == "https://collector.example:4318/v1/logs"
|
| 1363 |
+
assert calls[0]["otlp_allowed_hosts"] == ["collector.example"]
|
| 1364 |
+
|
| 1365 |
+
|
| 1366 |
+
def test_telemetry_export_cli_can_fail_on_degraded_status(
|
| 1367 |
+
tmp_path: Path,
|
| 1368 |
+
capsys: pytest.CaptureFixture[str],
|
| 1369 |
+
) -> None:
|
| 1370 |
+
path = tmp_path / "events.jsonl"
|
| 1371 |
+
export_path = tmp_path / "exported-events.jsonl"
|
| 1372 |
+
record_event(
|
| 1373 |
+
"ctx.api.recommend_bundle",
|
| 1374 |
+
source="ctx-api",
|
| 1375 |
+
path=path,
|
| 1376 |
+
trusted_root=tmp_path,
|
| 1377 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 1378 |
+
)
|
| 1379 |
+
with path.open("a", encoding="utf-8") as fh:
|
| 1380 |
+
fh.write("not-json\n")
|
| 1381 |
+
|
| 1382 |
+
rc = telemetry_cli.main(
|
| 1383 |
+
[
|
| 1384 |
+
"--path",
|
| 1385 |
+
str(path),
|
| 1386 |
+
"--trusted-root",
|
| 1387 |
+
str(tmp_path),
|
| 1388 |
+
"--sink",
|
| 1389 |
+
"local_jsonl",
|
| 1390 |
+
"--output",
|
| 1391 |
+
str(export_path),
|
| 1392 |
+
"--fail-on-degraded",
|
| 1393 |
+
"--json",
|
| 1394 |
+
]
|
| 1395 |
+
)
|
| 1396 |
+
|
| 1397 |
+
assert rc == 1
|
| 1398 |
+
summary = json.loads(capsys.readouterr().out)
|
| 1399 |
+
assert summary["exported"] == 1
|
| 1400 |
+
assert summary["failed"] == 0
|
| 1401 |
+
assert summary["status"] == "degraded"
|
| 1402 |
+
assert summary["malformed_pending_records"] == 1
|
| 1403 |
+
assert summary["checkpoint_advanced"] is False
|
| 1404 |
+
|
| 1405 |
+
|
| 1406 |
+
def test_telemetry_export_cli_dry_run_counts_events(
|
| 1407 |
+
tmp_path: Path,
|
| 1408 |
+
capsys: pytest.CaptureFixture[str],
|
| 1409 |
+
) -> None:
|
| 1410 |
+
path = tmp_path / "events.jsonl"
|
| 1411 |
+
event = record_event(
|
| 1412 |
+
"ctx.cli.run",
|
| 1413 |
+
source="ctx-cli",
|
| 1414 |
+
path=path,
|
| 1415 |
+
trusted_root=tmp_path,
|
| 1416 |
+
config={"path": str(path), "export": {"enabled": False}},
|
| 1417 |
+
)
|
| 1418 |
+
assert event is not None
|
| 1419 |
+
|
| 1420 |
+
rc = telemetry_cli.main(
|
| 1421 |
+
[
|
| 1422 |
+
"--path",
|
| 1423 |
+
str(path),
|
| 1424 |
+
"--trusted-root",
|
| 1425 |
+
str(tmp_path),
|
| 1426 |
+
"--sink",
|
| 1427 |
+
"local_jsonl",
|
| 1428 |
+
"--dry-run",
|
| 1429 |
+
"--json",
|
| 1430 |
+
]
|
| 1431 |
+
)
|
| 1432 |
+
|
| 1433 |
+
assert rc == 0
|
| 1434 |
+
summary = json.loads(capsys.readouterr().out)
|
| 1435 |
+
assert summary["attempted"] == 1
|
| 1436 |
+
assert summary["dry_run"] is True
|
| 1437 |
+
assert summary["exported"] == 0
|
| 1438 |
+
assert summary["failed"] == 0
|
| 1439 |
+
assert summary["sink"] == "local_jsonl"
|
| 1440 |
+
assert summary["status"] == "ok"
|
| 1441 |
+
assert summary["checkpoint_advanced"] is False
|
| 1442 |
+
assert summary["last_event_id"] == event.event_id
|
| 1443 |
+
assert summary["malformed_records"] == 0
|
| 1444 |
+
assert summary["malformed_pending_records"] == 0
|
| 1445 |
+
assert summary["destination_hash"].startswith("sha256:")
|
| 1446 |
+
assert summary["status_path"] == str(path) + ".export-status.json"
|
| 1447 |
+
assert not Path(summary["status_path"]).exists()
|
| 1448 |
+
|
| 1449 |
+
|
| 1450 |
+
def test_hash_identifier_is_stable_and_saltable(monkeypatch: pytest.MonkeyPatch) -> None:
|
| 1451 |
+
monkeypatch.setenv("CTX_TELEMETRY_HASH_SALT", "tenant-a")
|
| 1452 |
+
|
| 1453 |
+
assert hash_identifier("repo") == hash_identifier("repo")
|
| 1454 |
+
assert hash_identifier("repo") != hash_identifier("other")
|
| 1455 |
+
assert hash_identifier("repo", salt="tenant-a") != hash_identifier("repo", salt="tenant-b")
|
| 1456 |
+
|
| 1457 |
+
|
| 1458 |
+
def test_hash_identifier_uses_env_salt(monkeypatch: pytest.MonkeyPatch) -> None:
|
| 1459 |
+
monkeypatch.setenv("CTX_TELEMETRY_HASH_SALT", "tenant-a")
|
| 1460 |
+
tenant_a = hash_identifier("repo")
|
| 1461 |
+
|
| 1462 |
+
monkeypatch.setenv("CTX_TELEMETRY_HASH_SALT", "tenant-b")
|
| 1463 |
+
|
| 1464 |
+
assert hash_identifier("repo") != tenant_a
|
| 1465 |
+
assert hash_identifier("repo", salt="explicit") == hash_identifier("repo", salt="explicit")
|
| 1466 |
+
|
| 1467 |
+
|
| 1468 |
+
def test_hash_identifier_generates_owner_only_local_salt(
|
| 1469 |
+
tmp_path: Path,
|
| 1470 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 1471 |
+
) -> None:
|
| 1472 |
+
salt_path = tmp_path / "hash-salt"
|
| 1473 |
+
monkeypatch.delenv("CTX_TELEMETRY_HASH_SALT", raising=False)
|
| 1474 |
+
monkeypatch.setattr(
|
| 1475 |
+
telemetry,
|
| 1476 |
+
"_config_get",
|
| 1477 |
+
lambda key, default: (
|
| 1478 |
+
{"privacy": {"hash_salt_path": str(salt_path)}} if key == "telemetry" else default
|
| 1479 |
+
),
|
| 1480 |
+
)
|
| 1481 |
+
|
| 1482 |
+
first = hash_identifier("repo")
|
| 1483 |
+
|
| 1484 |
+
assert salt_path.is_file()
|
| 1485 |
+
assert salt_path.read_text(encoding="utf-8").strip()
|
| 1486 |
+
assert hash_identifier("repo") == first
|
| 1487 |
+
if os.name != "nt":
|
| 1488 |
+
assert stat.S_IMODE(salt_path.stat().st_mode) == 0o600
|
| 1489 |
+
|
| 1490 |
+
|
| 1491 |
+
def test_record_event_hashes_with_configured_salt(tmp_path: Path) -> None:
|
| 1492 |
+
path_a = tmp_path / "tenant-a.jsonl"
|
| 1493 |
+
path_b = tmp_path / "tenant-b.jsonl"
|
| 1494 |
+
|
| 1495 |
+
event_a = record_event(
|
| 1496 |
+
"ctx.api.recommend_bundle",
|
| 1497 |
+
source="ctx-api",
|
| 1498 |
+
repo="/Users/example/private-repo",
|
| 1499 |
+
payload={"query": "private acme query"},
|
| 1500 |
+
path=path_a,
|
| 1501 |
+
trusted_root=tmp_path,
|
| 1502 |
+
config={"path": str(path_a), "privacy": {"hash_salt": "tenant-a"}},
|
| 1503 |
+
)
|
| 1504 |
+
event_b = record_event(
|
| 1505 |
+
"ctx.api.recommend_bundle",
|
| 1506 |
+
source="ctx-api",
|
| 1507 |
+
repo="/Users/example/private-repo",
|
| 1508 |
+
payload={"query": "private acme query"},
|
| 1509 |
+
path=path_b,
|
| 1510 |
+
trusted_root=tmp_path,
|
| 1511 |
+
config={"path": str(path_b), "privacy": {"hash_salt": "tenant-b"}},
|
| 1512 |
+
)
|
| 1513 |
+
|
| 1514 |
+
assert event_a is not None
|
| 1515 |
+
assert event_b is not None
|
| 1516 |
+
assert event_a.repo_hash != event_b.repo_hash
|
| 1517 |
+
assert event_a.payload["query_hash"] != event_b.payload["query_hash"]
|
| 1518 |
+
|
| 1519 |
+
|
| 1520 |
+
def test_nested_payload_hashing_uses_configured_salt(tmp_path: Path) -> None:
|
| 1521 |
+
path_a = tmp_path / "tenant-a.jsonl"
|
| 1522 |
+
path_b = tmp_path / "tenant-b.jsonl"
|
| 1523 |
+
|
| 1524 |
+
event_a = record_event(
|
| 1525 |
+
"ctx.api.recommend_bundle",
|
| 1526 |
+
source="ctx-api",
|
| 1527 |
+
payload={"nested": {"query": "private nested query"}},
|
| 1528 |
+
path=path_a,
|
| 1529 |
+
trusted_root=tmp_path,
|
| 1530 |
+
config={"path": str(path_a), "privacy": {"hash_salt": "tenant-a"}},
|
| 1531 |
+
)
|
| 1532 |
+
event_b = record_event(
|
| 1533 |
+
"ctx.api.recommend_bundle",
|
| 1534 |
+
source="ctx-api",
|
| 1535 |
+
payload={"nested": {"query": "private nested query"}},
|
| 1536 |
+
path=path_b,
|
| 1537 |
+
trusted_root=tmp_path,
|
| 1538 |
+
config={"path": str(path_b), "privacy": {"hash_salt": "tenant-b"}},
|
| 1539 |
+
)
|
| 1540 |
+
|
| 1541 |
+
assert event_a is not None
|
| 1542 |
+
assert event_b is not None
|
| 1543 |
+
assert event_a.payload["nested"]["query_hash"].startswith("sha256:")
|
| 1544 |
+
assert event_b.payload["nested"]["query_hash"].startswith("sha256:")
|
| 1545 |
+
assert event_a.payload["nested"]["query_hash"] != event_b.payload["nested"]["query_hash"]
|
| 1546 |
+
assert "private nested query" not in path_a.read_text(encoding="utf-8")
|
| 1547 |
+
assert "private nested query" not in path_b.read_text(encoding="utf-8")
|
| 1548 |
+
|
| 1549 |
+
|
| 1550 |
+
def test_record_exception_hashes_message_and_stack_for_otlp(
|
| 1551 |
+
tmp_path: Path,
|
| 1552 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 1553 |
+
) -> None:
|
| 1554 |
+
path = tmp_path / "events.jsonl"
|
| 1555 |
+
config = {"path": str(path), "privacy": {"hash_salt": "tenant-a"}}
|
| 1556 |
+
monkeypatch.setattr(telemetry, "record_event", record_event)
|
| 1557 |
+
|
| 1558 |
+
try:
|
| 1559 |
+
raise RuntimeError("private acme failure at /Users/example/private-repo")
|
| 1560 |
+
except RuntimeError as exc:
|
| 1561 |
+
payload = exception_payload(exc, config=config)
|
| 1562 |
+
event = record_exception(
|
| 1563 |
+
"ctx.api.recommend_bundle",
|
| 1564 |
+
source="ctx-api",
|
| 1565 |
+
exc=exc,
|
| 1566 |
+
payload={"query": "private acme query"},
|
| 1567 |
+
path=path,
|
| 1568 |
+
trusted_root=tmp_path,
|
| 1569 |
+
config=config,
|
| 1570 |
+
)
|
| 1571 |
+
|
| 1572 |
+
assert event is not None
|
| 1573 |
+
assert payload["ctx.exception.message_hash"].startswith("sha256:")
|
| 1574 |
+
assert payload["ctx.exception.stack_hash"].startswith("sha256:")
|
| 1575 |
+
assert event.payload["ctx.exception.message_hash"] == payload["ctx.exception.message_hash"]
|
| 1576 |
+
assert event.payload["ctx.exception.stack_hash"] == payload["ctx.exception.stack_hash"]
|
| 1577 |
+
local_text = path.read_text(encoding="utf-8")
|
| 1578 |
+
assert "private acme failure" not in local_text
|
| 1579 |
+
assert "/Users/example/private-repo" not in local_text
|
| 1580 |
+
assert "private acme query" not in local_text
|
| 1581 |
+
|
| 1582 |
+
calls: list[dict[str, Any]] = []
|
| 1583 |
+
|
| 1584 |
+
def fake_post_otlp_http(
|
| 1585 |
+
otlp_payload: dict[str, Any],
|
| 1586 |
+
settings: dict[str, Any],
|
| 1587 |
+
) -> None:
|
| 1588 |
+
calls.append(otlp_payload)
|
| 1589 |
+
|
| 1590 |
+
monkeypatch.setattr(telemetry, "_post_otlp_http", fake_post_otlp_http)
|
| 1591 |
+
result = export_events(
|
| 1592 |
+
path,
|
| 1593 |
+
trusted_root=tmp_path,
|
| 1594 |
+
config={
|
| 1595 |
+
"path": str(path),
|
| 1596 |
+
"privacy": {"hash_salt": "tenant-a"},
|
| 1597 |
+
"export": {
|
| 1598 |
+
"enabled": True,
|
| 1599 |
+
"sink": "otlp_http",
|
| 1600 |
+
"otlp": {
|
| 1601 |
+
"endpoint": "https://collector.example:4318/v1/logs",
|
| 1602 |
+
"allowed_hosts": ["collector.example"],
|
| 1603 |
+
},
|
| 1604 |
+
},
|
| 1605 |
+
},
|
| 1606 |
+
)
|
| 1607 |
+
|
| 1608 |
+
assert result.exported == 1
|
| 1609 |
+
otlp_text = json.dumps(calls[0])
|
| 1610 |
+
assert "private acme failure" not in otlp_text
|
| 1611 |
+
assert "/Users/example/private-repo" not in otlp_text
|
| 1612 |
+
assert "private acme query" not in otlp_text
|
| 1613 |
+
assert "ctx.payload.ctx.exception.message_hash" in otlp_text
|
| 1614 |
+
assert "ctx.payload.ctx.exception.stack_hash" in otlp_text
|
| 1615 |
+
|
| 1616 |
+
|
| 1617 |
+
def test_api_and_core_exceptions_record_hashed_payloads(
|
| 1618 |
+
tmp_path: Path,
|
| 1619 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 1620 |
+
) -> None:
|
| 1621 |
+
import ctx.adapters.generic.ctx_core_tools as core_tools
|
| 1622 |
+
|
| 1623 |
+
path = tmp_path / "events.jsonl"
|
| 1624 |
+
_redirect_real_event_telemetry(monkeypatch, path)
|
| 1625 |
+
|
| 1626 |
+
toolbox = CtxCoreToolbox(wiki_dir=tmp_path / "wiki", graph_path=tmp_path / "graph.json")
|
| 1627 |
+
|
| 1628 |
+
def fail_recommend(args: dict[str, Any]) -> dict[str, Any]:
|
| 1629 |
+
raise RuntimeError("private core failure for /Users/example/private-repo")
|
| 1630 |
+
|
| 1631 |
+
monkeypatch.setattr(toolbox, "_dispatch_recommend", fail_recommend)
|
| 1632 |
+
with pytest.raises(RuntimeError):
|
| 1633 |
+
toolbox.dispatch(
|
| 1634 |
+
core_tools.ToolCall(
|
| 1635 |
+
id="core",
|
| 1636 |
+
name="ctx__recommend_bundle",
|
| 1637 |
+
arguments={"query": "private core query"},
|
| 1638 |
+
)
|
| 1639 |
+
)
|
| 1640 |
+
|
| 1641 |
+
class FailingToolbox:
|
| 1642 |
+
def dispatch(self, call: Any) -> str:
|
| 1643 |
+
raise RuntimeError("private api failure for /Users/example/private-repo")
|
| 1644 |
+
|
| 1645 |
+
monkeypatch.setattr(ctx_api, "_get_toolbox", lambda: FailingToolbox())
|
| 1646 |
+
with pytest.raises(RuntimeError):
|
| 1647 |
+
ctx_api._call("ctx__recommend_bundle", {"query": "private api query"})
|
| 1648 |
+
|
| 1649 |
+
events = list(read_events(path, trusted_root=tmp_path))
|
| 1650 |
+
by_source = {event.source: event for event in events}
|
| 1651 |
+
assert {"ctx-core", "ctx-api"} <= set(by_source)
|
| 1652 |
+
for event in by_source.values():
|
| 1653 |
+
assert event.payload["ctx.exception.message_hash"].startswith("sha256:")
|
| 1654 |
+
assert event.payload["ctx.exception.stack_hash"].startswith("sha256:")
|
| 1655 |
+
assert event.payload["ctx.exception.escaped"] is True
|
| 1656 |
+
raw = path.read_text(encoding="utf-8")
|
| 1657 |
+
assert "private core failure" not in raw
|
| 1658 |
+
assert "private api failure" not in raw
|
| 1659 |
+
assert "private core query" not in raw
|
| 1660 |
+
assert "private api query" not in raw
|
| 1661 |
+
assert "/Users/example/private-repo" not in raw
|
| 1662 |
+
|
| 1663 |
+
|
| 1664 |
+
def test_mcp_handler_exception_records_hashed_payload_and_sanitized_response(
|
| 1665 |
+
tmp_path: Path,
|
| 1666 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 1667 |
+
) -> None:
|
| 1668 |
+
path = tmp_path / "events.jsonl"
|
| 1669 |
+
_redirect_real_event_telemetry(monkeypatch, path)
|
| 1670 |
+
|
| 1671 |
+
def boom(state: Any, params: dict[str, Any]) -> dict[str, Any]:
|
| 1672 |
+
raise RuntimeError("private mcp failure for /Users/example/private-repo")
|
| 1673 |
+
|
| 1674 |
+
monkeypatch.setitem(mcp_server._HANDLERS, "boom", boom)
|
| 1675 |
+
out = BytesIO()
|
| 1676 |
+
frame = {"jsonrpc": "2.0", "id": 1, "method": "boom", "params": {}}
|
| 1677 |
+
|
| 1678 |
+
mcp_server._process_line(json.dumps(frame), mcp_server._ServerState(), out)
|
| 1679 |
+
|
| 1680 |
+
response = json.loads(out.getvalue().decode("utf-8"))
|
| 1681 |
+
assert response["error"]["code"] == -32603
|
| 1682 |
+
assert response["error"]["message"] == "internal error: RuntimeError"
|
| 1683 |
+
assert "private mcp failure" not in json.dumps(response)
|
| 1684 |
+
event = next(read_events(path, trusted_root=tmp_path))
|
| 1685 |
+
assert event.event_name == "ctx.mcp.request"
|
| 1686 |
+
assert event.payload["ctx.exception.message_hash"].startswith("sha256:")
|
| 1687 |
+
assert event.payload["ctx.exception.stack_hash"].startswith("sha256:")
|
| 1688 |
+
raw = path.read_text(encoding="utf-8")
|
| 1689 |
+
assert "private mcp failure" not in raw
|
| 1690 |
+
assert "/Users/example/private-repo" not in raw
|
| 1691 |
+
|
| 1692 |
+
|
| 1693 |
+
def _write_event_record(path: Path, event_id: str, ts: str) -> None:
|
| 1694 |
+
event = TelemetryEvent(
|
| 1695 |
+
schema_version=SCHEMA_VERSION,
|
| 1696 |
+
event_id=event_id,
|
| 1697 |
+
ts=ts,
|
| 1698 |
+
event_name="ctx.api.recommend_bundle",
|
| 1699 |
+
source="ctx-api",
|
| 1700 |
+
payload={"ctx.result.count": 1},
|
| 1701 |
+
)
|
| 1702 |
+
with path.open("a", encoding="utf-8") as fh:
|
| 1703 |
+
fh.write(json.dumps(asdict(event), separators=(",", ":")) + "\n")
|
| 1704 |
+
|
| 1705 |
+
|
| 1706 |
+
def _write_metric_record(path: Path, metric_id: str, ts: str) -> None:
|
| 1707 |
+
metric = TelemetryMetric(
|
| 1708 |
+
schema_version=METRIC_SCHEMA_VERSION,
|
| 1709 |
+
metric_id=metric_id,
|
| 1710 |
+
ts=ts,
|
| 1711 |
+
name="ctx.api.duration",
|
| 1712 |
+
instrument="histogram",
|
| 1713 |
+
value=42.0,
|
| 1714 |
+
unit="ms",
|
| 1715 |
+
attributes={"ctx.source": "api"},
|
| 1716 |
+
)
|
| 1717 |
+
with path.open("a", encoding="utf-8") as fh:
|
| 1718 |
+
fh.write(json.dumps(asdict(metric), separators=(",", ":")) + "\n")
|
| 1719 |
+
|
| 1720 |
+
|
| 1721 |
+
def test_plan_telemetry_retention_does_not_mutate_spool(tmp_path: Path) -> None:
|
| 1722 |
+
path = tmp_path / "events.jsonl"
|
| 1723 |
+
status_path = tmp_path / "retention-status.json"
|
| 1724 |
+
for index in range(4):
|
| 1725 |
+
_write_event_record(path, f"event-{index}", f"2026-01-0{index + 1}T00:00:00Z")
|
| 1726 |
+
before = path.read_text(encoding="utf-8")
|
| 1727 |
+
|
| 1728 |
+
results = plan_telemetry_retention(
|
| 1729 |
+
signal="events",
|
| 1730 |
+
event_path=path,
|
| 1731 |
+
trusted_root=tmp_path,
|
| 1732 |
+
config={
|
| 1733 |
+
"path": str(path),
|
| 1734 |
+
"retention": {
|
| 1735 |
+
"enabled": True,
|
| 1736 |
+
"status_path": str(status_path),
|
| 1737 |
+
"min_keep_records": 1,
|
| 1738 |
+
"events": {"max_records": 2},
|
| 1739 |
+
},
|
| 1740 |
+
},
|
| 1741 |
+
)
|
| 1742 |
+
|
| 1743 |
+
assert len(results) == 1
|
| 1744 |
+
result = results[0]
|
| 1745 |
+
assert result.signal == "events"
|
| 1746 |
+
assert result.status == "planned"
|
| 1747 |
+
assert result.dry_run is True
|
| 1748 |
+
assert result.scanned_records == 4
|
| 1749 |
+
assert result.retained_records == 2
|
| 1750 |
+
assert result.dropped_records == 2
|
| 1751 |
+
assert result.status_path == str(status_path)
|
| 1752 |
+
assert path.read_text(encoding="utf-8") == before
|
| 1753 |
+
assert not status_path.exists()
|
| 1754 |
+
|
| 1755 |
+
|
| 1756 |
+
def test_enforce_telemetry_retention_prunes_events_and_preserves_malformed(
|
| 1757 |
+
tmp_path: Path,
|
| 1758 |
+
) -> None:
|
| 1759 |
+
path = tmp_path / "events.jsonl"
|
| 1760 |
+
status_path = tmp_path / "retention-status.json"
|
| 1761 |
+
for index in range(3):
|
| 1762 |
+
_write_event_record(path, f"event-{index}", f"2026-01-0{index + 1}T00:00:00Z")
|
| 1763 |
+
with path.open("a", encoding="utf-8") as fh:
|
| 1764 |
+
fh.write("not-json\n")
|
| 1765 |
+
|
| 1766 |
+
results = enforce_telemetry_retention(
|
| 1767 |
+
signal="events",
|
| 1768 |
+
event_path=path,
|
| 1769 |
+
trusted_root=tmp_path,
|
| 1770 |
+
config={
|
| 1771 |
+
"path": str(path),
|
| 1772 |
+
"retention": {
|
| 1773 |
+
"enabled": True,
|
| 1774 |
+
"status_path": str(status_path),
|
| 1775 |
+
"min_keep_records": 1,
|
| 1776 |
+
"drop_malformed": False,
|
| 1777 |
+
"events": {"max_records": 2},
|
| 1778 |
+
},
|
| 1779 |
+
},
|
| 1780 |
+
)
|
| 1781 |
+
|
| 1782 |
+
assert len(results) == 1
|
| 1783 |
+
result = results[0]
|
| 1784 |
+
assert result.status == "pruned"
|
| 1785 |
+
assert result.dry_run is False
|
| 1786 |
+
assert result.scanned_records == 3
|
| 1787 |
+
assert result.retained_records == 2
|
| 1788 |
+
assert result.dropped_records == 1
|
| 1789 |
+
assert result.malformed_records == 1
|
| 1790 |
+
assert result.malformed_dropped_records == 0
|
| 1791 |
+
assert [event.event_id for event in read_events(path, trusted_root=tmp_path)] == [
|
| 1792 |
+
"event-1",
|
| 1793 |
+
"event-2",
|
| 1794 |
+
]
|
| 1795 |
+
assert "not-json" in path.read_text(encoding="utf-8")
|
| 1796 |
+
status = json.loads(status_path.read_text(encoding="utf-8"))
|
| 1797 |
+
assert status["schema_version"] == RETENTION_STATUS_SCHEMA_VERSION
|
| 1798 |
+
assert status["results"][0]["signal"] == "events"
|
| 1799 |
+
assert status["results"][0]["status"] == "pruned"
|
| 1800 |
+
if os.name != "nt":
|
| 1801 |
+
assert stat.S_IMODE(status_path.stat().st_mode) == 0o600
|
| 1802 |
+
|
| 1803 |
+
|
| 1804 |
+
def test_enforce_telemetry_retention_prunes_metrics_and_can_drop_malformed(
|
| 1805 |
+
tmp_path: Path,
|
| 1806 |
+
) -> None:
|
| 1807 |
+
path = tmp_path / "metrics.jsonl"
|
| 1808 |
+
status_path = tmp_path / "retention-status.json"
|
| 1809 |
+
_write_metric_record(path, "metric-1", "2026-01-01T00:00:00Z")
|
| 1810 |
+
_write_metric_record(path, "metric-2", "2026-01-02T00:00:00Z")
|
| 1811 |
+
with path.open("a", encoding="utf-8") as fh:
|
| 1812 |
+
fh.write("not-json\n")
|
| 1813 |
+
|
| 1814 |
+
results = enforce_telemetry_retention(
|
| 1815 |
+
signal="metrics",
|
| 1816 |
+
metrics_path=path,
|
| 1817 |
+
trusted_root=tmp_path,
|
| 1818 |
+
drop_malformed=True,
|
| 1819 |
+
config={
|
| 1820 |
+
"metrics": {"enabled": True, "path": str(path)},
|
| 1821 |
+
"retention": {
|
| 1822 |
+
"enabled": True,
|
| 1823 |
+
"status_path": str(status_path),
|
| 1824 |
+
"min_keep_records": 0,
|
| 1825 |
+
"metrics": {"max_records": 1},
|
| 1826 |
+
},
|
| 1827 |
+
},
|
| 1828 |
+
)
|
| 1829 |
+
|
| 1830 |
+
assert len(results) == 1
|
| 1831 |
+
result = results[0]
|
| 1832 |
+
assert result.signal == "metrics"
|
| 1833 |
+
assert result.status == "pruned"
|
| 1834 |
+
assert result.retained_records == 1
|
| 1835 |
+
assert result.dropped_records == 1
|
| 1836 |
+
assert result.malformed_records == 1
|
| 1837 |
+
assert result.malformed_dropped_records == 1
|
| 1838 |
+
assert [metric.metric_id for metric in read_metrics(path, trusted_root=tmp_path)] == [
|
| 1839 |
+
"metric-2"
|
| 1840 |
+
]
|
| 1841 |
+
assert "not-json" not in path.read_text(encoding="utf-8")
|
| 1842 |
+
status = json.loads(status_path.read_text(encoding="utf-8"))
|
| 1843 |
+
assert status["results"][0]["signal"] == "metrics"
|
| 1844 |
+
|
| 1845 |
+
|
| 1846 |
+
def test_telemetry_retention_cli_plans_then_enforces(
|
| 1847 |
+
tmp_path: Path,
|
| 1848 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 1849 |
+
capsys: pytest.CaptureFixture[str],
|
| 1850 |
+
) -> None:
|
| 1851 |
+
path = tmp_path / "events.jsonl"
|
| 1852 |
+
status_path = tmp_path / "retention-status.json"
|
| 1853 |
+
_write_event_record(path, "event-1", "2026-01-01T00:00:00Z")
|
| 1854 |
+
_write_event_record(path, "event-2", "2026-01-02T00:00:00Z")
|
| 1855 |
+
monkeypatch.setattr(
|
| 1856 |
+
telemetry_cli,
|
| 1857 |
+
"_base_telemetry_config",
|
| 1858 |
+
lambda: {
|
| 1859 |
+
"path": str(path),
|
| 1860 |
+
"retention": {
|
| 1861 |
+
"enabled": True,
|
| 1862 |
+
"status_path": str(status_path),
|
| 1863 |
+
"min_keep_records": 0,
|
| 1864 |
+
"events": {"max_records": 1},
|
| 1865 |
+
},
|
| 1866 |
+
},
|
| 1867 |
+
)
|
| 1868 |
+
|
| 1869 |
+
plan_rc = telemetry_cli.retention_main(
|
| 1870 |
+
[
|
| 1871 |
+
"plan",
|
| 1872 |
+
"--signal",
|
| 1873 |
+
"events",
|
| 1874 |
+
"--event-path",
|
| 1875 |
+
str(path),
|
| 1876 |
+
"--trusted-root",
|
| 1877 |
+
str(tmp_path),
|
| 1878 |
+
"--json",
|
| 1879 |
+
]
|
| 1880 |
+
)
|
| 1881 |
+
|
| 1882 |
+
assert plan_rc == 0
|
| 1883 |
+
plan = json.loads(capsys.readouterr().out)
|
| 1884 |
+
assert plan["dry_run"] is True
|
| 1885 |
+
assert plan["results"][0]["status"] == "planned"
|
| 1886 |
+
assert [event.event_id for event in read_events(path, trusted_root=tmp_path)] == [
|
| 1887 |
+
"event-1",
|
| 1888 |
+
"event-2",
|
| 1889 |
+
]
|
| 1890 |
+
|
| 1891 |
+
enforce_rc = telemetry_cli.retention_main(
|
| 1892 |
+
[
|
| 1893 |
+
"enforce",
|
| 1894 |
+
"--signal",
|
| 1895 |
+
"events",
|
| 1896 |
+
"--event-path",
|
| 1897 |
+
str(path),
|
| 1898 |
+
"--trusted-root",
|
| 1899 |
+
str(tmp_path),
|
| 1900 |
+
"--json",
|
| 1901 |
+
]
|
| 1902 |
+
)
|
| 1903 |
+
|
| 1904 |
+
assert enforce_rc == 0
|
| 1905 |
+
enforced = json.loads(capsys.readouterr().out)
|
| 1906 |
+
assert enforced["dry_run"] is False
|
| 1907 |
+
assert enforced["results"][0]["status"] == "pruned"
|
| 1908 |
+
assert enforced["results"][0]["dropped_records"] == 1
|
| 1909 |
+
assert [event.event_id for event in read_events(path, trusted_root=tmp_path)] == [
|
| 1910 |
+
"event-2"
|
| 1911 |
+
]
|
| 1912 |
+
assert json.loads(status_path.read_text(encoding="utf-8"))["schema_version"] == (
|
| 1913 |
+
RETENTION_STATUS_SCHEMA_VERSION
|
| 1914 |
+
)
|
| 1915 |
+
|
| 1916 |
+
|
| 1917 |
+
def test_event_rejects_invalid_schema_and_negative_duration() -> None:
|
| 1918 |
+
with pytest.raises(ValueError, match="unsupported telemetry schema"):
|
| 1919 |
+
TelemetryEvent(
|
| 1920 |
+
schema_version="wrong",
|
| 1921 |
+
event_id="e1",
|
| 1922 |
+
ts="2026-06-28T00:00:00Z",
|
| 1923 |
+
event_name="session.started",
|
| 1924 |
+
source="ctx-run",
|
| 1925 |
+
)
|
| 1926 |
+
with pytest.raises(ValueError, match="duration_ms"):
|
| 1927 |
+
TelemetryEvent(
|
| 1928 |
+
schema_version=SCHEMA_VERSION,
|
| 1929 |
+
event_id="e1",
|
| 1930 |
+
ts="2026-06-28T00:00:00Z",
|
| 1931 |
+
event_name="session.started",
|
| 1932 |
+
source="ctx-run",
|
| 1933 |
+
duration_ms=-1,
|
| 1934 |
+
)
|
| 1935 |
+
with pytest.raises(ValueError, match="privacy_mode"):
|
| 1936 |
+
TelemetryEvent(
|
| 1937 |
+
schema_version=SCHEMA_VERSION,
|
| 1938 |
+
event_id="e1",
|
| 1939 |
+
ts="2026-06-28T00:00:00Z",
|
| 1940 |
+
event_name="session.started",
|
| 1941 |
+
source="ctx-run",
|
| 1942 |
+
privacy_mode="debug_raw",
|
| 1943 |
+
)
|
| 1944 |
+
with pytest.raises(ValueError, match="session_hash"):
|
| 1945 |
+
TelemetryEvent(
|
| 1946 |
+
schema_version=SCHEMA_VERSION,
|
| 1947 |
+
event_id="e1",
|
| 1948 |
+
ts="2026-06-28T00:00:00Z",
|
| 1949 |
+
event_name="session.started",
|
| 1950 |
+
source="ctx-run",
|
| 1951 |
+
session_hash="sess-raw",
|
| 1952 |
+
)
|
| 1953 |
+
|
| 1954 |
+
|
| 1955 |
+
def test_path_containment_rejects_escape(tmp_path: Path) -> None:
|
| 1956 |
+
with pytest.raises(ValueError, match="escapes"):
|
| 1957 |
+
record_event(
|
| 1958 |
+
"session.started",
|
| 1959 |
+
source="ctx-run",
|
| 1960 |
+
path=tmp_path / ".." / "events.jsonl",
|
| 1961 |
+
trusted_root=tmp_path,
|
| 1962 |
+
config={"path": str(tmp_path / "events.jsonl")},
|
| 1963 |
+
)
|
| 1964 |
+
|
| 1965 |
+
|
| 1966 |
+
def test_default_config_declares_local_only_export_disabled() -> None:
|
| 1967 |
+
for path in (Path("src/config.json"), Path("src/ctx/config.json")):
|
| 1968 |
+
data = json.loads(path.read_text(encoding="utf-8"))
|
| 1969 |
+
telemetry = data["telemetry"]
|
| 1970 |
+
assert telemetry["enabled"] is True
|
| 1971 |
+
assert telemetry["mode"] == "local_redacted"
|
| 1972 |
+
assert telemetry["path"] == "~/.ctx/telemetry/events.jsonl"
|
| 1973 |
+
assert telemetry["export"]["enabled"] is False
|
| 1974 |
+
assert telemetry["export"]["sink"] == "otlp_http"
|
| 1975 |
+
assert telemetry["export"]["path"] == "~/.ctx/telemetry/exported-events.jsonl"
|
| 1976 |
+
assert telemetry["export"]["otlp"]["endpoint"] == "http://localhost:4318/v1/logs"
|
| 1977 |
+
assert telemetry["export"]["otlp"]["allowed_hosts"] == []
|
| 1978 |
+
assert telemetry["metrics"]["enabled"] is True
|
| 1979 |
+
assert telemetry["metrics"]["path"] == "~/.ctx/telemetry/metrics.jsonl"
|
| 1980 |
+
assert telemetry["metrics"]["export"]["enabled"] is False
|
| 1981 |
+
assert telemetry["metrics"]["export"]["sink"] == "otlp_http"
|
| 1982 |
+
assert telemetry["metrics"]["export"]["path"] == "~/.ctx/telemetry/exported-metrics.jsonl"
|
| 1983 |
+
assert telemetry["metrics"]["export"]["otlp"]["endpoint"] == (
|
| 1984 |
+
"http://localhost:4318/v1/metrics"
|
| 1985 |
+
)
|
| 1986 |
+
assert telemetry["metrics"]["export"]["otlp"]["allowed_hosts"] == []
|
| 1987 |
+
assert telemetry["privacy"]["store_raw_inputs"] is False
|
| 1988 |
+
assert telemetry["privacy"]["hash_identifiers"] is True
|
| 1989 |
+
assert telemetry["privacy"]["hash_salt_env"] == "CTX_TELEMETRY_HASH_SALT"
|
| 1990 |
+
assert telemetry["privacy"]["hash_salt_path"] == "~/.ctx/telemetry/hash-salt"
|
| 1991 |
+
assert telemetry["retention"]["enabled"] is True
|
| 1992 |
+
assert telemetry["retention"]["status_path"] == (
|
| 1993 |
+
"~/.ctx/telemetry/retention-status.json"
|
| 1994 |
+
)
|
| 1995 |
+
assert telemetry["retention"]["min_keep_records"] == 1000
|
| 1996 |
+
assert telemetry["retention"]["drop_malformed"] is False
|
| 1997 |
+
assert telemetry["retention"]["events"]["max_age_days"] == 90
|
| 1998 |
+
assert telemetry["retention"]["events"]["max_records"] == 100000
|
| 1999 |
+
assert telemetry["retention"]["metrics"]["max_age_days"] == 30
|
| 2000 |
+
assert telemetry["retention"]["metrics"]["max_records"] == 200000
|
src/tests/test_feature_user_story_tracker.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import csv
|
| 4 |
+
import sys
|
| 5 |
+
import tomllib
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import yaml
|
| 9 |
+
from yaml.nodes import ScalarNode
|
| 10 |
+
|
| 11 |
+
repo_root = Path(__file__).resolve().parents[2]
|
| 12 |
+
sys.path.insert(0, str(repo_root / "src"))
|
| 13 |
+
|
| 14 |
+
import ctx # noqa: E402
|
| 15 |
+
import ctx.api as ctx_api # noqa: E402
|
| 16 |
+
from ctx.monitor import routes as monitor_routes # noqa: E402
|
| 17 |
+
|
| 18 |
+
TRACKER = repo_root / "docs" / "qa" / "feature-user-story-status.csv"
|
| 19 |
+
DASHBOARD_TRACKER = repo_root / "docs" / "qa" / "dashboard-user-story-status.csv"
|
| 20 |
+
MKDOCS = repo_root / "mkdocs.yml"
|
| 21 |
+
README = repo_root / "README.md"
|
| 22 |
+
PASS_STATUSES = {"Tested Pass", "Retested Pass"}
|
| 23 |
+
VALIDATION_STATUSES = {"Needs Validation"}
|
| 24 |
+
FIX_STATUSES = {"Needs Fix"}
|
| 25 |
+
ACTIONABLE_STATUSES = PASS_STATUSES | VALIDATION_STATUSES | FIX_STATUSES
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _tracker_rows() -> list[dict[str, str]]:
|
| 29 |
+
with TRACKER.open(newline="", encoding="utf-8") as f:
|
| 30 |
+
return list(csv.DictReader(f))
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _tracker_text() -> str:
|
| 34 |
+
return "\n".join(" ".join(row.values()) for row in _tracker_rows())
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _row_text(row: dict[str, str]) -> str:
|
| 38 |
+
return " ".join(value for value in row.values() if value)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _rows_for_surface(rows: list[dict[str, str]], surface: str) -> list[dict[str, str]]:
|
| 42 |
+
return [row for row in rows if row["surface"] == surface]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class _MkDocsNavLoader(yaml.SafeLoader):
|
| 46 |
+
pass
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _mkdocs_python_name(
|
| 50 |
+
loader: _MkDocsNavLoader,
|
| 51 |
+
suffix: str, # noqa: ARG001
|
| 52 |
+
node: yaml.Node,
|
| 53 |
+
) -> str:
|
| 54 |
+
if not isinstance(node, ScalarNode):
|
| 55 |
+
raise TypeError(f"Expected scalar YAML node, got {type(node).__name__}")
|
| 56 |
+
return loader.construct_scalar(node)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
_MkDocsNavLoader.add_multi_constructor(
|
| 60 |
+
"tag:yaml.org,2002:python/name:",
|
| 61 |
+
_mkdocs_python_name,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _nav_markdown_paths(nav_items: list[object]) -> list[str]:
|
| 66 |
+
paths: list[str] = []
|
| 67 |
+
for item in nav_items:
|
| 68 |
+
if isinstance(item, str):
|
| 69 |
+
paths.append(item)
|
| 70 |
+
elif isinstance(item, dict):
|
| 71 |
+
for value in item.values():
|
| 72 |
+
if isinstance(value, str):
|
| 73 |
+
paths.append(value)
|
| 74 |
+
elif isinstance(value, list):
|
| 75 |
+
paths.extend(_nav_markdown_paths(value))
|
| 76 |
+
return [path for path in paths if path.endswith(".md")]
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _mkdocs_nav_markdown_paths() -> list[str]:
|
| 80 |
+
config = yaml.load(
|
| 81 |
+
MKDOCS.read_text(encoding="utf-8"),
|
| 82 |
+
Loader=_MkDocsNavLoader,
|
| 83 |
+
)
|
| 84 |
+
docs_dir = config.get("docs_dir", "docs")
|
| 85 |
+
nav = config["nav"]
|
| 86 |
+
return list(dict.fromkeys(f"{docs_dir}/{path}" for path in _nav_markdown_paths(nav)))
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def test_feature_user_story_tracker_has_no_empty_core_fields() -> None:
|
| 90 |
+
rows = _tracker_rows()
|
| 91 |
+
assert rows
|
| 92 |
+
required = (
|
| 93 |
+
"feature_id",
|
| 94 |
+
"surface",
|
| 95 |
+
"feature",
|
| 96 |
+
"entrypoint_or_route",
|
| 97 |
+
"user_story",
|
| 98 |
+
"expected_behavior",
|
| 99 |
+
"test_command_or_steps",
|
| 100 |
+
"status",
|
| 101 |
+
"first_test_result",
|
| 102 |
+
"last_verified_at",
|
| 103 |
+
)
|
| 104 |
+
for row in rows:
|
| 105 |
+
for key in required:
|
| 106 |
+
assert row[key].strip(), f"{row.get('feature_id', '<unknown>')} missing {key}"
|
| 107 |
+
assert row["status"] in ACTIONABLE_STATUSES
|
| 108 |
+
if row["status"] in FIX_STATUSES:
|
| 109 |
+
for key in ("error_id", "error_summary", "fix_status"):
|
| 110 |
+
assert row[key].strip(), (
|
| 111 |
+
f"{row.get('feature_id', '<unknown>')} has {row['status']} without {key}"
|
| 112 |
+
)
|
| 113 |
+
if row["status"] in VALIDATION_STATUSES:
|
| 114 |
+
assert row["notes"].strip(), (
|
| 115 |
+
f"{row.get('feature_id', '<unknown>')} needs validation without a validation note"
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def test_feature_user_story_tracker_covers_all_console_scripts() -> None:
|
| 120 |
+
pyproject = tomllib.loads((repo_root / "pyproject.toml").read_text(encoding="utf-8"))
|
| 121 |
+
scripts = sorted(pyproject["project"]["scripts"])
|
| 122 |
+
tracker = _tracker_text()
|
| 123 |
+
|
| 124 |
+
assert scripts
|
| 125 |
+
assert [script for script in scripts if script not in tracker] == []
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_feature_user_story_tracker_covers_monitor_route_inventory() -> None:
|
| 129 |
+
route_patterns: list[str] = []
|
| 130 |
+
route_patterns.extend(href for _key, _label, href in monitor_routes.NAV_ROUTES)
|
| 131 |
+
route_patterns.extend(sorted(monitor_routes.PAGE_ROUTES))
|
| 132 |
+
route_patterns.extend(sorted(monitor_routes.GET_API_ROUTES))
|
| 133 |
+
route_patterns.extend(monitor_routes.GET_API_PATTERNS)
|
| 134 |
+
route_patterns.extend(sorted(monitor_routes.POST_API_ROUTES))
|
| 135 |
+
route_patterns.extend(("/session/<session_id>", "/skill/<slug>"))
|
| 136 |
+
route_patterns = list(dict.fromkeys(route_patterns))
|
| 137 |
+
tracker = _tracker_text()
|
| 138 |
+
|
| 139 |
+
assert route_patterns
|
| 140 |
+
assert [route for route in route_patterns if route not in tracker] == []
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def test_feature_user_story_tracker_covers_distribution_workflows() -> None:
|
| 144 |
+
workflows = (
|
| 145 |
+
".github/workflows/test.yml",
|
| 146 |
+
".github/workflows/docs.yml",
|
| 147 |
+
".github/workflows/huggingface-sync.yml",
|
| 148 |
+
".github/workflows/publish.yml",
|
| 149 |
+
".github/workflows/clean-host-contract.yml",
|
| 150 |
+
".github/workflows/xdist-experiment.yml",
|
| 151 |
+
)
|
| 152 |
+
tracker = _tracker_text()
|
| 153 |
+
|
| 154 |
+
assert [workflow for workflow in workflows if workflow not in tracker] == []
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def test_feature_user_story_tracker_covers_maintainer_scripts() -> None:
|
| 158 |
+
scripts = sorted((repo_root / "scripts").glob("*.py"))
|
| 159 |
+
tracker = _tracker_text()
|
| 160 |
+
script_paths = [script.relative_to(repo_root).as_posix() for script in scripts]
|
| 161 |
+
|
| 162 |
+
assert scripts
|
| 163 |
+
assert [path for path in script_paths if path not in tracker] == []
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def test_feature_user_story_tracker_covers_public_docs_assets() -> None:
|
| 167 |
+
assets = sorted((repo_root / "docs" / "assets" / "javascripts").glob("*.js"))
|
| 168 |
+
tracker_rows = _tracker_rows()
|
| 169 |
+
tracker = "\n".join(_row_text(row) for row in tracker_rows)
|
| 170 |
+
asset_paths = [asset.relative_to(repo_root).as_posix() for asset in assets]
|
| 171 |
+
nav_doc_paths = _mkdocs_nav_markdown_paths()
|
| 172 |
+
|
| 173 |
+
assert assets
|
| 174 |
+
assert [path for path in asset_paths if path not in tracker] == []
|
| 175 |
+
assert nav_doc_paths
|
| 176 |
+
assert [
|
| 177 |
+
path
|
| 178 |
+
for path in nav_doc_paths
|
| 179 |
+
if not any(row["entrypoint_or_route"] == path for row in tracker_rows)
|
| 180 |
+
] == []
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def test_readme_shows_user_story_examples_from_tracker() -> None:
|
| 184 |
+
readme = README.read_text(encoding="utf-8")
|
| 185 |
+
tracker_rows = _tracker_rows()
|
| 186 |
+
with DASHBOARD_TRACKER.open(newline="", encoding="utf-8") as f:
|
| 187 |
+
dashboard_rows = list(csv.DictReader(f))
|
| 188 |
+
tracker_ids = {row["feature_id"] for row in tracker_rows}
|
| 189 |
+
|
| 190 |
+
assert "## Example user stories" in readme
|
| 191 |
+
assert "docs/qa/feature-user-story-status.csv" in readme
|
| 192 |
+
assert "docs/qa/dashboard-user-story-status.csv" in readme
|
| 193 |
+
assert "supporting detail ledger" in readme
|
| 194 |
+
for feature_id in ("CLI-002", "CLI-026", "API-011"):
|
| 195 |
+
assert feature_id in readme
|
| 196 |
+
assert dashboard_rows
|
| 197 |
+
assert {row["status"] for row in dashboard_rows} <= PASS_STATUSES
|
| 198 |
+
required_ids = ("DASH-001", "DASH-007", "API-011")
|
| 199 |
+
assert [row_id for row_id in required_ids if row_id not in tracker_ids] == []
|
| 200 |
+
|
| 201 |
+
required_surface_markers = (
|
| 202 |
+
"ctx.api and ctx top-level re-exports",
|
| 203 |
+
"ctx__recommend_bundle, ctx__graph_query, ctx__wiki_search, ctx__wiki_get",
|
| 204 |
+
"ctx__observe_dev_event, ctx__load_entity, ctx__mark_entity_used",
|
| 205 |
+
"McpClient and McpRouter",
|
| 206 |
+
"output_format and _response_format",
|
| 207 |
+
)
|
| 208 |
+
tracker = _tracker_text()
|
| 209 |
+
|
| 210 |
+
assert [marker for marker in required_surface_markers if marker not in tracker] == []
|
| 211 |
+
python_api_rows = _rows_for_surface(tracker_rows, "Python API")
|
| 212 |
+
python_api_text = " ".join(_row_text(row) for row in python_api_rows)
|
| 213 |
+
public_api_names = sorted(
|
| 214 |
+
set(ctx_api.__all__)
|
| 215 |
+
| {
|
| 216 |
+
name
|
| 217 |
+
for name in ctx.__all__
|
| 218 |
+
if name != "__version__"
|
| 219 |
+
and hasattr(ctx_api, name)
|
| 220 |
+
and getattr(ctx, name) is getattr(ctx_api, name)
|
| 221 |
+
}
|
| 222 |
+
)
|
| 223 |
+
assert python_api_rows
|
| 224 |
+
assert [name for name in public_api_names if name not in python_api_text] == []
|
| 225 |
+
for marker in ("src/ctx/api.py", "src/ctx/__init__.py", "src/tests/test_public_api.py"):
|
| 226 |
+
assert marker in python_api_text
|
| 227 |
+
|
| 228 |
+
mcp_core_rows = _rows_for_surface(tracker_rows, "MCP/Core Tools")
|
| 229 |
+
assert mcp_core_rows
|
| 230 |
+
tool_names = sorted(
|
| 231 |
+
definition.name for definition in ctx_api.CtxCoreToolbox().tool_definitions()
|
| 232 |
+
)
|
| 233 |
+
assert [
|
| 234 |
+
name for name in tool_names if not any(name in _row_text(row) for row in mcp_core_rows)
|
| 235 |
+
] == []
|
src/tests/test_graph_packs.py
ADDED
|
@@ -0,0 +1,830 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import networkx as nx
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
from ctx.core.graph.graph_packs import (
|
| 10 |
+
GraphPackManifest,
|
| 11 |
+
GraphPackManifestError,
|
| 12 |
+
build_pack_manifest,
|
| 13 |
+
compact_graph_packs,
|
| 14 |
+
discover_pack_manifests,
|
| 15 |
+
load_merged_pack_graph,
|
| 16 |
+
promote_graph_pack_set,
|
| 17 |
+
read_pack_manifest,
|
| 18 |
+
sha256_file,
|
| 19 |
+
main,
|
| 20 |
+
write_base_pack,
|
| 21 |
+
write_overlay_pack,
|
| 22 |
+
write_pack_manifest,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_base_pack_manifest_round_trips_with_file_checksums(tmp_path: Path) -> None:
|
| 27 |
+
pack_dir = tmp_path / "graph" / "packs" / "base-export-1"
|
| 28 |
+
pack_dir.mkdir(parents=True)
|
| 29 |
+
(pack_dir / "graph.json").write_text('{"nodes":[],"edges":[]}\n', encoding="utf-8")
|
| 30 |
+
(pack_dir / "communities.json").write_text('{"communities":[]}\n', encoding="utf-8")
|
| 31 |
+
|
| 32 |
+
manifest = build_pack_manifest(
|
| 33 |
+
pack_dir=pack_dir,
|
| 34 |
+
pack_id="base-export-1",
|
| 35 |
+
pack_type="base",
|
| 36 |
+
base_export_id="export-1",
|
| 37 |
+
parent_export_id=None,
|
| 38 |
+
config_hash="config-sha",
|
| 39 |
+
model_id="bge-small-en-v1.5",
|
| 40 |
+
node_count=0,
|
| 41 |
+
edge_count=0,
|
| 42 |
+
artifact_paths=["graph.json", "communities.json"],
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
assert manifest.checksums["graph.json"] == sha256_file(pack_dir / "graph.json")
|
| 46 |
+
|
| 47 |
+
manifest_path = pack_dir / "graph-pack-manifest.json"
|
| 48 |
+
write_pack_manifest(manifest_path, manifest)
|
| 49 |
+
|
| 50 |
+
assert read_pack_manifest(manifest_path) == manifest
|
| 51 |
+
assert json.loads(manifest_path.read_text(encoding="utf-8"))["schema_version"] == 1
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_overlay_pack_manifest_requires_parent_export_id() -> None:
|
| 55 |
+
with pytest.raises(GraphPackManifestError, match="parent_export_id"):
|
| 56 |
+
GraphPackManifest.from_mapping({
|
| 57 |
+
"schema_version": 1,
|
| 58 |
+
"pack_id": "overlay-1",
|
| 59 |
+
"pack_type": "overlay",
|
| 60 |
+
"base_export_id": "export-1",
|
| 61 |
+
"parent_export_id": None,
|
| 62 |
+
"config_hash": "config-sha",
|
| 63 |
+
"model_id": "bge-small-en-v1.5",
|
| 64 |
+
"node_count": 1,
|
| 65 |
+
"edge_count": 2,
|
| 66 |
+
"tombstone_count": 0,
|
| 67 |
+
"checksums": {"entity-overlays.jsonl": "a" * 64},
|
| 68 |
+
})
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_manifest_rejects_unsafe_artifact_paths(tmp_path: Path) -> None:
|
| 72 |
+
pack_dir = tmp_path / "pack"
|
| 73 |
+
pack_dir.mkdir()
|
| 74 |
+
(tmp_path / "graph.json").write_text("{}", encoding="utf-8")
|
| 75 |
+
|
| 76 |
+
with pytest.raises(GraphPackManifestError, match="unsafe"):
|
| 77 |
+
build_pack_manifest(
|
| 78 |
+
pack_dir=pack_dir,
|
| 79 |
+
pack_id="base-export-1",
|
| 80 |
+
pack_type="base",
|
| 81 |
+
base_export_id="export-1",
|
| 82 |
+
parent_export_id=None,
|
| 83 |
+
config_hash="config-sha",
|
| 84 |
+
model_id="bge-small-en-v1.5",
|
| 85 |
+
node_count=0,
|
| 86 |
+
edge_count=0,
|
| 87 |
+
artifact_paths=["../graph.json"],
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def test_manifest_rejects_bad_checksum_shape() -> None:
|
| 92 |
+
payload = {
|
| 93 |
+
"schema_version": 1,
|
| 94 |
+
"pack_id": "base-export-1",
|
| 95 |
+
"pack_type": "base",
|
| 96 |
+
"base_export_id": "export-1",
|
| 97 |
+
"parent_export_id": None,
|
| 98 |
+
"config_hash": "config-sha",
|
| 99 |
+
"model_id": "bge-small-en-v1.5",
|
| 100 |
+
"node_count": 0,
|
| 101 |
+
"edge_count": 0,
|
| 102 |
+
"tombstone_count": 0,
|
| 103 |
+
"checksums": {"graph.json": "not-a-digest"},
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
with pytest.raises(GraphPackManifestError, match="SHA-256"):
|
| 107 |
+
GraphPackManifest.from_mapping(payload)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def test_discover_pack_manifests_orders_base_then_overlays(tmp_path: Path) -> None:
|
| 111 |
+
packs_dir = tmp_path / "graph" / "packs"
|
| 112 |
+
base_dir = packs_dir / "base-export-1"
|
| 113 |
+
overlay_dir = packs_dir / "overlay-review-skill"
|
| 114 |
+
base_dir.mkdir(parents=True)
|
| 115 |
+
overlay_dir.mkdir()
|
| 116 |
+
(base_dir / "graph.json").write_text('{"nodes":[],"edges":[]}\n', encoding="utf-8")
|
| 117 |
+
(overlay_dir / "nodes.jsonl").write_text('{"id":"skill:review"}\n', encoding="utf-8")
|
| 118 |
+
write_pack_manifest(
|
| 119 |
+
base_dir / "graph-pack-manifest.json",
|
| 120 |
+
build_pack_manifest(
|
| 121 |
+
pack_dir=base_dir,
|
| 122 |
+
pack_id="base-export-1",
|
| 123 |
+
pack_type="base",
|
| 124 |
+
base_export_id="export-1",
|
| 125 |
+
parent_export_id=None,
|
| 126 |
+
config_hash="config-sha",
|
| 127 |
+
model_id="bge-small-en-v1.5",
|
| 128 |
+
node_count=0,
|
| 129 |
+
edge_count=0,
|
| 130 |
+
artifact_paths=["graph.json"],
|
| 131 |
+
),
|
| 132 |
+
)
|
| 133 |
+
write_pack_manifest(
|
| 134 |
+
overlay_dir / "graph-pack-manifest.json",
|
| 135 |
+
build_pack_manifest(
|
| 136 |
+
pack_dir=overlay_dir,
|
| 137 |
+
pack_id="overlay-review-skill",
|
| 138 |
+
pack_type="overlay",
|
| 139 |
+
base_export_id="export-1",
|
| 140 |
+
parent_export_id="export-1",
|
| 141 |
+
config_hash="config-sha",
|
| 142 |
+
model_id="bge-small-en-v1.5",
|
| 143 |
+
node_count=1,
|
| 144 |
+
edge_count=0,
|
| 145 |
+
artifact_paths=["nodes.jsonl"],
|
| 146 |
+
tombstone_count=2,
|
| 147 |
+
),
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
discovered = discover_pack_manifests(packs_dir)
|
| 151 |
+
|
| 152 |
+
assert [entry.manifest.pack_id for entry in discovered] == [
|
| 153 |
+
"base-export-1",
|
| 154 |
+
"overlay-review-skill",
|
| 155 |
+
]
|
| 156 |
+
assert discovered[1].manifest.tombstone_count == 2
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def test_discover_pack_manifests_rejects_overlay_parent_mismatch(tmp_path: Path) -> None:
|
| 160 |
+
packs_dir = tmp_path / "packs"
|
| 161 |
+
base_dir = packs_dir / "base-export-1"
|
| 162 |
+
overlay_dir = packs_dir / "overlay-stale"
|
| 163 |
+
base_dir.mkdir(parents=True)
|
| 164 |
+
overlay_dir.mkdir()
|
| 165 |
+
(base_dir / "graph.json").write_text("{}", encoding="utf-8")
|
| 166 |
+
(overlay_dir / "nodes.jsonl").write_text("{}", encoding="utf-8")
|
| 167 |
+
write_pack_manifest(
|
| 168 |
+
base_dir / "graph-pack-manifest.json",
|
| 169 |
+
build_pack_manifest(
|
| 170 |
+
pack_dir=base_dir,
|
| 171 |
+
pack_id="base-export-1",
|
| 172 |
+
pack_type="base",
|
| 173 |
+
base_export_id="export-1",
|
| 174 |
+
parent_export_id=None,
|
| 175 |
+
config_hash="config-sha",
|
| 176 |
+
model_id="bge-small-en-v1.5",
|
| 177 |
+
node_count=0,
|
| 178 |
+
edge_count=0,
|
| 179 |
+
artifact_paths=["graph.json"],
|
| 180 |
+
),
|
| 181 |
+
)
|
| 182 |
+
write_pack_manifest(
|
| 183 |
+
overlay_dir / "graph-pack-manifest.json",
|
| 184 |
+
build_pack_manifest(
|
| 185 |
+
pack_dir=overlay_dir,
|
| 186 |
+
pack_id="overlay-stale",
|
| 187 |
+
pack_type="overlay",
|
| 188 |
+
base_export_id="export-1",
|
| 189 |
+
parent_export_id="old-export",
|
| 190 |
+
config_hash="config-sha",
|
| 191 |
+
model_id="bge-small-en-v1.5",
|
| 192 |
+
node_count=1,
|
| 193 |
+
edge_count=0,
|
| 194 |
+
artifact_paths=["nodes.jsonl"],
|
| 195 |
+
),
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
with pytest.raises(GraphPackManifestError, match="parent_export_id"):
|
| 199 |
+
discover_pack_manifests(packs_dir)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def test_discover_pack_manifests_rejects_checksum_drift(tmp_path: Path) -> None:
|
| 203 |
+
packs_dir = tmp_path / "packs"
|
| 204 |
+
base_dir = packs_dir / "base-export-1"
|
| 205 |
+
base_dir.mkdir(parents=True)
|
| 206 |
+
graph_path = base_dir / "graph.json"
|
| 207 |
+
graph_path.write_text("{}", encoding="utf-8")
|
| 208 |
+
write_pack_manifest(
|
| 209 |
+
base_dir / "graph-pack-manifest.json",
|
| 210 |
+
build_pack_manifest(
|
| 211 |
+
pack_dir=base_dir,
|
| 212 |
+
pack_id="base-export-1",
|
| 213 |
+
pack_type="base",
|
| 214 |
+
base_export_id="export-1",
|
| 215 |
+
parent_export_id=None,
|
| 216 |
+
config_hash="config-sha",
|
| 217 |
+
model_id="bge-small-en-v1.5",
|
| 218 |
+
node_count=0,
|
| 219 |
+
edge_count=0,
|
| 220 |
+
artifact_paths=["graph.json"],
|
| 221 |
+
),
|
| 222 |
+
)
|
| 223 |
+
graph_path.write_text('{"changed":true}', encoding="utf-8")
|
| 224 |
+
|
| 225 |
+
with pytest.raises(GraphPackManifestError, match="checksum mismatch"):
|
| 226 |
+
discover_pack_manifests(packs_dir)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def test_load_merged_pack_graph_applies_overlay_nodes_and_edges(tmp_path: Path) -> None:
|
| 230 |
+
packs_dir = tmp_path / "packs"
|
| 231 |
+
base_dir = packs_dir / "base-export-1"
|
| 232 |
+
overlay_dir = packs_dir / "overlay-review"
|
| 233 |
+
base_dir.mkdir(parents=True)
|
| 234 |
+
overlay_dir.mkdir()
|
| 235 |
+
(base_dir / "graph.json").write_text(
|
| 236 |
+
json.dumps({
|
| 237 |
+
"graph": {"export_id": "export-1"},
|
| 238 |
+
"nodes": [
|
| 239 |
+
{"id": "skill:python", "type": "skill", "tags": ["python"]},
|
| 240 |
+
{"id": "mcp-server:github", "type": "mcp-server", "tags": ["github"]},
|
| 241 |
+
],
|
| 242 |
+
"edges": [
|
| 243 |
+
{"source": "skill:python", "target": "mcp-server:github", "weight": 0.4},
|
| 244 |
+
],
|
| 245 |
+
}),
|
| 246 |
+
encoding="utf-8",
|
| 247 |
+
)
|
| 248 |
+
(overlay_dir / "nodes.jsonl").write_text(
|
| 249 |
+
json.dumps({"id": "skill:review", "type": "skill", "tags": ["review"]}) + "\n",
|
| 250 |
+
encoding="utf-8",
|
| 251 |
+
)
|
| 252 |
+
(overlay_dir / "edges.jsonl").write_text(
|
| 253 |
+
json.dumps({
|
| 254 |
+
"source": "skill:review",
|
| 255 |
+
"target": "mcp-server:github",
|
| 256 |
+
"weight": 0.8,
|
| 257 |
+
"provenance": "overlay-test",
|
| 258 |
+
}) + "\n",
|
| 259 |
+
encoding="utf-8",
|
| 260 |
+
)
|
| 261 |
+
write_pack_manifest(
|
| 262 |
+
base_dir / "graph-pack-manifest.json",
|
| 263 |
+
build_pack_manifest(
|
| 264 |
+
pack_dir=base_dir,
|
| 265 |
+
pack_id="base-export-1",
|
| 266 |
+
pack_type="base",
|
| 267 |
+
base_export_id="export-1",
|
| 268 |
+
parent_export_id=None,
|
| 269 |
+
config_hash="config-sha",
|
| 270 |
+
model_id="bge-small-en-v1.5",
|
| 271 |
+
node_count=2,
|
| 272 |
+
edge_count=1,
|
| 273 |
+
artifact_paths=["graph.json"],
|
| 274 |
+
),
|
| 275 |
+
)
|
| 276 |
+
write_pack_manifest(
|
| 277 |
+
overlay_dir / "graph-pack-manifest.json",
|
| 278 |
+
build_pack_manifest(
|
| 279 |
+
pack_dir=overlay_dir,
|
| 280 |
+
pack_id="overlay-review",
|
| 281 |
+
pack_type="overlay",
|
| 282 |
+
base_export_id="export-1",
|
| 283 |
+
parent_export_id="export-1",
|
| 284 |
+
config_hash="config-sha",
|
| 285 |
+
model_id="bge-small-en-v1.5",
|
| 286 |
+
node_count=1,
|
| 287 |
+
edge_count=1,
|
| 288 |
+
artifact_paths=["nodes.jsonl", "edges.jsonl"],
|
| 289 |
+
),
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
graph = load_merged_pack_graph(packs_dir)
|
| 293 |
+
|
| 294 |
+
assert graph.number_of_nodes() == 3
|
| 295 |
+
assert graph.has_edge("skill:review", "mcp-server:github")
|
| 296 |
+
assert graph.edges["skill:review", "mcp-server:github"]["weight"] == 0.8
|
| 297 |
+
assert graph.graph["ctx_pack_ids"] == ["base-export-1", "overlay-review"]
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def test_load_merged_pack_graph_applies_overlays_by_created_at(tmp_path: Path) -> None:
|
| 301 |
+
packs_dir = tmp_path / "packs"
|
| 302 |
+
base_graph = nx.Graph()
|
| 303 |
+
base_graph.add_node("skill:docs", title="base", type="skill")
|
| 304 |
+
write_base_pack(
|
| 305 |
+
pack_dir=packs_dir / "base-export-1",
|
| 306 |
+
pack_id="base-export-1",
|
| 307 |
+
base_export_id="export-1",
|
| 308 |
+
config_hash="config-sha",
|
| 309 |
+
model_id="model-a",
|
| 310 |
+
graph=base_graph,
|
| 311 |
+
)
|
| 312 |
+
write_overlay_pack(
|
| 313 |
+
pack_dir=packs_dir / "overlay-z-old",
|
| 314 |
+
pack_id="overlay-z-old",
|
| 315 |
+
base_export_id="export-1",
|
| 316 |
+
parent_export_id="export-1",
|
| 317 |
+
config_hash="config-sha",
|
| 318 |
+
model_id="model-a",
|
| 319 |
+
nodes=[{"id": "skill:docs", "title": "old"}],
|
| 320 |
+
edges=[],
|
| 321 |
+
tombstones=[],
|
| 322 |
+
created_at="2026-01-01T00:00:00+00:00",
|
| 323 |
+
)
|
| 324 |
+
write_overlay_pack(
|
| 325 |
+
pack_dir=packs_dir / "overlay-a-new",
|
| 326 |
+
pack_id="overlay-a-new",
|
| 327 |
+
base_export_id="export-1",
|
| 328 |
+
parent_export_id="export-1",
|
| 329 |
+
config_hash="config-sha",
|
| 330 |
+
model_id="model-a",
|
| 331 |
+
nodes=[{"id": "skill:docs", "title": "new"}],
|
| 332 |
+
edges=[],
|
| 333 |
+
tombstones=[],
|
| 334 |
+
created_at="2026-01-02T00:00:00+00:00",
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
graph = load_merged_pack_graph(packs_dir)
|
| 338 |
+
|
| 339 |
+
assert graph.nodes["skill:docs"]["title"] == "new"
|
| 340 |
+
assert graph.graph["ctx_pack_ids"] == [
|
| 341 |
+
"base-export-1",
|
| 342 |
+
"overlay-z-old",
|
| 343 |
+
"overlay-a-new",
|
| 344 |
+
]
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def test_load_merged_pack_graph_applies_tombstones(tmp_path: Path) -> None:
|
| 348 |
+
packs_dir = tmp_path / "packs"
|
| 349 |
+
base_dir = packs_dir / "base-export-1"
|
| 350 |
+
overlay_dir = packs_dir / "overlay-delete"
|
| 351 |
+
base_dir.mkdir(parents=True)
|
| 352 |
+
overlay_dir.mkdir()
|
| 353 |
+
(base_dir / "graph.json").write_text(
|
| 354 |
+
json.dumps({
|
| 355 |
+
"nodes": [
|
| 356 |
+
{"id": "skill:python"},
|
| 357 |
+
{"id": "skill:old"},
|
| 358 |
+
],
|
| 359 |
+
"edges": [
|
| 360 |
+
{"source": "skill:python", "target": "skill:old", "weight": 0.4},
|
| 361 |
+
],
|
| 362 |
+
}),
|
| 363 |
+
encoding="utf-8",
|
| 364 |
+
)
|
| 365 |
+
(overlay_dir / "tombstones.jsonl").write_text(
|
| 366 |
+
json.dumps({"node_id": "skill:old", "reason": "deleted"}) + "\n",
|
| 367 |
+
encoding="utf-8",
|
| 368 |
+
)
|
| 369 |
+
write_pack_manifest(
|
| 370 |
+
base_dir / "graph-pack-manifest.json",
|
| 371 |
+
build_pack_manifest(
|
| 372 |
+
pack_dir=base_dir,
|
| 373 |
+
pack_id="base-export-1",
|
| 374 |
+
pack_type="base",
|
| 375 |
+
base_export_id="export-1",
|
| 376 |
+
parent_export_id=None,
|
| 377 |
+
config_hash="config-sha",
|
| 378 |
+
model_id="bge-small-en-v1.5",
|
| 379 |
+
node_count=2,
|
| 380 |
+
edge_count=1,
|
| 381 |
+
artifact_paths=["graph.json"],
|
| 382 |
+
),
|
| 383 |
+
)
|
| 384 |
+
write_pack_manifest(
|
| 385 |
+
overlay_dir / "graph-pack-manifest.json",
|
| 386 |
+
build_pack_manifest(
|
| 387 |
+
pack_dir=overlay_dir,
|
| 388 |
+
pack_id="overlay-delete",
|
| 389 |
+
pack_type="overlay",
|
| 390 |
+
base_export_id="export-1",
|
| 391 |
+
parent_export_id="export-1",
|
| 392 |
+
config_hash="config-sha",
|
| 393 |
+
model_id="bge-small-en-v1.5",
|
| 394 |
+
node_count=0,
|
| 395 |
+
edge_count=0,
|
| 396 |
+
artifact_paths=["tombstones.jsonl"],
|
| 397 |
+
tombstone_count=1,
|
| 398 |
+
),
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
graph = load_merged_pack_graph(packs_dir)
|
| 402 |
+
|
| 403 |
+
assert "skill:old" not in graph
|
| 404 |
+
assert graph.number_of_edges() == 0
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def test_load_merged_pack_graph_rejects_base_count_drift(tmp_path: Path) -> None:
|
| 408 |
+
packs_dir = tmp_path / "packs"
|
| 409 |
+
base_dir = packs_dir / "base-export-1"
|
| 410 |
+
base_dir.mkdir(parents=True)
|
| 411 |
+
(base_dir / "graph.json").write_text(
|
| 412 |
+
json.dumps({
|
| 413 |
+
"nodes": [{"id": "skill:python"}],
|
| 414 |
+
"edges": [],
|
| 415 |
+
}),
|
| 416 |
+
encoding="utf-8",
|
| 417 |
+
)
|
| 418 |
+
write_pack_manifest(
|
| 419 |
+
base_dir / "graph-pack-manifest.json",
|
| 420 |
+
build_pack_manifest(
|
| 421 |
+
pack_dir=base_dir,
|
| 422 |
+
pack_id="base-export-1",
|
| 423 |
+
pack_type="base",
|
| 424 |
+
base_export_id="export-1",
|
| 425 |
+
parent_export_id=None,
|
| 426 |
+
config_hash="config-sha",
|
| 427 |
+
model_id="bge-small-en-v1.5",
|
| 428 |
+
node_count=2,
|
| 429 |
+
edge_count=0,
|
| 430 |
+
artifact_paths=["graph.json"],
|
| 431 |
+
),
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
with pytest.raises(GraphPackManifestError, match="node_count mismatch"):
|
| 435 |
+
load_merged_pack_graph(packs_dir)
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def test_load_merged_pack_graph_rejects_overlay_count_drift(tmp_path: Path) -> None:
|
| 439 |
+
packs_dir = tmp_path / "packs"
|
| 440 |
+
base_graph = nx.Graph()
|
| 441 |
+
base_graph.add_node("skill:python")
|
| 442 |
+
write_base_pack(
|
| 443 |
+
pack_dir=packs_dir / "base-export-1",
|
| 444 |
+
pack_id="base-export-1",
|
| 445 |
+
base_export_id="export-1",
|
| 446 |
+
config_hash="config-sha",
|
| 447 |
+
model_id="bge-small-en-v1.5",
|
| 448 |
+
graph=base_graph,
|
| 449 |
+
)
|
| 450 |
+
overlay_dir = packs_dir / "overlay-review"
|
| 451 |
+
overlay_dir.mkdir()
|
| 452 |
+
(overlay_dir / "nodes.jsonl").write_text(
|
| 453 |
+
json.dumps({"id": "skill:review"}) + "\n",
|
| 454 |
+
encoding="utf-8",
|
| 455 |
+
)
|
| 456 |
+
write_pack_manifest(
|
| 457 |
+
overlay_dir / "graph-pack-manifest.json",
|
| 458 |
+
build_pack_manifest(
|
| 459 |
+
pack_dir=overlay_dir,
|
| 460 |
+
pack_id="overlay-review",
|
| 461 |
+
pack_type="overlay",
|
| 462 |
+
base_export_id="export-1",
|
| 463 |
+
parent_export_id="export-1",
|
| 464 |
+
config_hash="config-sha",
|
| 465 |
+
model_id="bge-small-en-v1.5",
|
| 466 |
+
node_count=2,
|
| 467 |
+
edge_count=0,
|
| 468 |
+
artifact_paths=["nodes.jsonl"],
|
| 469 |
+
),
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
with pytest.raises(GraphPackManifestError, match="node_count mismatch"):
|
| 473 |
+
load_merged_pack_graph(packs_dir)
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def test_write_overlay_pack_creates_jsonl_artifacts_and_manifest(tmp_path: Path) -> None:
|
| 477 |
+
pack_dir = tmp_path / "packs" / "overlay-review"
|
| 478 |
+
|
| 479 |
+
manifest = write_overlay_pack(
|
| 480 |
+
pack_dir=pack_dir,
|
| 481 |
+
pack_id="overlay-review",
|
| 482 |
+
base_export_id="export-1",
|
| 483 |
+
parent_export_id="export-1",
|
| 484 |
+
config_hash="config-sha",
|
| 485 |
+
model_id="bge-small-en-v1.5",
|
| 486 |
+
nodes=[{"id": "skill:review", "type": "skill"}],
|
| 487 |
+
edges=[{"source": "skill:review", "target": "skill:python", "weight": 0.7}],
|
| 488 |
+
tombstones=[{"node_id": "skill:old"}],
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
assert manifest.pack_type == "overlay"
|
| 492 |
+
assert manifest.node_count == 1
|
| 493 |
+
assert manifest.edge_count == 1
|
| 494 |
+
assert manifest.tombstone_count == 1
|
| 495 |
+
assert (pack_dir / "nodes.jsonl").read_text(encoding="utf-8").count("\n") == 1
|
| 496 |
+
assert (pack_dir / "edges.jsonl").read_text(encoding="utf-8").count("\n") == 1
|
| 497 |
+
assert (pack_dir / "tombstones.jsonl").read_text(encoding="utf-8").count("\n") == 1
|
| 498 |
+
assert read_pack_manifest(pack_dir / "graph-pack-manifest.json") == manifest
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def test_write_overlay_pack_rejects_empty_pack(tmp_path: Path) -> None:
|
| 502 |
+
with pytest.raises(GraphPackManifestError, match="empty overlay pack"):
|
| 503 |
+
write_overlay_pack(
|
| 504 |
+
pack_dir=tmp_path / "overlay-empty",
|
| 505 |
+
pack_id="overlay-empty",
|
| 506 |
+
base_export_id="export-1",
|
| 507 |
+
parent_export_id="export-1",
|
| 508 |
+
config_hash="config-sha",
|
| 509 |
+
model_id="bge-small-en-v1.5",
|
| 510 |
+
nodes=[],
|
| 511 |
+
edges=[],
|
| 512 |
+
tombstones=[],
|
| 513 |
+
)
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
def test_write_overlay_pack_rejects_existing_manifest(tmp_path: Path) -> None:
|
| 517 |
+
pack_dir = tmp_path / "packs" / "overlay-review"
|
| 518 |
+
write_overlay_pack(
|
| 519 |
+
pack_dir=pack_dir,
|
| 520 |
+
pack_id="overlay-review",
|
| 521 |
+
base_export_id="export-1",
|
| 522 |
+
parent_export_id="export-1",
|
| 523 |
+
config_hash="config-sha",
|
| 524 |
+
model_id="bge-small-en-v1.5",
|
| 525 |
+
nodes=[{"id": "skill:review"}],
|
| 526 |
+
edges=[],
|
| 527 |
+
tombstones=[],
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
with pytest.raises(GraphPackManifestError, match="already exists"):
|
| 531 |
+
write_overlay_pack(
|
| 532 |
+
pack_dir=pack_dir,
|
| 533 |
+
pack_id="overlay-review",
|
| 534 |
+
base_export_id="export-1",
|
| 535 |
+
parent_export_id="export-1",
|
| 536 |
+
config_hash="config-sha",
|
| 537 |
+
model_id="bge-small-en-v1.5",
|
| 538 |
+
nodes=[{"id": "skill:changed"}],
|
| 539 |
+
edges=[],
|
| 540 |
+
tombstones=[],
|
| 541 |
+
)
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
def test_write_base_pack_creates_graph_json_and_manifest(tmp_path: Path) -> None:
|
| 545 |
+
graph = nx.Graph()
|
| 546 |
+
graph.add_node("skill:python", type="skill")
|
| 547 |
+
graph.add_node("agent:review", type="agent")
|
| 548 |
+
graph.add_edge("skill:python", "agent:review", weight=0.6)
|
| 549 |
+
|
| 550 |
+
manifest = write_base_pack(
|
| 551 |
+
pack_dir=tmp_path / "base-export-2",
|
| 552 |
+
pack_id="base-export-2",
|
| 553 |
+
base_export_id="export-2",
|
| 554 |
+
config_hash="config-sha",
|
| 555 |
+
model_id="model-a",
|
| 556 |
+
graph=graph,
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
payload = json.loads((tmp_path / "base-export-2" / "graph.json").read_text(encoding="utf-8"))
|
| 560 |
+
assert payload["graph"]["export_id"] == "export-2"
|
| 561 |
+
assert "edges" in payload
|
| 562 |
+
assert manifest.pack_type == "base"
|
| 563 |
+
assert manifest.node_count == 2
|
| 564 |
+
assert manifest.edge_count == 1
|
| 565 |
+
assert read_pack_manifest(tmp_path / "base-export-2" / "graph-pack-manifest.json") == manifest
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def test_pack_writers_reject_unsafe_pack_id_before_payload_write(tmp_path: Path) -> None:
|
| 569 |
+
graph = nx.Graph()
|
| 570 |
+
graph.add_node("skill:python", type="skill")
|
| 571 |
+
|
| 572 |
+
with pytest.raises(GraphPackManifestError, match="pack_id is unsafe"):
|
| 573 |
+
write_base_pack(
|
| 574 |
+
pack_dir=tmp_path / "base-bad",
|
| 575 |
+
pack_id="../base-bad",
|
| 576 |
+
base_export_id="export-2",
|
| 577 |
+
config_hash="config-sha",
|
| 578 |
+
model_id="model-a",
|
| 579 |
+
graph=graph,
|
| 580 |
+
)
|
| 581 |
+
assert not (tmp_path / "base-bad" / "graph.json").exists()
|
| 582 |
+
|
| 583 |
+
with pytest.raises(GraphPackManifestError, match="pack_id is unsafe"):
|
| 584 |
+
write_overlay_pack(
|
| 585 |
+
pack_dir=tmp_path / "overlay-bad",
|
| 586 |
+
pack_id="../overlay-bad",
|
| 587 |
+
base_export_id="export-1",
|
| 588 |
+
parent_export_id="export-1",
|
| 589 |
+
config_hash="config-sha",
|
| 590 |
+
model_id="model-a",
|
| 591 |
+
nodes=[{"id": "skill:review"}],
|
| 592 |
+
edges=[],
|
| 593 |
+
tombstones=[],
|
| 594 |
+
)
|
| 595 |
+
assert not (tmp_path / "overlay-bad" / "nodes.jsonl").exists()
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
def test_compact_graph_packs_writes_staged_base_without_mutating_active_packs(
|
| 599 |
+
tmp_path: Path,
|
| 600 |
+
) -> None:
|
| 601 |
+
active_packs = tmp_path / "active" / "packs"
|
| 602 |
+
base_dir = active_packs / "base-export-1"
|
| 603 |
+
overlay_dir = active_packs / "overlay-review"
|
| 604 |
+
base_dir.mkdir(parents=True)
|
| 605 |
+
overlay_dir.mkdir()
|
| 606 |
+
(base_dir / "graph.json").write_text(
|
| 607 |
+
json.dumps({
|
| 608 |
+
"graph": {"export_id": "export-1"},
|
| 609 |
+
"nodes": [
|
| 610 |
+
{"id": "skill:python", "type": "skill"},
|
| 611 |
+
{"id": "agent:review", "type": "agent"},
|
| 612 |
+
],
|
| 613 |
+
"edges": [],
|
| 614 |
+
}),
|
| 615 |
+
encoding="utf-8",
|
| 616 |
+
)
|
| 617 |
+
write_pack_manifest(
|
| 618 |
+
base_dir / "graph-pack-manifest.json",
|
| 619 |
+
build_pack_manifest(
|
| 620 |
+
pack_dir=base_dir,
|
| 621 |
+
pack_id="base-export-1",
|
| 622 |
+
pack_type="base",
|
| 623 |
+
base_export_id="export-1",
|
| 624 |
+
parent_export_id=None,
|
| 625 |
+
config_hash="config-sha",
|
| 626 |
+
model_id="model-a",
|
| 627 |
+
node_count=2,
|
| 628 |
+
edge_count=0,
|
| 629 |
+
artifact_paths=["graph.json"],
|
| 630 |
+
),
|
| 631 |
+
)
|
| 632 |
+
write_overlay_pack(
|
| 633 |
+
pack_dir=overlay_dir,
|
| 634 |
+
pack_id="overlay-review",
|
| 635 |
+
base_export_id="export-1",
|
| 636 |
+
parent_export_id="export-1",
|
| 637 |
+
config_hash="config-sha",
|
| 638 |
+
model_id="model-a",
|
| 639 |
+
nodes=[{"id": "skill:review", "type": "skill"}],
|
| 640 |
+
edges=[{"source": "skill:review", "target": "agent:review", "weight": 0.8}],
|
| 641 |
+
tombstones=[{"node_id": "skill:python"}],
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
staged_pack = tmp_path / "staged" / "base-export-2"
|
| 645 |
+
manifest = compact_graph_packs(
|
| 646 |
+
packs_dir=active_packs,
|
| 647 |
+
compacted_pack_dir=staged_pack,
|
| 648 |
+
base_export_id="export-2",
|
| 649 |
+
)
|
| 650 |
+
|
| 651 |
+
assert manifest.pack_type == "base"
|
| 652 |
+
assert manifest.base_export_id == "export-2"
|
| 653 |
+
assert [entry.manifest.pack_id for entry in discover_pack_manifests(active_packs)] == [
|
| 654 |
+
"base-export-1",
|
| 655 |
+
"overlay-review",
|
| 656 |
+
]
|
| 657 |
+
staged_packs_root = tmp_path / "staged"
|
| 658 |
+
compacted = load_merged_pack_graph(staged_packs_root)
|
| 659 |
+
assert "skill:python" not in compacted
|
| 660 |
+
assert compacted.has_edge("skill:review", "agent:review")
|
| 661 |
+
assert compacted.graph["export_id"] == "export-2"
|
| 662 |
+
assert compacted.graph["ctx_compacted_from_base_export_id"] == "export-1"
|
| 663 |
+
assert compacted.graph["ctx_compacted_overlay_count"] == 1
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
def test_main_compact_writes_json_report_and_staged_pack(
|
| 667 |
+
tmp_path: Path,
|
| 668 |
+
capsys: pytest.CaptureFixture[str],
|
| 669 |
+
) -> None:
|
| 670 |
+
active_packs = tmp_path / "active" / "packs"
|
| 671 |
+
base_dir = active_packs / "base-export-1"
|
| 672 |
+
overlay_dir = active_packs / "overlay-review"
|
| 673 |
+
base_dir.mkdir(parents=True)
|
| 674 |
+
(base_dir / "graph.json").write_text(
|
| 675 |
+
json.dumps({
|
| 676 |
+
"graph": {"export_id": "export-1"},
|
| 677 |
+
"nodes": [{"id": "skill:python"}, {"id": "skill:review"}],
|
| 678 |
+
"edges": [],
|
| 679 |
+
}),
|
| 680 |
+
encoding="utf-8",
|
| 681 |
+
)
|
| 682 |
+
write_pack_manifest(
|
| 683 |
+
base_dir / "graph-pack-manifest.json",
|
| 684 |
+
build_pack_manifest(
|
| 685 |
+
pack_dir=base_dir,
|
| 686 |
+
pack_id="base-export-1",
|
| 687 |
+
pack_type="base",
|
| 688 |
+
base_export_id="export-1",
|
| 689 |
+
parent_export_id=None,
|
| 690 |
+
config_hash="config-sha",
|
| 691 |
+
model_id="model-a",
|
| 692 |
+
node_count=2,
|
| 693 |
+
edge_count=0,
|
| 694 |
+
artifact_paths=["graph.json"],
|
| 695 |
+
),
|
| 696 |
+
)
|
| 697 |
+
write_overlay_pack(
|
| 698 |
+
pack_dir=overlay_dir,
|
| 699 |
+
pack_id="overlay-review",
|
| 700 |
+
base_export_id="export-1",
|
| 701 |
+
parent_export_id="export-1",
|
| 702 |
+
config_hash="config-sha",
|
| 703 |
+
model_id="model-a",
|
| 704 |
+
nodes=[],
|
| 705 |
+
edges=[{"source": "skill:review", "target": "skill:python", "weight": 0.8}],
|
| 706 |
+
tombstones=[],
|
| 707 |
+
)
|
| 708 |
+
staged_pack = tmp_path / "staged" / "base-export-2"
|
| 709 |
+
|
| 710 |
+
rc = main([
|
| 711 |
+
"compact",
|
| 712 |
+
"--packs-dir", str(active_packs),
|
| 713 |
+
"--staged-pack-dir", str(staged_pack),
|
| 714 |
+
"--base-export-id", "export-2",
|
| 715 |
+
"--json",
|
| 716 |
+
])
|
| 717 |
+
|
| 718 |
+
assert rc == 0
|
| 719 |
+
output = json.loads(capsys.readouterr().out)
|
| 720 |
+
assert output["pack_id"] == "base-export-2"
|
| 721 |
+
assert output["base_export_id"] == "export-2"
|
| 722 |
+
graph = load_merged_pack_graph(tmp_path / "staged")
|
| 723 |
+
assert graph.has_edge("skill:review", "skill:python")
|
| 724 |
+
|
| 725 |
+
|
| 726 |
+
def test_promote_graph_pack_set_replaces_active_and_writes_rollback_metadata(
|
| 727 |
+
tmp_path: Path,
|
| 728 |
+
) -> None:
|
| 729 |
+
active_packs = tmp_path / "graph" / "packs"
|
| 730 |
+
old_graph = nx.Graph()
|
| 731 |
+
old_graph.add_node("skill:old")
|
| 732 |
+
write_base_pack(
|
| 733 |
+
pack_dir=active_packs / "base-export-1",
|
| 734 |
+
pack_id="base-export-1",
|
| 735 |
+
base_export_id="export-1",
|
| 736 |
+
config_hash="config-sha",
|
| 737 |
+
model_id="model-a",
|
| 738 |
+
graph=old_graph,
|
| 739 |
+
)
|
| 740 |
+
write_overlay_pack(
|
| 741 |
+
pack_dir=active_packs / "overlay-review",
|
| 742 |
+
pack_id="overlay-review",
|
| 743 |
+
base_export_id="export-1",
|
| 744 |
+
parent_export_id="export-1",
|
| 745 |
+
config_hash="config-sha",
|
| 746 |
+
model_id="model-a",
|
| 747 |
+
nodes=[{"id": "skill:review"}],
|
| 748 |
+
edges=[{"source": "skill:old", "target": "skill:review", "weight": 0.8}],
|
| 749 |
+
tombstones=[],
|
| 750 |
+
)
|
| 751 |
+
|
| 752 |
+
staged_packs = tmp_path / "staged-packs"
|
| 753 |
+
new_graph = nx.Graph()
|
| 754 |
+
new_graph.add_node("skill:new")
|
| 755 |
+
write_base_pack(
|
| 756 |
+
pack_dir=staged_packs / "base-export-2",
|
| 757 |
+
pack_id="base-export-2",
|
| 758 |
+
base_export_id="export-2",
|
| 759 |
+
config_hash="config-sha",
|
| 760 |
+
model_id="model-a",
|
| 761 |
+
graph=new_graph,
|
| 762 |
+
)
|
| 763 |
+
backup_packs = tmp_path / "graph" / "packs.rollback"
|
| 764 |
+
|
| 765 |
+
result = promote_graph_pack_set(
|
| 766 |
+
staged_packs_dir=staged_packs,
|
| 767 |
+
active_packs_dir=active_packs,
|
| 768 |
+
backup_packs_dir=backup_packs,
|
| 769 |
+
)
|
| 770 |
+
|
| 771 |
+
assert result.promoted_pack_ids == ["base-export-2"]
|
| 772 |
+
assert result.replaced_pack_ids == ["base-export-1", "overlay-review"]
|
| 773 |
+
assert not staged_packs.exists()
|
| 774 |
+
assert [entry.manifest.pack_id for entry in discover_pack_manifests(active_packs)] == [
|
| 775 |
+
"base-export-2",
|
| 776 |
+
]
|
| 777 |
+
assert [entry.manifest.pack_id for entry in discover_pack_manifests(backup_packs)] == [
|
| 778 |
+
"base-export-1",
|
| 779 |
+
"overlay-review",
|
| 780 |
+
]
|
| 781 |
+
promoted_graph = load_merged_pack_graph(active_packs)
|
| 782 |
+
assert list(promoted_graph.nodes) == ["skill:new"]
|
| 783 |
+
rollback_metadata = json.loads(result.rollback_metadata_path.read_text(encoding="utf-8"))
|
| 784 |
+
assert rollback_metadata["backup_packs_dir"] == str(backup_packs)
|
| 785 |
+
assert rollback_metadata["promoted_pack_ids"] == ["base-export-2"]
|
| 786 |
+
assert rollback_metadata["replaced_pack_ids"] == ["base-export-1", "overlay-review"]
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
def test_main_promote_writes_json_report_and_uses_default_backup(
|
| 790 |
+
tmp_path: Path,
|
| 791 |
+
capsys: pytest.CaptureFixture[str],
|
| 792 |
+
) -> None:
|
| 793 |
+
active_packs = tmp_path / "graph" / "packs"
|
| 794 |
+
old_graph = nx.Graph()
|
| 795 |
+
old_graph.add_node("skill:old")
|
| 796 |
+
write_base_pack(
|
| 797 |
+
pack_dir=active_packs / "base-export-1",
|
| 798 |
+
pack_id="base-export-1",
|
| 799 |
+
base_export_id="export-1",
|
| 800 |
+
config_hash="config-sha",
|
| 801 |
+
model_id="model-a",
|
| 802 |
+
graph=old_graph,
|
| 803 |
+
)
|
| 804 |
+
staged_packs = tmp_path / "staged-packs"
|
| 805 |
+
new_graph = nx.Graph()
|
| 806 |
+
new_graph.add_node("skill:new")
|
| 807 |
+
write_base_pack(
|
| 808 |
+
pack_dir=staged_packs / "base-export-2",
|
| 809 |
+
pack_id="base-export-2",
|
| 810 |
+
base_export_id="export-2",
|
| 811 |
+
config_hash="config-sha",
|
| 812 |
+
model_id="model-a",
|
| 813 |
+
graph=new_graph,
|
| 814 |
+
)
|
| 815 |
+
|
| 816 |
+
rc = main([
|
| 817 |
+
"promote",
|
| 818 |
+
"--staged-packs-dir", str(staged_packs),
|
| 819 |
+
"--active-packs-dir", str(active_packs),
|
| 820 |
+
"--json",
|
| 821 |
+
])
|
| 822 |
+
|
| 823 |
+
assert rc == 0
|
| 824 |
+
output = json.loads(capsys.readouterr().out)
|
| 825 |
+
assert output["promoted_pack_ids"] == ["base-export-2"]
|
| 826 |
+
assert output["replaced_pack_ids"] == ["base-export-1"]
|
| 827 |
+
assert output["backup_packs_dir"] == str(tmp_path / "graph" / "packs.rollback")
|
| 828 |
+
assert [entry.manifest.pack_id for entry in discover_pack_manifests(active_packs)] == [
|
| 829 |
+
"base-export-2",
|
| 830 |
+
]
|
src/tests/test_graph_store.py
ADDED
|
@@ -0,0 +1,611 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import sqlite3
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
from ctx.core.graph.graph_store import (
|
| 11 |
+
build_graph_store,
|
| 12 |
+
build_graph_store_from_graph_dir,
|
| 13 |
+
ensure_graph_store,
|
| 14 |
+
graph_store_metadata,
|
| 15 |
+
graph_store_is_fresh,
|
| 16 |
+
graph_store_stats,
|
| 17 |
+
validate_graph_store,
|
| 18 |
+
load_neighborhood,
|
| 19 |
+
main,
|
| 20 |
+
search_nodes,
|
| 21 |
+
)
|
| 22 |
+
from ctx.core.graph.graph_packs import write_base_pack, write_overlay_pack
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _sample_graph() -> nx.Graph:
|
| 26 |
+
graph = nx.Graph()
|
| 27 |
+
graph.add_node(
|
| 28 |
+
"skill:python-testing",
|
| 29 |
+
label="python-testing",
|
| 30 |
+
title="Python Testing",
|
| 31 |
+
type="skill",
|
| 32 |
+
tags=["python", "testing"],
|
| 33 |
+
quality_score=0.9,
|
| 34 |
+
)
|
| 35 |
+
graph.add_node(
|
| 36 |
+
"mcp-server:github",
|
| 37 |
+
label="github",
|
| 38 |
+
title="GitHub",
|
| 39 |
+
type="mcp-server",
|
| 40 |
+
tags=["github", "repos"],
|
| 41 |
+
)
|
| 42 |
+
graph.add_node(
|
| 43 |
+
"agent:reviewer",
|
| 44 |
+
label="reviewer",
|
| 45 |
+
title="Code Reviewer",
|
| 46 |
+
type="agent",
|
| 47 |
+
tags=["review", "testing"],
|
| 48 |
+
)
|
| 49 |
+
graph.add_edge(
|
| 50 |
+
"skill:python-testing",
|
| 51 |
+
"mcp-server:github",
|
| 52 |
+
weight=0.72,
|
| 53 |
+
shared_tags=["testing"],
|
| 54 |
+
)
|
| 55 |
+
graph.add_edge(
|
| 56 |
+
"skill:python-testing",
|
| 57 |
+
"agent:reviewer",
|
| 58 |
+
weight=0.81,
|
| 59 |
+
shared_tags=["testing"],
|
| 60 |
+
)
|
| 61 |
+
return graph
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_build_graph_store_persists_counts(tmp_path: Path) -> None:
|
| 65 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 66 |
+
|
| 67 |
+
build_graph_store(db_path, _sample_graph())
|
| 68 |
+
|
| 69 |
+
assert graph_store_stats(db_path) == {"nodes": 3, "edges": 2}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_search_nodes_matches_label_title_and_tags(tmp_path: Path) -> None:
|
| 73 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 74 |
+
build_graph_store(db_path, _sample_graph())
|
| 75 |
+
|
| 76 |
+
results = search_nodes(db_path, "testing", limit=10)
|
| 77 |
+
|
| 78 |
+
assert [row["id"] for row in results] == [
|
| 79 |
+
"skill:python-testing",
|
| 80 |
+
"agent:reviewer",
|
| 81 |
+
]
|
| 82 |
+
assert results[0]["type"] == "skill"
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def test_load_neighborhood_returns_center_and_edges(tmp_path: Path) -> None:
|
| 86 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 87 |
+
build_graph_store(db_path, _sample_graph())
|
| 88 |
+
|
| 89 |
+
neighborhood = load_neighborhood(db_path, "skill:python-testing", limit=10)
|
| 90 |
+
|
| 91 |
+
assert {node["id"] for node in neighborhood["nodes"]} == {
|
| 92 |
+
"skill:python-testing",
|
| 93 |
+
"mcp-server:github",
|
| 94 |
+
"agent:reviewer",
|
| 95 |
+
}
|
| 96 |
+
assert {edge["target"] for edge in neighborhood["edges"]} == {
|
| 97 |
+
"mcp-server:github",
|
| 98 |
+
"agent:reviewer",
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def test_build_graph_store_from_graph_dir_prefers_active_packs(tmp_path: Path) -> None:
|
| 103 |
+
graph_dir = tmp_path / "graphify-out"
|
| 104 |
+
packs_dir = graph_dir / "packs"
|
| 105 |
+
base_graph = nx.Graph()
|
| 106 |
+
base_graph.add_node(
|
| 107 |
+
"skill:base",
|
| 108 |
+
label="base",
|
| 109 |
+
title="Base",
|
| 110 |
+
type="skill",
|
| 111 |
+
tags=["base"],
|
| 112 |
+
)
|
| 113 |
+
base_graph.add_node(
|
| 114 |
+
"mcp-server:github",
|
| 115 |
+
label="github",
|
| 116 |
+
title="GitHub",
|
| 117 |
+
type="mcp-server",
|
| 118 |
+
tags=["github"],
|
| 119 |
+
)
|
| 120 |
+
base_graph.add_edge("skill:base", "mcp-server:github", weight=0.2)
|
| 121 |
+
write_base_pack(
|
| 122 |
+
pack_dir=packs_dir / "base-export-1",
|
| 123 |
+
pack_id="base-export-1",
|
| 124 |
+
base_export_id="export-1",
|
| 125 |
+
config_hash="config-sha",
|
| 126 |
+
model_id="bge-small-en-v1.5",
|
| 127 |
+
graph=base_graph,
|
| 128 |
+
)
|
| 129 |
+
write_overlay_pack(
|
| 130 |
+
pack_dir=packs_dir / "overlay-review",
|
| 131 |
+
pack_id="overlay-review",
|
| 132 |
+
base_export_id="export-1",
|
| 133 |
+
parent_export_id="export-1",
|
| 134 |
+
config_hash="config-sha",
|
| 135 |
+
model_id="bge-small-en-v1.5",
|
| 136 |
+
nodes=[
|
| 137 |
+
{
|
| 138 |
+
"id": "skill:review",
|
| 139 |
+
"label": "review",
|
| 140 |
+
"title": "Code Review",
|
| 141 |
+
"type": "skill",
|
| 142 |
+
"tags": ["review"],
|
| 143 |
+
}
|
| 144 |
+
],
|
| 145 |
+
edges=[
|
| 146 |
+
{
|
| 147 |
+
"source": "skill:review",
|
| 148 |
+
"target": "mcp-server:github",
|
| 149 |
+
"weight": 0.9,
|
| 150 |
+
}
|
| 151 |
+
],
|
| 152 |
+
tombstones=[],
|
| 153 |
+
)
|
| 154 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 155 |
+
|
| 156 |
+
build_graph_store_from_graph_dir(graph_dir, db_path)
|
| 157 |
+
|
| 158 |
+
assert graph_store_stats(db_path) == {"nodes": 3, "edges": 2}
|
| 159 |
+
assert [row["id"] for row in search_nodes(db_path, "review")] == ["skill:review"]
|
| 160 |
+
neighborhood = load_neighborhood(db_path, "skill:review")
|
| 161 |
+
assert {edge["target"] for edge in neighborhood["edges"]} == {"mcp-server:github"}
|
| 162 |
+
metadata = graph_store_metadata(db_path)
|
| 163 |
+
assert metadata["ctx_graph_pack_source"] == "packs"
|
| 164 |
+
assert json.loads(metadata["ctx_pack_ids"]) == ["base-export-1", "overlay-review"]
|
| 165 |
+
assert metadata["ctx_pack_base_export_id"] == "export-1"
|
| 166 |
+
assert metadata["node_count"] == "3"
|
| 167 |
+
assert metadata["edge_count"] == "2"
|
| 168 |
+
assert graph_store_is_fresh(db_path, graph_dir) is True
|
| 169 |
+
write_overlay_pack(
|
| 170 |
+
pack_dir=packs_dir / "overlay-docs",
|
| 171 |
+
pack_id="overlay-docs",
|
| 172 |
+
base_export_id="export-1",
|
| 173 |
+
parent_export_id="export-1",
|
| 174 |
+
config_hash="config-sha",
|
| 175 |
+
model_id="bge-small-en-v1.5",
|
| 176 |
+
nodes=[
|
| 177 |
+
{
|
| 178 |
+
"id": "skill:docs",
|
| 179 |
+
"label": "docs",
|
| 180 |
+
"title": "Docs",
|
| 181 |
+
"type": "skill",
|
| 182 |
+
"tags": ["docs"],
|
| 183 |
+
}
|
| 184 |
+
],
|
| 185 |
+
edges=[],
|
| 186 |
+
tombstones=[],
|
| 187 |
+
)
|
| 188 |
+
assert graph_store_is_fresh(db_path, graph_dir) is False
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def test_graph_store_freshness_tracks_full_pack_manifest_drift(
|
| 192 |
+
tmp_path: Path,
|
| 193 |
+
) -> None:
|
| 194 |
+
graph_dir = tmp_path / "graphify-out"
|
| 195 |
+
packs_dir = graph_dir / "packs"
|
| 196 |
+
base_graph = nx.Graph()
|
| 197 |
+
base_graph.add_node("skill:base", label="base", type="skill", tags=["base"])
|
| 198 |
+
write_base_pack(
|
| 199 |
+
pack_dir=packs_dir / "base-export-1",
|
| 200 |
+
pack_id="base-export-1",
|
| 201 |
+
base_export_id="export-1",
|
| 202 |
+
config_hash="config-sha",
|
| 203 |
+
model_id="bge-small-en-v1.5",
|
| 204 |
+
graph=base_graph,
|
| 205 |
+
)
|
| 206 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 207 |
+
ensure_graph_store(graph_dir, db_path)
|
| 208 |
+
|
| 209 |
+
manifest_path = packs_dir / "base-export-1" / "graph-pack-manifest.json"
|
| 210 |
+
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 211 |
+
manifest["node_count"] = 2
|
| 212 |
+
manifest_path.write_text(
|
| 213 |
+
json.dumps(manifest, indent=2, sort_keys=True) + "\n",
|
| 214 |
+
encoding="utf-8",
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
assert graph_store_is_fresh(db_path, graph_dir) is False
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def test_graph_store_freshness_tracks_entity_overlay_file_with_packs(
|
| 221 |
+
tmp_path: Path,
|
| 222 |
+
) -> None:
|
| 223 |
+
graph_dir = tmp_path / "graphify-out"
|
| 224 |
+
packs_dir = graph_dir / "packs"
|
| 225 |
+
base_graph = nx.Graph()
|
| 226 |
+
base_graph.add_node(
|
| 227 |
+
"skill:base",
|
| 228 |
+
label="base",
|
| 229 |
+
title="Base",
|
| 230 |
+
type="skill",
|
| 231 |
+
tags=["base"],
|
| 232 |
+
)
|
| 233 |
+
base_graph.add_node(
|
| 234 |
+
"mcp-server:github",
|
| 235 |
+
label="github",
|
| 236 |
+
title="GitHub",
|
| 237 |
+
type="mcp-server",
|
| 238 |
+
tags=["github"],
|
| 239 |
+
)
|
| 240 |
+
base_graph.add_edge("skill:base", "mcp-server:github", weight=0.2)
|
| 241 |
+
write_base_pack(
|
| 242 |
+
pack_dir=packs_dir / "base-export-1",
|
| 243 |
+
pack_id="base-export-1",
|
| 244 |
+
base_export_id="export-1",
|
| 245 |
+
config_hash="config-sha",
|
| 246 |
+
model_id="bge-small-en-v1.5",
|
| 247 |
+
graph=base_graph,
|
| 248 |
+
)
|
| 249 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 250 |
+
|
| 251 |
+
assert ensure_graph_store(graph_dir, db_path) == {
|
| 252 |
+
"rebuilt": True,
|
| 253 |
+
"nodes": 2,
|
| 254 |
+
"edges": 1,
|
| 255 |
+
}
|
| 256 |
+
metadata = graph_store_metadata(db_path)
|
| 257 |
+
assert metadata["ctx_graph_store_entity_overlay"] == "absent"
|
| 258 |
+
assert graph_store_is_fresh(db_path, graph_dir) is True
|
| 259 |
+
|
| 260 |
+
(graph_dir / "entity-overlays.jsonl").write_text(
|
| 261 |
+
json.dumps({
|
| 262 |
+
"overlay_id": "overlay-docs",
|
| 263 |
+
"nodes": [{
|
| 264 |
+
"id": "skill:docs",
|
| 265 |
+
"label": "docs",
|
| 266 |
+
"title": "Docs",
|
| 267 |
+
"type": "skill",
|
| 268 |
+
"tags": ["docs"],
|
| 269 |
+
}],
|
| 270 |
+
"edges": [{
|
| 271 |
+
"source": "skill:docs",
|
| 272 |
+
"target": "mcp-server:github",
|
| 273 |
+
"weight": 0.8,
|
| 274 |
+
}],
|
| 275 |
+
})
|
| 276 |
+
+ "\n",
|
| 277 |
+
encoding="utf-8",
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
assert graph_store_is_fresh(db_path, graph_dir) is False
|
| 281 |
+
assert ensure_graph_store(graph_dir, db_path) == {
|
| 282 |
+
"rebuilt": True,
|
| 283 |
+
"nodes": 3,
|
| 284 |
+
"edges": 2,
|
| 285 |
+
}
|
| 286 |
+
metadata = graph_store_metadata(db_path)
|
| 287 |
+
assert metadata["ctx_graph_store_entity_overlay"] == "present"
|
| 288 |
+
assert [row["id"] for row in search_nodes(db_path, "docs")] == ["skill:docs"]
|
| 289 |
+
neighborhood = load_neighborhood(db_path, "skill:docs")
|
| 290 |
+
assert {edge["target"] for edge in neighborhood["edges"]} == {"mcp-server:github"}
|
| 291 |
+
assert graph_store_is_fresh(db_path, graph_dir) is True
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def test_build_graph_store_from_graph_dir_falls_back_to_legacy_graph_json(tmp_path: Path) -> None:
|
| 295 |
+
graph_dir = tmp_path / "graphify-out"
|
| 296 |
+
graph_dir.mkdir()
|
| 297 |
+
graph = _sample_graph()
|
| 298 |
+
payload = nx.node_link_data(graph, edges="edges")
|
| 299 |
+
(graph_dir / "graph.json").write_text(json.dumps(payload), encoding="utf-8")
|
| 300 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 301 |
+
|
| 302 |
+
build_graph_store_from_graph_dir(graph_dir, db_path)
|
| 303 |
+
|
| 304 |
+
assert graph_store_stats(db_path) == {"nodes": 3, "edges": 2}
|
| 305 |
+
assert search_nodes(db_path, "github")[0]["id"] == "mcp-server:github"
|
| 306 |
+
assert graph_store_is_fresh(db_path, graph_dir) is True
|
| 307 |
+
graph.add_node("skill:docs", label="docs", type="skill", tags=["docs"])
|
| 308 |
+
payload = nx.node_link_data(graph, edges="edges")
|
| 309 |
+
(graph_dir / "graph.json").write_text(json.dumps(payload), encoding="utf-8")
|
| 310 |
+
assert graph_store_is_fresh(db_path, graph_dir) is False
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def test_cli_builds_graph_store_from_graph_dir(tmp_path: Path) -> None:
|
| 314 |
+
graph_dir = tmp_path / "graphify-out"
|
| 315 |
+
graph_dir.mkdir()
|
| 316 |
+
payload = nx.node_link_data(_sample_graph(), edges="edges")
|
| 317 |
+
(graph_dir / "graph.json").write_text(json.dumps(payload), encoding="utf-8")
|
| 318 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 319 |
+
|
| 320 |
+
assert main(["build", "--graph-dir", str(graph_dir), "--db", str(db_path)]) == 0
|
| 321 |
+
|
| 322 |
+
assert graph_store_stats(db_path) == {"nodes": 3, "edges": 2}
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def test_cli_validates_fresh_graph_store(tmp_path: Path) -> None:
|
| 326 |
+
graph_dir = tmp_path / "graphify-out"
|
| 327 |
+
graph_dir.mkdir()
|
| 328 |
+
payload = nx.node_link_data(_sample_graph(), edges="edges")
|
| 329 |
+
(graph_dir / "graph.json").write_text(json.dumps(payload), encoding="utf-8")
|
| 330 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 331 |
+
ensure_graph_store(graph_dir, db_path)
|
| 332 |
+
|
| 333 |
+
result = main(["validate", "--graph-dir", str(graph_dir), "--db", str(db_path)])
|
| 334 |
+
|
| 335 |
+
assert result == 0
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def test_cli_validate_returns_1_for_stale_graph_store(tmp_path: Path) -> None:
|
| 339 |
+
graph_dir = tmp_path / "graphify-out"
|
| 340 |
+
graph_dir.mkdir()
|
| 341 |
+
graph = _sample_graph()
|
| 342 |
+
payload = nx.node_link_data(graph, edges="edges")
|
| 343 |
+
(graph_dir / "graph.json").write_text(json.dumps(payload), encoding="utf-8")
|
| 344 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 345 |
+
ensure_graph_store(graph_dir, db_path)
|
| 346 |
+
graph.add_node("skill:docs", label="docs", type="skill", tags=["docs"])
|
| 347 |
+
payload = nx.node_link_data(graph, edges="edges")
|
| 348 |
+
(graph_dir / "graph.json").write_text(json.dumps(payload), encoding="utf-8")
|
| 349 |
+
|
| 350 |
+
result = main(["validate", "--graph-dir", str(graph_dir), "--db", str(db_path)])
|
| 351 |
+
|
| 352 |
+
assert result == 1
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def test_cli_search_reads_built_pack_backed_store(tmp_path: Path, capsys) -> None:
|
| 356 |
+
graph_dir = tmp_path / "graphify-out"
|
| 357 |
+
packs_dir = graph_dir / "packs"
|
| 358 |
+
base_graph = nx.Graph()
|
| 359 |
+
base_graph.add_node("skill:base", label="base", type="skill", tags=["base"])
|
| 360 |
+
write_base_pack(
|
| 361 |
+
pack_dir=packs_dir / "base-export-1",
|
| 362 |
+
pack_id="base-export-1",
|
| 363 |
+
base_export_id="export-1",
|
| 364 |
+
config_hash="config-sha",
|
| 365 |
+
model_id="bge-small-en-v1.5",
|
| 366 |
+
graph=base_graph,
|
| 367 |
+
)
|
| 368 |
+
write_overlay_pack(
|
| 369 |
+
pack_dir=packs_dir / "overlay-review",
|
| 370 |
+
pack_id="overlay-review",
|
| 371 |
+
base_export_id="export-1",
|
| 372 |
+
parent_export_id="export-1",
|
| 373 |
+
config_hash="config-sha",
|
| 374 |
+
model_id="bge-small-en-v1.5",
|
| 375 |
+
nodes=[{
|
| 376 |
+
"id": "agent:reviewer",
|
| 377 |
+
"label": "reviewer",
|
| 378 |
+
"title": "Code Reviewer",
|
| 379 |
+
"type": "agent",
|
| 380 |
+
"tags": ["review"],
|
| 381 |
+
}],
|
| 382 |
+
edges=[],
|
| 383 |
+
tombstones=[],
|
| 384 |
+
)
|
| 385 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 386 |
+
ensure_graph_store(graph_dir, db_path)
|
| 387 |
+
|
| 388 |
+
result = main([
|
| 389 |
+
"search",
|
| 390 |
+
"--db", str(db_path),
|
| 391 |
+
"--graph-dir", str(graph_dir),
|
| 392 |
+
"--query", "review",
|
| 393 |
+
])
|
| 394 |
+
|
| 395 |
+
assert result == 0
|
| 396 |
+
payload = json.loads(capsys.readouterr().out)
|
| 397 |
+
assert [row["id"] for row in payload["results"]] == ["agent:reviewer"]
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def test_cli_search_rejects_stale_store_when_graph_dir_is_required(
|
| 401 |
+
tmp_path: Path,
|
| 402 |
+
capsys,
|
| 403 |
+
) -> None:
|
| 404 |
+
graph_dir = tmp_path / "graphify-out"
|
| 405 |
+
graph_dir.mkdir()
|
| 406 |
+
graph = _sample_graph()
|
| 407 |
+
(graph_dir / "graph.json").write_text(
|
| 408 |
+
json.dumps(nx.node_link_data(graph, edges="edges")),
|
| 409 |
+
encoding="utf-8",
|
| 410 |
+
)
|
| 411 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 412 |
+
ensure_graph_store(graph_dir, db_path)
|
| 413 |
+
graph.add_node("skill:docs", label="docs", type="skill", tags=["docs"])
|
| 414 |
+
(graph_dir / "graph.json").write_text(
|
| 415 |
+
json.dumps(nx.node_link_data(graph, edges="edges")),
|
| 416 |
+
encoding="utf-8",
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
result = main([
|
| 420 |
+
"search",
|
| 421 |
+
"--db", str(db_path),
|
| 422 |
+
"--graph-dir", str(graph_dir),
|
| 423 |
+
"--query", "docs",
|
| 424 |
+
])
|
| 425 |
+
|
| 426 |
+
assert result == 1
|
| 427 |
+
payload = json.loads(capsys.readouterr().out)
|
| 428 |
+
assert payload["ok"] is False
|
| 429 |
+
assert "source fingerprint is stale" in payload["errors"]
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def test_cli_neighborhood_reads_built_pack_backed_store(tmp_path: Path, capsys) -> None:
|
| 433 |
+
graph_dir = tmp_path / "graphify-out"
|
| 434 |
+
packs_dir = graph_dir / "packs"
|
| 435 |
+
base_graph = nx.Graph()
|
| 436 |
+
base_graph.add_node("skill:base", label="base", type="skill", tags=["base"])
|
| 437 |
+
base_graph.add_node("mcp-server:github", label="github", type="mcp-server", tags=["github"])
|
| 438 |
+
write_base_pack(
|
| 439 |
+
pack_dir=packs_dir / "base-export-1",
|
| 440 |
+
pack_id="base-export-1",
|
| 441 |
+
base_export_id="export-1",
|
| 442 |
+
config_hash="config-sha",
|
| 443 |
+
model_id="bge-small-en-v1.5",
|
| 444 |
+
graph=base_graph,
|
| 445 |
+
)
|
| 446 |
+
write_overlay_pack(
|
| 447 |
+
pack_dir=packs_dir / "overlay-review-edge",
|
| 448 |
+
pack_id="overlay-review-edge",
|
| 449 |
+
base_export_id="export-1",
|
| 450 |
+
parent_export_id="export-1",
|
| 451 |
+
config_hash="config-sha",
|
| 452 |
+
model_id="bge-small-en-v1.5",
|
| 453 |
+
nodes=[],
|
| 454 |
+
edges=[{
|
| 455 |
+
"source": "skill:base",
|
| 456 |
+
"target": "mcp-server:github",
|
| 457 |
+
"weight": 0.9,
|
| 458 |
+
}],
|
| 459 |
+
tombstones=[],
|
| 460 |
+
)
|
| 461 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 462 |
+
ensure_graph_store(graph_dir, db_path)
|
| 463 |
+
|
| 464 |
+
result = main([
|
| 465 |
+
"neighborhood",
|
| 466 |
+
"--db", str(db_path),
|
| 467 |
+
"--graph-dir", str(graph_dir),
|
| 468 |
+
"--node-id", "skill:base",
|
| 469 |
+
])
|
| 470 |
+
|
| 471 |
+
assert result == 0
|
| 472 |
+
payload = json.loads(capsys.readouterr().out)
|
| 473 |
+
assert {node["id"] for node in payload["nodes"]} == {
|
| 474 |
+
"skill:base",
|
| 475 |
+
"mcp-server:github",
|
| 476 |
+
}
|
| 477 |
+
assert payload["edges"] == [{
|
| 478 |
+
"attrs": {"weight": 0.9},
|
| 479 |
+
"source": "skill:base",
|
| 480 |
+
"target": "mcp-server:github",
|
| 481 |
+
"weight": 0.9,
|
| 482 |
+
}]
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def test_ensure_graph_store_reuses_fresh_store_and_rebuilds_stale_store(
|
| 486 |
+
tmp_path: Path,
|
| 487 |
+
) -> None:
|
| 488 |
+
graph_dir = tmp_path / "graphify-out"
|
| 489 |
+
graph_dir.mkdir()
|
| 490 |
+
graph = _sample_graph()
|
| 491 |
+
payload = nx.node_link_data(graph, edges="edges")
|
| 492 |
+
(graph_dir / "graph.json").write_text(json.dumps(payload), encoding="utf-8")
|
| 493 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 494 |
+
|
| 495 |
+
first = ensure_graph_store(graph_dir, db_path)
|
| 496 |
+
second = ensure_graph_store(graph_dir, db_path)
|
| 497 |
+
|
| 498 |
+
assert first == {"rebuilt": True, "nodes": 3, "edges": 2}
|
| 499 |
+
assert second == {"rebuilt": False, "nodes": 3, "edges": 2}
|
| 500 |
+
|
| 501 |
+
graph.add_node("skill:docs", label="docs", type="skill", tags=["docs"])
|
| 502 |
+
payload = nx.node_link_data(graph, edges="edges")
|
| 503 |
+
(graph_dir / "graph.json").write_text(json.dumps(payload), encoding="utf-8")
|
| 504 |
+
|
| 505 |
+
third = ensure_graph_store(graph_dir, db_path)
|
| 506 |
+
|
| 507 |
+
assert third == {"rebuilt": True, "nodes": 4, "edges": 2}
|
| 508 |
+
assert search_nodes(db_path, "docs")[0]["id"] == "skill:docs"
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def test_validate_graph_store_reports_fresh_store(tmp_path: Path) -> None:
|
| 512 |
+
graph_dir = tmp_path / "graphify-out"
|
| 513 |
+
graph_dir.mkdir()
|
| 514 |
+
payload = nx.node_link_data(_sample_graph(), edges="edges")
|
| 515 |
+
(graph_dir / "graph.json").write_text(json.dumps(payload), encoding="utf-8")
|
| 516 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 517 |
+
ensure_graph_store(graph_dir, db_path)
|
| 518 |
+
|
| 519 |
+
report = validate_graph_store(db_path, graph_dir)
|
| 520 |
+
|
| 521 |
+
assert report == {
|
| 522 |
+
"ok": True,
|
| 523 |
+
"fresh": True,
|
| 524 |
+
"nodes": 3,
|
| 525 |
+
"edges": 2,
|
| 526 |
+
"errors": [],
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def test_validate_graph_store_reports_stale_source(tmp_path: Path) -> None:
|
| 531 |
+
graph_dir = tmp_path / "graphify-out"
|
| 532 |
+
graph_dir.mkdir()
|
| 533 |
+
graph = _sample_graph()
|
| 534 |
+
payload = nx.node_link_data(graph, edges="edges")
|
| 535 |
+
(graph_dir / "graph.json").write_text(json.dumps(payload), encoding="utf-8")
|
| 536 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 537 |
+
ensure_graph_store(graph_dir, db_path)
|
| 538 |
+
graph.add_node("skill:docs", label="docs", type="skill", tags=["docs"])
|
| 539 |
+
payload = nx.node_link_data(graph, edges="edges")
|
| 540 |
+
(graph_dir / "graph.json").write_text(json.dumps(payload), encoding="utf-8")
|
| 541 |
+
|
| 542 |
+
report = validate_graph_store(db_path, graph_dir)
|
| 543 |
+
|
| 544 |
+
assert report["ok"] is False
|
| 545 |
+
assert report["fresh"] is False
|
| 546 |
+
errors = report["errors"]
|
| 547 |
+
assert isinstance(errors, list)
|
| 548 |
+
assert "source fingerprint is stale" in errors
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def test_validate_graph_store_rejects_missing_source_graph(tmp_path: Path) -> None:
|
| 552 |
+
graph_dir = tmp_path / "graphify-out"
|
| 553 |
+
graph_dir.mkdir()
|
| 554 |
+
payload = nx.node_link_data(_sample_graph(), edges="edges")
|
| 555 |
+
graph_json = graph_dir / "graph.json"
|
| 556 |
+
graph_json.write_text(json.dumps(payload), encoding="utf-8")
|
| 557 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 558 |
+
build_graph_store_from_graph_dir(graph_dir, db_path)
|
| 559 |
+
graph_json.unlink()
|
| 560 |
+
|
| 561 |
+
assert graph_store_is_fresh(db_path, graph_dir) is False
|
| 562 |
+
report = validate_graph_store(db_path, graph_dir)
|
| 563 |
+
|
| 564 |
+
assert report == {
|
| 565 |
+
"ok": False,
|
| 566 |
+
"fresh": False,
|
| 567 |
+
"nodes": 3,
|
| 568 |
+
"edges": 2,
|
| 569 |
+
"errors": ["source graph is missing"],
|
| 570 |
+
}
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def test_build_graph_store_from_graph_dir_rejects_missing_source_graph(tmp_path: Path) -> None:
|
| 574 |
+
graph_dir = tmp_path / "graphify-out"
|
| 575 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 576 |
+
|
| 577 |
+
with pytest.raises(ValueError, match="source graph is missing"):
|
| 578 |
+
build_graph_store_from_graph_dir(graph_dir, db_path)
|
| 579 |
+
|
| 580 |
+
assert not db_path.exists()
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def test_cli_build_returns_1_for_missing_source_graph(tmp_path: Path, capsys) -> None:
|
| 584 |
+
graph_dir = tmp_path / "graphify-out"
|
| 585 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 586 |
+
|
| 587 |
+
result = main(["build", "--graph-dir", str(graph_dir), "--db", str(db_path)])
|
| 588 |
+
|
| 589 |
+
assert result == 1
|
| 590 |
+
assert not db_path.exists()
|
| 591 |
+
payload = json.loads(capsys.readouterr().out)
|
| 592 |
+
assert payload == {"error": "source graph is missing", "ok": False}
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def test_validate_graph_store_reports_corrupt_count_metadata(tmp_path: Path) -> None:
|
| 596 |
+
graph_dir = tmp_path / "graphify-out"
|
| 597 |
+
graph_dir.mkdir()
|
| 598 |
+
payload = nx.node_link_data(_sample_graph(), edges="edges")
|
| 599 |
+
(graph_dir / "graph.json").write_text(json.dumps(payload), encoding="utf-8")
|
| 600 |
+
db_path = tmp_path / "graph.sqlite3"
|
| 601 |
+
ensure_graph_store(graph_dir, db_path)
|
| 602 |
+
with sqlite3.connect(db_path) as conn:
|
| 603 |
+
conn.execute("UPDATE metadata SET value = '99' WHERE key = 'node_count'")
|
| 604 |
+
|
| 605 |
+
report = validate_graph_store(db_path, graph_dir)
|
| 606 |
+
|
| 607 |
+
assert report["ok"] is False
|
| 608 |
+
assert report["fresh"] is True
|
| 609 |
+
errors = report["errors"]
|
| 610 |
+
assert isinstance(errors, list)
|
| 611 |
+
assert "metadata node_count 99 != actual 3" in errors
|
src/tests/test_harness_add.py
CHANGED
|
@@ -10,6 +10,7 @@ import yaml # type: ignore[import-untyped]
|
|
| 10 |
import pytest
|
| 11 |
|
| 12 |
import harness_add
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
def _record(**overrides: Any) -> harness_add.HarnessRecord:
|
|
@@ -31,6 +32,10 @@ def _record(**overrides: Any) -> harness_add.HarnessRecord:
|
|
| 31 |
|
| 32 |
def _frontmatter(path: Path) -> dict[str, Any]:
|
| 33 |
text = path.read_text(encoding="utf-8")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
_, fm_block, _ = text.split("---", 2)
|
| 35 |
parsed = yaml.safe_load(fm_block)
|
| 36 |
assert isinstance(parsed, dict)
|
|
@@ -152,7 +157,18 @@ def test_existing_harness_update_existing_applies_reviewed_change(
|
|
| 152 |
tmp_path: Path,
|
| 153 |
) -> None:
|
| 154 |
wiki = tmp_path / "wiki"
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
result = harness_add.add_harness(
|
| 158 |
record=_record(
|
|
@@ -166,10 +182,12 @@ def test_existing_harness_update_existing_applies_reviewed_change(
|
|
| 166 |
)
|
| 167 |
|
| 168 |
page = wiki / "entities" / "harnesses" / "text-to-cad.md"
|
| 169 |
-
|
|
|
|
| 170 |
assert result["is_new_page"] is False
|
| 171 |
assert result["skipped"] is False
|
| 172 |
assert result["sources"] == ["external-review", "manual"]
|
|
|
|
| 173 |
assert fm["sources"] == ["external-review", "manual"]
|
| 174 |
assert fm["verify_commands"] == ["pytest", "python smoke.py"]
|
| 175 |
|
|
@@ -212,3 +230,27 @@ def test_cli_from_json_adds_harness(
|
|
| 212 |
|
| 213 |
assert (wiki / "entities" / "harnesses" / "text-to-cad.md").exists()
|
| 214 |
assert "added: text-to-cad" in capsys.readouterr().out
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
import pytest
|
| 11 |
|
| 12 |
import harness_add
|
| 13 |
+
from ctx.core.wiki.wiki_packs import load_merged_wiki_pages, write_wiki_base_pack
|
| 14 |
|
| 15 |
|
| 16 |
def _record(**overrides: Any) -> harness_add.HarnessRecord:
|
|
|
|
| 32 |
|
| 33 |
def _frontmatter(path: Path) -> dict[str, Any]:
|
| 34 |
text = path.read_text(encoding="utf-8")
|
| 35 |
+
return _frontmatter_from_text(text)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _frontmatter_from_text(text: str) -> dict[str, Any]:
|
| 39 |
_, fm_block, _ = text.split("---", 2)
|
| 40 |
parsed = yaml.safe_load(fm_block)
|
| 41 |
assert isinstance(parsed, dict)
|
|
|
|
| 157 |
tmp_path: Path,
|
| 158 |
) -> None:
|
| 159 |
wiki = tmp_path / "wiki"
|
| 160 |
+
existing = _record(sources=["manual"])
|
| 161 |
+
packs_dir = wiki / "wiki-packs"
|
| 162 |
+
write_wiki_base_pack(
|
| 163 |
+
pack_dir=packs_dir / "base-export-1",
|
| 164 |
+
pack_id="base-export-1",
|
| 165 |
+
base_export_id="wiki-export-1",
|
| 166 |
+
pages={
|
| 167 |
+
"entities/harnesses/text-to-cad.md": harness_add.generate_harness_page(
|
| 168 |
+
existing
|
| 169 |
+
)
|
| 170 |
+
},
|
| 171 |
+
)
|
| 172 |
|
| 173 |
result = harness_add.add_harness(
|
| 174 |
record=_record(
|
|
|
|
| 182 |
)
|
| 183 |
|
| 184 |
page = wiki / "entities" / "harnesses" / "text-to-cad.md"
|
| 185 |
+
merged = load_merged_wiki_pages(packs_dir)
|
| 186 |
+
fm = _frontmatter_from_text(merged["entities/harnesses/text-to-cad.md"])
|
| 187 |
assert result["is_new_page"] is False
|
| 188 |
assert result["skipped"] is False
|
| 189 |
assert result["sources"] == ["external-review", "manual"]
|
| 190 |
+
assert not page.exists()
|
| 191 |
assert fm["sources"] == ["external-review", "manual"]
|
| 192 |
assert fm["verify_commands"] == ["pytest", "python smoke.py"]
|
| 193 |
|
|
|
|
| 230 |
|
| 231 |
assert (wiki / "entities" / "harnesses" / "text-to-cad.md").exists()
|
| 232 |
assert "added: text-to-cad" in capsys.readouterr().out
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def test_cli_from_bom_json_adds_harness(
|
| 236 |
+
tmp_path: Path,
|
| 237 |
+
capsys: Any,
|
| 238 |
+
) -> None:
|
| 239 |
+
record_path = tmp_path / "harness.json"
|
| 240 |
+
record_path.write_text(
|
| 241 |
+
"\ufeff"
|
| 242 |
+
+ json.dumps(
|
| 243 |
+
{
|
| 244 |
+
"repo_url": "https://github.com/example/bom-harness",
|
| 245 |
+
"description": "Harness loaded from a Windows UTF-8 BOM JSON file.",
|
| 246 |
+
"tags": ["llm", "testing"],
|
| 247 |
+
}
|
| 248 |
+
),
|
| 249 |
+
encoding="utf-8",
|
| 250 |
+
)
|
| 251 |
+
wiki = tmp_path / "wiki"
|
| 252 |
+
|
| 253 |
+
harness_add.main(["--from-json", str(record_path), "--wiki", str(wiki)])
|
| 254 |
+
|
| 255 |
+
assert (wiki / "entities" / "harnesses" / "bom-harness.md").exists()
|
| 256 |
+
assert "added: bom-harness" in capsys.readouterr().out
|
src/tests/test_harness_cli_run.py
CHANGED
|
@@ -28,7 +28,9 @@ from typing import Any
|
|
| 28 |
|
| 29 |
import pytest
|
| 30 |
|
|
|
|
| 31 |
import ctx.cli.run as run_cli
|
|
|
|
| 32 |
from ctx.cli.run import (
|
| 33 |
_apply_mcp_env_overlays,
|
| 34 |
_compile_tool_policy,
|
|
@@ -39,6 +41,7 @@ from ctx.cli.run import (
|
|
| 39 |
main,
|
| 40 |
)
|
| 41 |
from ctx.adapters.generic.providers import ToolCall, Usage
|
|
|
|
| 42 |
|
| 43 |
|
| 44 |
# ── Fixture: fake litellm so --provider ollama (no key) works ───────────────
|
|
@@ -93,6 +96,28 @@ def _tool_call_completion(name: str) -> dict[str, Any]:
|
|
| 93 |
}
|
| 94 |
|
| 95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
# ── _model_provider_prefix ─────────────────────────────────────────────────
|
| 97 |
|
| 98 |
|
|
@@ -124,9 +149,11 @@ class TestResolveApiKeyEnv:
|
|
| 124 |
def test_inferred_from_model_prefix(self) -> None:
|
| 125 |
assert _resolve_api_key_env(None, "openrouter/x", None) == "OPENROUTER_API_KEY"
|
| 126 |
assert _resolve_api_key_env(None, "anthropic/claude", None) == "ANTHROPIC_API_KEY"
|
|
|
|
| 127 |
|
| 128 |
def test_inferred_from_provider_flag(self) -> None:
|
| 129 |
assert _resolve_api_key_env(None, "custom-x", "openai") == "OPENAI_API_KEY"
|
|
|
|
| 130 |
|
| 131 |
def test_ollama_returns_none(self) -> None:
|
| 132 |
assert _resolve_api_key_env(None, "ollama/llama3", None) is None
|
|
@@ -749,6 +776,12 @@ class TestRunCommand:
|
|
| 749 |
capsys: pytest.CaptureFixture[str],
|
| 750 |
monkeypatch: pytest.MonkeyPatch,
|
| 751 |
) -> None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 752 |
lifecycle_dir = tmp_path / "runtime"
|
| 753 |
monkeypatch.setenv("CTX_RUNTIME_LIFECYCLE_DIR", str(lifecycle_dir))
|
| 754 |
exit_code = main(
|
|
@@ -775,7 +808,20 @@ class TestRunCommand:
|
|
| 775 |
"session_end",
|
| 776 |
]
|
| 777 |
assert events[0]["session_id"] == "lifecycle-run"
|
| 778 |
-
assert events[0]["payload"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 779 |
tool = next(
|
| 780 |
item for item in fake_litellm._calls[0]["tools"]
|
| 781 |
if item["function"]["name"] == "ctx__load_entity"
|
|
@@ -783,6 +829,105 @@ class TestRunCommand:
|
|
| 783 |
assert "session_id" not in tool["function"]["parameters"]["properties"]
|
| 784 |
assert "session_id" not in tool["function"]["parameters"]["required"]
|
| 785 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 786 |
|
| 787 |
# ── Subcommand: sessions ──────────────────────────────────────────────────
|
| 788 |
|
|
@@ -971,6 +1116,12 @@ class TestResumeCommand:
|
|
| 971 |
capsys: pytest.CaptureFixture[str],
|
| 972 |
monkeypatch: pytest.MonkeyPatch,
|
| 973 |
) -> None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 974 |
lifecycle_dir = tmp_path / "runtime"
|
| 975 |
monkeypatch.setenv("CTX_RUNTIME_LIFECYCLE_DIR", str(lifecycle_dir))
|
| 976 |
sessions_dir = tmp_path / "sessions"
|
|
@@ -1009,7 +1160,23 @@ class TestResumeCommand:
|
|
| 1009 |
"session_end",
|
| 1010 |
]
|
| 1011 |
assert events[2]["event_type"] == "resume_task"
|
| 1012 |
-
assert events[2]["payload"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1013 |
resume_call = fake_litellm._calls[-1]
|
| 1014 |
tool = next(
|
| 1015 |
item for item in resume_call["tools"]
|
|
@@ -1018,6 +1185,160 @@ class TestResumeCommand:
|
|
| 1018 |
assert "session_id" not in tool["function"]["parameters"]["properties"]
|
| 1019 |
assert "session_id" not in tool["function"]["parameters"]["required"]
|
| 1020 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1021 |
def test_resume_reuses_recorded_provider_settings(
|
| 1022 |
self,
|
| 1023 |
fake_litellm: Any,
|
|
|
|
| 28 |
|
| 29 |
import pytest
|
| 30 |
|
| 31 |
+
import ctx.adapters.generic.runtime_lifecycle as runtime_lifecycle
|
| 32 |
import ctx.cli.run as run_cli
|
| 33 |
+
import ctx.telemetry as telemetry
|
| 34 |
from ctx.cli.run import (
|
| 35 |
_apply_mcp_env_overlays,
|
| 36 |
_compile_tool_policy,
|
|
|
|
| 41 |
main,
|
| 42 |
)
|
| 43 |
from ctx.adapters.generic.providers import ToolCall, Usage
|
| 44 |
+
from ctx.telemetry import read_events, record_event as real_record_event
|
| 45 |
|
| 46 |
|
| 47 |
# ── Fixture: fake litellm so --provider ollama (no key) works ───────────────
|
|
|
|
| 96 |
}
|
| 97 |
|
| 98 |
|
| 99 |
+
def _enable_real_telemetry(
|
| 100 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 101 |
+
tmp_path: Path,
|
| 102 |
+
) -> Path:
|
| 103 |
+
path = tmp_path / "telemetry" / "events.jsonl"
|
| 104 |
+
config = {
|
| 105 |
+
"enabled": True,
|
| 106 |
+
"mode": "local_redacted",
|
| 107 |
+
"path": str(path),
|
| 108 |
+
"export": {"enabled": False},
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
def config_get(key: str, default: Any) -> Any:
|
| 112 |
+
return config if key == "telemetry" else default
|
| 113 |
+
|
| 114 |
+
monkeypatch.setattr(telemetry, "_config_get", config_get)
|
| 115 |
+
monkeypatch.setattr(telemetry, "record_event", real_record_event)
|
| 116 |
+
monkeypatch.setattr(run_cli, "record_event", real_record_event)
|
| 117 |
+
monkeypatch.setattr(runtime_lifecycle, "record_event", real_record_event)
|
| 118 |
+
return path
|
| 119 |
+
|
| 120 |
+
|
| 121 |
# ── _model_provider_prefix ─────────────────────────────────────────────────
|
| 122 |
|
| 123 |
|
|
|
|
| 149 |
def test_inferred_from_model_prefix(self) -> None:
|
| 150 |
assert _resolve_api_key_env(None, "openrouter/x", None) == "OPENROUTER_API_KEY"
|
| 151 |
assert _resolve_api_key_env(None, "anthropic/claude", None) == "ANTHROPIC_API_KEY"
|
| 152 |
+
assert _resolve_api_key_env(None, "huggingface/org-model", None) == "HF_TOKEN"
|
| 153 |
|
| 154 |
def test_inferred_from_provider_flag(self) -> None:
|
| 155 |
assert _resolve_api_key_env(None, "custom-x", "openai") == "OPENAI_API_KEY"
|
| 156 |
+
assert _resolve_api_key_env(None, "custom-x", "huggingface") == "HF_TOKEN"
|
| 157 |
|
| 158 |
def test_ollama_returns_none(self) -> None:
|
| 159 |
assert _resolve_api_key_env(None, "ollama/llama3", None) is None
|
|
|
|
| 776 |
capsys: pytest.CaptureFixture[str],
|
| 777 |
monkeypatch: pytest.MonkeyPatch,
|
| 778 |
) -> None:
|
| 779 |
+
telemetry_events: list[dict[str, Any]] = []
|
| 780 |
+
|
| 781 |
+
def capture_record_event(event_name: str, **kwargs: Any) -> None:
|
| 782 |
+
telemetry_events.append({"event_name": event_name, **kwargs})
|
| 783 |
+
|
| 784 |
+
monkeypatch.setattr(run_cli, "record_event", capture_record_event)
|
| 785 |
lifecycle_dir = tmp_path / "runtime"
|
| 786 |
monkeypatch.setenv("CTX_RUNTIME_LIFECYCLE_DIR", str(lifecycle_dir))
|
| 787 |
exit_code = main(
|
|
|
|
| 808 |
"session_end",
|
| 809 |
]
|
| 810 |
assert events[0]["session_id"] == "lifecycle-run"
|
| 811 |
+
assert "task" not in events[0]["payload"]
|
| 812 |
+
assert events[0]["payload"]["task_hash"].startswith("sha256:")
|
| 813 |
+
assert "hi" not in json.dumps(events[0])
|
| 814 |
+
cli_events = [
|
| 815 |
+
event for event in telemetry_events
|
| 816 |
+
if event["event_name"] == "ctx.cli.run"
|
| 817 |
+
]
|
| 818 |
+
assert [event["payload"]["ctx.run.phase"] for event in cli_events] == [
|
| 819 |
+
"started",
|
| 820 |
+
"finished",
|
| 821 |
+
]
|
| 822 |
+
assert cli_events[0]["payload"]["ctx.task.length"] == len("hi")
|
| 823 |
+
assert cli_events[-1]["payload"]["ctx.stop_reason"] == "completed"
|
| 824 |
+
assert "hi" not in json.dumps([event["payload"] for event in cli_events])
|
| 825 |
tool = next(
|
| 826 |
item for item in fake_litellm._calls[0]["tools"]
|
| 827 |
if item["function"]["name"] == "ctx__load_entity"
|
|
|
|
| 829 |
assert "session_id" not in tool["function"]["parameters"]["properties"]
|
| 830 |
assert "session_id" not in tool["function"]["parameters"]["required"]
|
| 831 |
|
| 832 |
+
def test_run_telemetry_correlates_cli_and_runtime_lifecycle(
|
| 833 |
+
self,
|
| 834 |
+
fake_litellm: Any,
|
| 835 |
+
tmp_path: Path,
|
| 836 |
+
capsys: pytest.CaptureFixture[str],
|
| 837 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 838 |
+
) -> None:
|
| 839 |
+
telemetry_path = _enable_real_telemetry(monkeypatch, tmp_path)
|
| 840 |
+
lifecycle_dir = tmp_path / "runtime"
|
| 841 |
+
monkeypatch.setenv("CTX_RUNTIME_LIFECYCLE_DIR", str(lifecycle_dir))
|
| 842 |
+
|
| 843 |
+
exit_code = main(
|
| 844 |
+
[
|
| 845 |
+
"run",
|
| 846 |
+
"--model", "ollama/x",
|
| 847 |
+
"--task", "hi",
|
| 848 |
+
"--sessions-dir", str(tmp_path / "sessions"),
|
| 849 |
+
"--session-id", "trace-run",
|
| 850 |
+
"--quiet",
|
| 851 |
+
]
|
| 852 |
+
)
|
| 853 |
+
|
| 854 |
+
assert exit_code == 0
|
| 855 |
+
capsys.readouterr()
|
| 856 |
+
events = list(read_events(telemetry_path, trusted_root=tmp_path))
|
| 857 |
+
cli_events = [event for event in events if event.event_name == "ctx.cli.run"]
|
| 858 |
+
lifecycle_events = [
|
| 859 |
+
event for event in events
|
| 860 |
+
if event.event_name == "ctx.runtime_lifecycle.record"
|
| 861 |
+
]
|
| 862 |
+
|
| 863 |
+
assert [event.payload["ctx.run.phase"] for event in cli_events] == [
|
| 864 |
+
"started",
|
| 865 |
+
"finished",
|
| 866 |
+
]
|
| 867 |
+
assert [event.payload["ctx.lifecycle.action"] for event in lifecycle_events] == [
|
| 868 |
+
"dev_event",
|
| 869 |
+
"session_end",
|
| 870 |
+
]
|
| 871 |
+
assert cli_events[0].trace_id is not None
|
| 872 |
+
assert cli_events[0].span_id is not None
|
| 873 |
+
assert cli_events[1].trace_id == cli_events[0].trace_id
|
| 874 |
+
assert cli_events[1].span_id == cli_events[0].span_id
|
| 875 |
+
assert all(event.trace_id == cli_events[0].trace_id for event in lifecycle_events)
|
| 876 |
+
assert all(event.parent_span_id == cli_events[0].span_id for event in lifecycle_events)
|
| 877 |
+
assert {event.span_id for event in lifecycle_events}.isdisjoint(
|
| 878 |
+
{cli_events[0].span_id}
|
| 879 |
+
)
|
| 880 |
+
assert "hi" not in telemetry_path.read_text(encoding="utf-8")
|
| 881 |
+
|
| 882 |
+
def test_run_exception_telemetry_hashes_provider_error(
|
| 883 |
+
self,
|
| 884 |
+
fake_litellm: Any,
|
| 885 |
+
tmp_path: Path,
|
| 886 |
+
capsys: pytest.CaptureFixture[str],
|
| 887 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 888 |
+
) -> None:
|
| 889 |
+
telemetry_path = _enable_real_telemetry(monkeypatch, tmp_path)
|
| 890 |
+
|
| 891 |
+
def fail_run_loop(*_args: Any, **_kwargs: Any) -> None:
|
| 892 |
+
raise RuntimeError(
|
| 893 |
+
"private provider failure for /Users/example/private-repo"
|
| 894 |
+
)
|
| 895 |
+
|
| 896 |
+
monkeypatch.setattr(run_cli, "run_loop", fail_run_loop)
|
| 897 |
+
|
| 898 |
+
with pytest.raises(RuntimeError):
|
| 899 |
+
main(
|
| 900 |
+
[
|
| 901 |
+
"run",
|
| 902 |
+
"--model", "ollama/x",
|
| 903 |
+
"--task", "private run task",
|
| 904 |
+
"--sessions-dir", str(tmp_path / "sessions"),
|
| 905 |
+
"--session-id", "trace-run-error",
|
| 906 |
+
"--no-ctx-tools",
|
| 907 |
+
"--quiet",
|
| 908 |
+
]
|
| 909 |
+
)
|
| 910 |
+
|
| 911 |
+
capsys.readouterr()
|
| 912 |
+
events = [
|
| 913 |
+
event for event in read_events(telemetry_path, trusted_root=tmp_path)
|
| 914 |
+
if event.event_name == "ctx.cli.run"
|
| 915 |
+
]
|
| 916 |
+
assert [event.payload["ctx.run.phase"] for event in events] == [
|
| 917 |
+
"started",
|
| 918 |
+
"failed",
|
| 919 |
+
]
|
| 920 |
+
failed = events[-1]
|
| 921 |
+
assert failed.outcome == "error"
|
| 922 |
+
assert failed.error_kind == "RuntimeError"
|
| 923 |
+
assert failed.payload["ctx.exception.message_hash"].startswith("sha256:")
|
| 924 |
+
assert failed.payload["ctx.exception.stack_hash"].startswith("sha256:")
|
| 925 |
+
assert failed.payload["ctx.exception.escaped"] is True
|
| 926 |
+
raw = telemetry_path.read_text(encoding="utf-8")
|
| 927 |
+
assert "private provider failure" not in raw
|
| 928 |
+
assert "/Users/example/private-repo" not in raw
|
| 929 |
+
assert "private run task" not in raw
|
| 930 |
+
|
| 931 |
|
| 932 |
# ── Subcommand: sessions ──────────────────────────────────────────────────
|
| 933 |
|
|
|
|
| 1116 |
capsys: pytest.CaptureFixture[str],
|
| 1117 |
monkeypatch: pytest.MonkeyPatch,
|
| 1118 |
) -> None:
|
| 1119 |
+
telemetry_events: list[dict[str, Any]] = []
|
| 1120 |
+
|
| 1121 |
+
def capture_record_event(event_name: str, **kwargs: Any) -> None:
|
| 1122 |
+
telemetry_events.append({"event_name": event_name, **kwargs})
|
| 1123 |
+
|
| 1124 |
+
monkeypatch.setattr(run_cli, "record_event", capture_record_event)
|
| 1125 |
lifecycle_dir = tmp_path / "runtime"
|
| 1126 |
monkeypatch.setenv("CTX_RUNTIME_LIFECYCLE_DIR", str(lifecycle_dir))
|
| 1127 |
sessions_dir = tmp_path / "sessions"
|
|
|
|
| 1160 |
"session_end",
|
| 1161 |
]
|
| 1162 |
assert events[2]["event_type"] == "resume_task"
|
| 1163 |
+
assert "task" not in events[2]["payload"]
|
| 1164 |
+
assert events[2]["payload"]["task_hash"].startswith("sha256:")
|
| 1165 |
+
assert "follow-up" not in json.dumps(events[2])
|
| 1166 |
+
resume_events = [
|
| 1167 |
+
event for event in telemetry_events
|
| 1168 |
+
if event["event_name"] == "ctx.cli.resume"
|
| 1169 |
+
]
|
| 1170 |
+
assert [event["payload"]["ctx.run.phase"] for event in resume_events] == [
|
| 1171 |
+
"started",
|
| 1172 |
+
"finished",
|
| 1173 |
+
]
|
| 1174 |
+
assert resume_events[0]["payload"]["ctx.messages.prior_count"] > 0
|
| 1175 |
+
assert resume_events[0]["payload"]["ctx.task.length"] == len("follow-up")
|
| 1176 |
+
assert resume_events[-1]["payload"]["ctx.stop_reason"] == "completed"
|
| 1177 |
+
assert "follow-up" not in json.dumps(
|
| 1178 |
+
[event["payload"] for event in resume_events]
|
| 1179 |
+
)
|
| 1180 |
resume_call = fake_litellm._calls[-1]
|
| 1181 |
tool = next(
|
| 1182 |
item for item in resume_call["tools"]
|
|
|
|
| 1185 |
assert "session_id" not in tool["function"]["parameters"]["properties"]
|
| 1186 |
assert "session_id" not in tool["function"]["parameters"]["required"]
|
| 1187 |
|
| 1188 |
+
def test_resume_telemetry_correlates_cli_and_runtime_lifecycle(
|
| 1189 |
+
self,
|
| 1190 |
+
fake_litellm: Any,
|
| 1191 |
+
tmp_path: Path,
|
| 1192 |
+
capsys: pytest.CaptureFixture[str],
|
| 1193 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 1194 |
+
) -> None:
|
| 1195 |
+
telemetry_path = _enable_real_telemetry(monkeypatch, tmp_path)
|
| 1196 |
+
lifecycle_dir = tmp_path / "runtime"
|
| 1197 |
+
monkeypatch.setenv("CTX_RUNTIME_LIFECYCLE_DIR", str(lifecycle_dir))
|
| 1198 |
+
sessions_dir = tmp_path / "sessions"
|
| 1199 |
+
main(
|
| 1200 |
+
[
|
| 1201 |
+
"run",
|
| 1202 |
+
"--model", "ollama/x",
|
| 1203 |
+
"--task", "first",
|
| 1204 |
+
"--sessions-dir", str(sessions_dir),
|
| 1205 |
+
"--session-id", "trace-resume",
|
| 1206 |
+
"--quiet",
|
| 1207 |
+
]
|
| 1208 |
+
)
|
| 1209 |
+
capsys.readouterr()
|
| 1210 |
+
|
| 1211 |
+
exit_code = main(
|
| 1212 |
+
[
|
| 1213 |
+
"resume", "trace-resume",
|
| 1214 |
+
"--task", "follow-up",
|
| 1215 |
+
"--sessions-dir", str(sessions_dir),
|
| 1216 |
+
"--quiet",
|
| 1217 |
+
]
|
| 1218 |
+
)
|
| 1219 |
+
|
| 1220 |
+
assert exit_code == 0
|
| 1221 |
+
capsys.readouterr()
|
| 1222 |
+
events = list(read_events(telemetry_path, trusted_root=tmp_path))
|
| 1223 |
+
run_cli_events = [event for event in events if event.event_name == "ctx.cli.run"]
|
| 1224 |
+
resume_cli_events = [
|
| 1225 |
+
event for event in events if event.event_name == "ctx.cli.resume"
|
| 1226 |
+
]
|
| 1227 |
+
lifecycle_events = [
|
| 1228 |
+
event for event in events
|
| 1229 |
+
if event.event_name == "ctx.runtime_lifecycle.record"
|
| 1230 |
+
]
|
| 1231 |
+
resume_trace_id = resume_cli_events[0].trace_id
|
| 1232 |
+
resume_span_id = resume_cli_events[0].span_id
|
| 1233 |
+
resume_lifecycle_events = [
|
| 1234 |
+
event for event in lifecycle_events
|
| 1235 |
+
if event.trace_id == resume_trace_id
|
| 1236 |
+
]
|
| 1237 |
+
|
| 1238 |
+
assert [event.payload["ctx.run.phase"] for event in resume_cli_events] == [
|
| 1239 |
+
"started",
|
| 1240 |
+
"finished",
|
| 1241 |
+
]
|
| 1242 |
+
assert [event.payload["ctx.lifecycle.action"] for event in resume_lifecycle_events] == [
|
| 1243 |
+
"dev_event",
|
| 1244 |
+
"session_end",
|
| 1245 |
+
]
|
| 1246 |
+
assert resume_trace_id is not None
|
| 1247 |
+
assert resume_span_id is not None
|
| 1248 |
+
assert resume_cli_events[1].trace_id == resume_trace_id
|
| 1249 |
+
assert resume_cli_events[1].span_id == resume_span_id
|
| 1250 |
+
assert run_cli_events[0].trace_id != resume_trace_id
|
| 1251 |
+
assert all(event.parent_span_id == resume_span_id for event in resume_lifecycle_events)
|
| 1252 |
+
assert "follow-up" not in telemetry_path.read_text(encoding="utf-8")
|
| 1253 |
+
|
| 1254 |
+
def test_resume_exception_telemetry_hashes_provider_error(
|
| 1255 |
+
self,
|
| 1256 |
+
fake_litellm: Any,
|
| 1257 |
+
tmp_path: Path,
|
| 1258 |
+
capsys: pytest.CaptureFixture[str],
|
| 1259 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 1260 |
+
) -> None:
|
| 1261 |
+
telemetry_path = _enable_real_telemetry(monkeypatch, tmp_path)
|
| 1262 |
+
sessions_dir = tmp_path / "sessions"
|
| 1263 |
+
main(
|
| 1264 |
+
[
|
| 1265 |
+
"run",
|
| 1266 |
+
"--model", "ollama/x",
|
| 1267 |
+
"--task", "first",
|
| 1268 |
+
"--sessions-dir", str(sessions_dir),
|
| 1269 |
+
"--session-id", "trace-resume-error",
|
| 1270 |
+
"--no-ctx-tools",
|
| 1271 |
+
"--quiet",
|
| 1272 |
+
]
|
| 1273 |
+
)
|
| 1274 |
+
capsys.readouterr()
|
| 1275 |
+
|
| 1276 |
+
def fail_run_loop(*_args: Any, **_kwargs: Any) -> None:
|
| 1277 |
+
raise RuntimeError(
|
| 1278 |
+
"private resume provider failure for /Users/example/private-repo"
|
| 1279 |
+
)
|
| 1280 |
+
|
| 1281 |
+
monkeypatch.setattr(run_cli, "run_loop", fail_run_loop)
|
| 1282 |
+
|
| 1283 |
+
with pytest.raises(RuntimeError):
|
| 1284 |
+
main(
|
| 1285 |
+
[
|
| 1286 |
+
"resume",
|
| 1287 |
+
"trace-resume-error",
|
| 1288 |
+
"--task", "private resume task",
|
| 1289 |
+
"--sessions-dir", str(sessions_dir),
|
| 1290 |
+
"--quiet",
|
| 1291 |
+
]
|
| 1292 |
+
)
|
| 1293 |
+
|
| 1294 |
+
capsys.readouterr()
|
| 1295 |
+
events = [
|
| 1296 |
+
event for event in read_events(telemetry_path, trusted_root=tmp_path)
|
| 1297 |
+
if event.event_name == "ctx.cli.resume"
|
| 1298 |
+
]
|
| 1299 |
+
assert [event.payload["ctx.run.phase"] for event in events] == [
|
| 1300 |
+
"started",
|
| 1301 |
+
"failed",
|
| 1302 |
+
]
|
| 1303 |
+
failed = events[-1]
|
| 1304 |
+
assert failed.outcome == "error"
|
| 1305 |
+
assert failed.error_kind == "RuntimeError"
|
| 1306 |
+
assert failed.payload["ctx.exception.message_hash"].startswith("sha256:")
|
| 1307 |
+
assert failed.payload["ctx.exception.stack_hash"].startswith("sha256:")
|
| 1308 |
+
assert failed.payload["ctx.exception.escaped"] is True
|
| 1309 |
+
raw = telemetry_path.read_text(encoding="utf-8")
|
| 1310 |
+
assert "private resume provider failure" not in raw
|
| 1311 |
+
assert "/Users/example/private-repo" not in raw
|
| 1312 |
+
assert "private resume task" not in raw
|
| 1313 |
+
|
| 1314 |
+
def test_runtime_lifecycle_respects_telemetry_disabled(
|
| 1315 |
+
self,
|
| 1316 |
+
fake_litellm: Any,
|
| 1317 |
+
tmp_path: Path,
|
| 1318 |
+
capsys: pytest.CaptureFixture[str],
|
| 1319 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 1320 |
+
) -> None:
|
| 1321 |
+
import ctx.adapters.generic.runtime_lifecycle as runtime_lifecycle
|
| 1322 |
+
|
| 1323 |
+
lifecycle_dir = tmp_path / "runtime"
|
| 1324 |
+
monkeypatch.setenv("CTX_RUNTIME_LIFECYCLE_DIR", str(lifecycle_dir))
|
| 1325 |
+
monkeypatch.setattr(runtime_lifecycle, "telemetry_enabled", lambda: False)
|
| 1326 |
+
|
| 1327 |
+
exit_code = main(
|
| 1328 |
+
[
|
| 1329 |
+
"run",
|
| 1330 |
+
"--model", "ollama/x",
|
| 1331 |
+
"--task", "private task",
|
| 1332 |
+
"--sessions-dir", str(tmp_path / "sessions"),
|
| 1333 |
+
"--session-id", "lifecycle-disabled",
|
| 1334 |
+
"--quiet",
|
| 1335 |
+
]
|
| 1336 |
+
)
|
| 1337 |
+
|
| 1338 |
+
assert exit_code == 0
|
| 1339 |
+
capsys.readouterr()
|
| 1340 |
+
assert not (lifecycle_dir / "events.jsonl").exists()
|
| 1341 |
+
|
| 1342 |
def test_resume_reuses_recorded_provider_settings(
|
| 1343 |
self,
|
| 1344 |
fake_litellm: Any,
|
src/tests/test_harness_ctx_core.py
CHANGED
|
@@ -15,7 +15,9 @@ from __future__ import annotations
|
|
| 15 |
|
| 16 |
import json
|
| 17 |
import os
|
|
|
|
| 18 |
from pathlib import Path
|
|
|
|
| 19 |
from typing import Any
|
| 20 |
|
| 21 |
import networkx as nx
|
|
@@ -30,6 +32,8 @@ from ctx.adapters.generic.ctx_core_tools import (
|
|
| 30 |
make_tool_executor,
|
| 31 |
)
|
| 32 |
from ctx.adapters.generic.providers import ToolCall, ToolDefinition
|
|
|
|
|
|
|
| 33 |
|
| 34 |
|
| 35 |
# ── Helpers: build a synthetic wiki + graph for the toolbox ────────────────
|
|
@@ -187,6 +191,81 @@ def test_graph_cache_reloads_when_graph_json_changes(tmp_path: Path) -> None:
|
|
| 187 |
assert second["results"][0]["name"] == "new-target"
|
| 188 |
|
| 189 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
def test_graph_file_signature_detects_same_size_rewrite(
|
| 191 |
tmp_path: Path,
|
| 192 |
) -> None:
|
|
@@ -231,6 +310,48 @@ def test_wiki_page_cache_reloads_when_entity_page_changes(tmp_path: Path) -> Non
|
|
| 231 |
assert second["results"][0]["slug"] == "new-skill"
|
| 232 |
|
| 233 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
def test_semantic_miss_cache_clears_when_embedding_artifacts_change(
|
| 235 |
tmp_path: Path,
|
| 236 |
monkeypatch: pytest.MonkeyPatch,
|
|
@@ -296,6 +417,27 @@ class TestToolDefinitions:
|
|
| 296 |
)
|
| 297 |
assert td.parameters["required"] == ["seeds"]
|
| 298 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
|
| 300 |
# ── Namespace + dispatch ───────────────────────────────────────────────────
|
| 301 |
|
|
@@ -315,8 +457,135 @@ class TestDispatchRouting:
|
|
| 315 |
with pytest.raises(ValueError, match="unknown ctx-core tool"):
|
| 316 |
toolbox.dispatch(ToolCall(id="c1", name="ctx__bogus", arguments={}))
|
| 317 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
|
| 319 |
class TestRuntimeLifecycle:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
def test_lifecycle_tools_append_events(
|
| 321 |
self,
|
| 322 |
toolbox: CtxCoreToolbox,
|
|
@@ -724,6 +993,42 @@ def test_session_state_suppresses_current_dev_window_unloads(
|
|
| 724 |
|
| 725 |
|
| 726 |
class TestRecommendBundle:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 727 |
def test_happy_path_ranks_by_tag_overlap(
|
| 728 |
self, toolbox: CtxCoreToolbox
|
| 729 |
) -> None:
|
|
@@ -1106,6 +1411,51 @@ class TestWikiGet:
|
|
| 1106 |
assert result["wikilink"] == "[[entities/mcp-servers/f/filesystem]]"
|
| 1107 |
assert "Filesystem MCP" in result["body"]
|
| 1108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1109 |
|
| 1110 |
# ── _query_to_tags ────────────────────────────────────────────────────────
|
| 1111 |
|
|
|
|
| 15 |
|
| 16 |
import json
|
| 17 |
import os
|
| 18 |
+
import sys
|
| 19 |
from pathlib import Path
|
| 20 |
+
from types import SimpleNamespace
|
| 21 |
from typing import Any
|
| 22 |
|
| 23 |
import networkx as nx
|
|
|
|
| 32 |
make_tool_executor,
|
| 33 |
)
|
| 34 |
from ctx.adapters.generic.providers import ToolCall, ToolDefinition
|
| 35 |
+
from ctx.core.graph.graph_packs import write_base_pack, write_overlay_pack
|
| 36 |
+
from ctx.core.wiki.wiki_packs import write_wiki_base_pack, write_wiki_overlay_pack
|
| 37 |
|
| 38 |
|
| 39 |
# ── Helpers: build a synthetic wiki + graph for the toolbox ────────────────
|
|
|
|
| 191 |
assert second["results"][0]["name"] == "new-target"
|
| 192 |
|
| 193 |
|
| 194 |
+
def test_graph_cache_reloads_when_graph_pack_overlay_changes(tmp_path: Path) -> None:
|
| 195 |
+
graph_dir = tmp_path / "graphify-out"
|
| 196 |
+
graph_path = graph_dir / "graph.json"
|
| 197 |
+
packs_dir = graph_dir / "packs"
|
| 198 |
+
base = nx.Graph()
|
| 199 |
+
base.add_node("skill:seed", label="seed", type="skill", tags=[])
|
| 200 |
+
base.add_node("skill:old-target", label="old-target", type="skill", tags=[])
|
| 201 |
+
base.add_edge("skill:seed", "skill:old-target", weight=1.0)
|
| 202 |
+
write_base_pack(
|
| 203 |
+
pack_dir=packs_dir / "base-export-1",
|
| 204 |
+
pack_id="base-export-1",
|
| 205 |
+
base_export_id="export-1",
|
| 206 |
+
config_hash="config-1",
|
| 207 |
+
model_id="model-1",
|
| 208 |
+
graph=base,
|
| 209 |
+
)
|
| 210 |
+
toolbox = CtxCoreToolbox(wiki_dir=tmp_path / "wiki", graph_path=graph_path)
|
| 211 |
+
|
| 212 |
+
first = json.loads(toolbox.dispatch(ToolCall(
|
| 213 |
+
id="c1",
|
| 214 |
+
name="ctx__graph_query",
|
| 215 |
+
arguments={"seeds": ["seed"], "max_hops": 1},
|
| 216 |
+
)))
|
| 217 |
+
write_overlay_pack(
|
| 218 |
+
pack_dir=packs_dir / "overlay-new-target",
|
| 219 |
+
pack_id="overlay-new-target",
|
| 220 |
+
base_export_id="export-1",
|
| 221 |
+
parent_export_id="export-1",
|
| 222 |
+
config_hash="config-1",
|
| 223 |
+
model_id="model-1",
|
| 224 |
+
nodes=[{"id": "skill:new-target", "label": "new-target", "type": "skill", "tags": []}],
|
| 225 |
+
edges=[{"source": "skill:seed", "target": "skill:new-target", "weight": 1.0}],
|
| 226 |
+
tombstones=[],
|
| 227 |
+
)
|
| 228 |
+
second = json.loads(toolbox.dispatch(ToolCall(
|
| 229 |
+
id="c2",
|
| 230 |
+
name="ctx__graph_query",
|
| 231 |
+
arguments={"seeds": ["seed"], "max_hops": 1},
|
| 232 |
+
)))
|
| 233 |
+
|
| 234 |
+
first_names = {item["name"] for item in first["results"]}
|
| 235 |
+
second_names = {item["name"] for item in second["results"]}
|
| 236 |
+
assert "old-target" in first_names
|
| 237 |
+
assert "new-target" not in first_names
|
| 238 |
+
assert "new-target" in second_names
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def test_graph_cache_uses_wiki_packs_when_explicit_graph_path_is_missing(
|
| 242 |
+
tmp_path: Path,
|
| 243 |
+
) -> None:
|
| 244 |
+
wiki = tmp_path / "wiki"
|
| 245 |
+
graph = nx.Graph()
|
| 246 |
+
graph.add_node("skill:seed", label="seed", type="skill", tags=[])
|
| 247 |
+
graph.add_node("skill:pack-target", label="pack-target", type="skill", tags=[])
|
| 248 |
+
graph.add_edge("skill:seed", "skill:pack-target", weight=1.0)
|
| 249 |
+
write_base_pack(
|
| 250 |
+
pack_dir=wiki / "graphify-out" / "packs" / "base-export-1",
|
| 251 |
+
pack_id="base-export-1",
|
| 252 |
+
base_export_id="export-1",
|
| 253 |
+
config_hash="config-1",
|
| 254 |
+
model_id="model-1",
|
| 255 |
+
graph=graph,
|
| 256 |
+
)
|
| 257 |
+
assert not (wiki / "graphify-out" / "graph.json").exists()
|
| 258 |
+
|
| 259 |
+
toolbox = CtxCoreToolbox(wiki_dir=wiki, graph_path=tmp_path / "missing.json")
|
| 260 |
+
result = json.loads(toolbox.dispatch(ToolCall(
|
| 261 |
+
id="c1",
|
| 262 |
+
name="ctx__graph_query",
|
| 263 |
+
arguments={"seeds": ["seed"], "max_hops": 1},
|
| 264 |
+
)))
|
| 265 |
+
|
| 266 |
+
assert [row["name"] for row in result["results"]] == ["pack-target"]
|
| 267 |
+
|
| 268 |
+
|
| 269 |
def test_graph_file_signature_detects_same_size_rewrite(
|
| 270 |
tmp_path: Path,
|
| 271 |
) -> None:
|
|
|
|
| 310 |
assert second["results"][0]["slug"] == "new-skill"
|
| 311 |
|
| 312 |
|
| 313 |
+
def test_wiki_page_cache_reloads_when_wiki_pack_overlay_changes(tmp_path: Path) -> None:
|
| 314 |
+
wiki = tmp_path / "wiki"
|
| 315 |
+
packs_dir = wiki / "wiki-packs"
|
| 316 |
+
write_wiki_base_pack(
|
| 317 |
+
pack_dir=packs_dir / "base-export-1",
|
| 318 |
+
pack_id="base-export-1",
|
| 319 |
+
base_export_id="wiki-export-1",
|
| 320 |
+
pages={"entities/skills/old-skill.md": "# Old\n"},
|
| 321 |
+
)
|
| 322 |
+
toolbox = CtxCoreToolbox(wiki_dir=wiki, graph_path=tmp_path / "missing.json")
|
| 323 |
+
first = json.loads(toolbox.dispatch(ToolCall(
|
| 324 |
+
id="c1",
|
| 325 |
+
name="ctx__wiki_search",
|
| 326 |
+
arguments={"query": "packunique"},
|
| 327 |
+
)))
|
| 328 |
+
|
| 329 |
+
write_wiki_overlay_pack(
|
| 330 |
+
pack_dir=packs_dir / "overlay-packunique",
|
| 331 |
+
pack_id="overlay-packunique",
|
| 332 |
+
base_export_id="wiki-export-1",
|
| 333 |
+
parent_export_id="wiki-export-1",
|
| 334 |
+
pages={
|
| 335 |
+
"entities/skills/pack-skill.md": (
|
| 336 |
+
"---\n"
|
| 337 |
+
"name: pack-skill\n"
|
| 338 |
+
"tags: [packunique]\n"
|
| 339 |
+
"---\n"
|
| 340 |
+
"# Pack Skill\n"
|
| 341 |
+
),
|
| 342 |
+
},
|
| 343 |
+
tombstones=[],
|
| 344 |
+
)
|
| 345 |
+
second = json.loads(toolbox.dispatch(ToolCall(
|
| 346 |
+
id="c2",
|
| 347 |
+
name="ctx__wiki_search",
|
| 348 |
+
arguments={"query": "packunique"},
|
| 349 |
+
)))
|
| 350 |
+
|
| 351 |
+
assert first["results"] == []
|
| 352 |
+
assert second["results"][0]["slug"] == "pack-skill"
|
| 353 |
+
|
| 354 |
+
|
| 355 |
def test_semantic_miss_cache_clears_when_embedding_artifacts_change(
|
| 356 |
tmp_path: Path,
|
| 357 |
monkeypatch: pytest.MonkeyPatch,
|
|
|
|
| 417 |
)
|
| 418 |
assert td.parameters["required"] == ["seeds"]
|
| 419 |
|
| 420 |
+
def test_read_tools_expose_optional_response_format(
|
| 421 |
+
self,
|
| 422 |
+
toolbox: CtxCoreToolbox,
|
| 423 |
+
) -> None:
|
| 424 |
+
read_tools = {
|
| 425 |
+
"ctx__recommend_bundle",
|
| 426 |
+
"ctx__graph_query",
|
| 427 |
+
"ctx__wiki_search",
|
| 428 |
+
"ctx__wiki_get",
|
| 429 |
+
}
|
| 430 |
+
by_name = {definition.name: definition for definition in toolbox.tool_definitions()}
|
| 431 |
+
|
| 432 |
+
for tool_name in read_tools:
|
| 433 |
+
schema = by_name[tool_name].parameters
|
| 434 |
+
output_format = schema["properties"]["output_format"]
|
| 435 |
+
assert output_format["enum"] == ["json", "gcf"]
|
| 436 |
+
assert "output_format" not in schema.get("required", [])
|
| 437 |
+
response_format = schema["properties"]["_response_format"]
|
| 438 |
+
assert response_format["enum"] == ["json", "gcf"]
|
| 439 |
+
assert "_response_format" not in schema.get("required", [])
|
| 440 |
+
|
| 441 |
|
| 442 |
# ── Namespace + dispatch ───────────────────────────────────────────────────
|
| 443 |
|
|
|
|
| 457 |
with pytest.raises(ValueError, match="unknown ctx-core tool"):
|
| 458 |
toolbox.dispatch(ToolCall(id="c1", name="ctx__bogus", arguments={}))
|
| 459 |
|
| 460 |
+
def test_read_tools_default_to_json(self, toolbox: CtxCoreToolbox) -> None:
|
| 461 |
+
raw = toolbox.dispatch(ToolCall(
|
| 462 |
+
id="c1",
|
| 463 |
+
name="ctx__wiki_search",
|
| 464 |
+
arguments={"query": "python", "top_n": 1},
|
| 465 |
+
))
|
| 466 |
+
|
| 467 |
+
payload = json.loads(raw)
|
| 468 |
+
assert payload["query"] == "python"
|
| 469 |
+
assert payload["results"]
|
| 470 |
+
|
| 471 |
+
def test_read_tools_can_opt_into_gcf(
|
| 472 |
+
self,
|
| 473 |
+
toolbox: CtxCoreToolbox,
|
| 474 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 475 |
+
) -> None:
|
| 476 |
+
monkeypatch.setitem(
|
| 477 |
+
sys.modules,
|
| 478 |
+
"gcf",
|
| 479 |
+
SimpleNamespace(
|
| 480 |
+
encode_generic=lambda data: (
|
| 481 |
+
f"GCF profile=generic\nquery={data['query']}"
|
| 482 |
+
)
|
| 483 |
+
),
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
raw = toolbox.dispatch(ToolCall(
|
| 487 |
+
id="c1",
|
| 488 |
+
name="ctx__wiki_search",
|
| 489 |
+
arguments={
|
| 490 |
+
"query": "python",
|
| 491 |
+
"top_n": 1,
|
| 492 |
+
"_response_format": "gcf",
|
| 493 |
+
},
|
| 494 |
+
))
|
| 495 |
+
|
| 496 |
+
assert raw.startswith("GCF profile=generic\n")
|
| 497 |
+
assert "query=python" in raw
|
| 498 |
+
|
| 499 |
+
def test_read_tools_accept_public_output_format_alias(
|
| 500 |
+
self,
|
| 501 |
+
toolbox: CtxCoreToolbox,
|
| 502 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 503 |
+
) -> None:
|
| 504 |
+
monkeypatch.setitem(
|
| 505 |
+
sys.modules,
|
| 506 |
+
"gcf",
|
| 507 |
+
SimpleNamespace(
|
| 508 |
+
encode_generic=lambda data: (
|
| 509 |
+
f"GCF profile=generic\nquery={data['query']}"
|
| 510 |
+
)
|
| 511 |
+
),
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
raw = toolbox.dispatch(ToolCall(
|
| 515 |
+
id="c1",
|
| 516 |
+
name="ctx__wiki_search",
|
| 517 |
+
arguments={
|
| 518 |
+
"query": "python",
|
| 519 |
+
"top_n": 1,
|
| 520 |
+
"output_format": "gcf",
|
| 521 |
+
},
|
| 522 |
+
))
|
| 523 |
+
|
| 524 |
+
assert raw.startswith("GCF profile=generic\n")
|
| 525 |
+
assert "query=python" in raw
|
| 526 |
+
|
| 527 |
+
def test_gcf_opt_in_without_codec_returns_json_error(
|
| 528 |
+
self,
|
| 529 |
+
toolbox: CtxCoreToolbox,
|
| 530 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 531 |
+
) -> None:
|
| 532 |
+
monkeypatch.setitem(sys.modules, "gcf", None)
|
| 533 |
+
|
| 534 |
+
raw = toolbox.dispatch(ToolCall(
|
| 535 |
+
id="c1",
|
| 536 |
+
name="ctx__wiki_search",
|
| 537 |
+
arguments={
|
| 538 |
+
"query": "python",
|
| 539 |
+
"top_n": 1,
|
| 540 |
+
"_response_format": "gcf",
|
| 541 |
+
},
|
| 542 |
+
))
|
| 543 |
+
|
| 544 |
+
payload = json.loads(raw)
|
| 545 |
+
assert "gcf-python" in payload["error"]
|
| 546 |
+
assert payload["response_format"] == "json"
|
| 547 |
+
|
| 548 |
|
| 549 |
class TestRuntimeLifecycle:
|
| 550 |
+
def test_lifecycle_tool_emits_core_and_store_telemetry(
|
| 551 |
+
self,
|
| 552 |
+
toolbox: CtxCoreToolbox,
|
| 553 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 554 |
+
) -> None:
|
| 555 |
+
import ctx.adapters.generic.ctx_core_tools as core_tools
|
| 556 |
+
import ctx.adapters.generic.runtime_lifecycle as runtime_lifecycle
|
| 557 |
+
|
| 558 |
+
events: list[dict[str, Any]] = []
|
| 559 |
+
|
| 560 |
+
def capture_record_event(event_name: str, **kwargs: Any) -> None:
|
| 561 |
+
events.append({"event_name": event_name, **kwargs})
|
| 562 |
+
|
| 563 |
+
monkeypatch.setattr(core_tools, "record_event", capture_record_event)
|
| 564 |
+
monkeypatch.setattr(runtime_lifecycle, "record_event", capture_record_event)
|
| 565 |
+
|
| 566 |
+
result = json.loads(
|
| 567 |
+
toolbox.dispatch(ToolCall(
|
| 568 |
+
id="c1",
|
| 569 |
+
name="ctx__load_entity",
|
| 570 |
+
arguments={
|
| 571 |
+
"session_id": "s-1",
|
| 572 |
+
"entity_type": "skill",
|
| 573 |
+
"slug": "fastapi-pro",
|
| 574 |
+
},
|
| 575 |
+
))
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
assert result["ok"] is True
|
| 579 |
+
event_names = [event["event_name"] for event in events]
|
| 580 |
+
assert "ctx.runtime_lifecycle.record" in event_names
|
| 581 |
+
assert "ctx.core.lifecycle" in event_names
|
| 582 |
+
for event in events:
|
| 583 |
+
payload = event["payload"]
|
| 584 |
+
assert payload["otel.status_code"] == "OK"
|
| 585 |
+
assert payload["ctx.entity.type"] == "skill"
|
| 586 |
+
assert payload["ctx.slug.hash"].startswith("sha256:")
|
| 587 |
+
assert "fastapi-pro" not in json.dumps(payload)
|
| 588 |
+
|
| 589 |
def test_lifecycle_tools_append_events(
|
| 590 |
self,
|
| 591 |
toolbox: CtxCoreToolbox,
|
|
|
|
| 993 |
|
| 994 |
|
| 995 |
class TestRecommendBundle:
|
| 996 |
+
def test_recommend_bundle_emits_core_telemetry_without_raw_query(
|
| 997 |
+
self,
|
| 998 |
+
toolbox: CtxCoreToolbox,
|
| 999 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 1000 |
+
) -> None:
|
| 1001 |
+
import ctx.adapters.generic.ctx_core_tools as core_tools
|
| 1002 |
+
|
| 1003 |
+
events: list[dict[str, Any]] = []
|
| 1004 |
+
|
| 1005 |
+
def capture_record_event(event_name: str, **kwargs: Any) -> None:
|
| 1006 |
+
events.append({"event_name": event_name, **kwargs})
|
| 1007 |
+
|
| 1008 |
+
monkeypatch.setattr(core_tools, "record_event", capture_record_event)
|
| 1009 |
+
raw_query = "private acme python web api"
|
| 1010 |
+
|
| 1011 |
+
result = json.loads(
|
| 1012 |
+
toolbox.dispatch(
|
| 1013 |
+
ToolCall(
|
| 1014 |
+
id="c1",
|
| 1015 |
+
name="ctx__recommend_bundle",
|
| 1016 |
+
arguments={"query": raw_query, "top_k": 5},
|
| 1017 |
+
)
|
| 1018 |
+
)
|
| 1019 |
+
)
|
| 1020 |
+
|
| 1021 |
+
event = events[-1]
|
| 1022 |
+
payload = event["payload"]
|
| 1023 |
+
assert event["event_name"] == "ctx.core.recommend_bundle"
|
| 1024 |
+
assert event["source"] == "ctx-core"
|
| 1025 |
+
assert event["outcome"] == "ok"
|
| 1026 |
+
assert payload["ctx.operation"] == "recommend_bundle"
|
| 1027 |
+
assert payload["ctx.query.length"] == len(raw_query)
|
| 1028 |
+
assert payload["ctx.query.hash"].startswith("sha256:")
|
| 1029 |
+
assert payload["ctx.result.count"] == len(result["results"])
|
| 1030 |
+
assert raw_query not in json.dumps(payload)
|
| 1031 |
+
|
| 1032 |
def test_happy_path_ranks_by_tag_overlap(
|
| 1033 |
self, toolbox: CtxCoreToolbox
|
| 1034 |
) -> None:
|
|
|
|
| 1411 |
assert result["wikilink"] == "[[entities/mcp-servers/f/filesystem]]"
|
| 1412 |
assert "Filesystem MCP" in result["body"]
|
| 1413 |
|
| 1414 |
+
def test_reads_entity_page_from_wiki_pack_before_stale_file(
|
| 1415 |
+
self, tmp_path: Path
|
| 1416 |
+
) -> None:
|
| 1417 |
+
wiki = _build_synthetic_wiki(tmp_path)
|
| 1418 |
+
(wiki / "entities" / "skills" / "python-patterns.md").write_text(
|
| 1419 |
+
"---\n"
|
| 1420 |
+
"name: python-patterns\n"
|
| 1421 |
+
"title: Stale Physical Page\n"
|
| 1422 |
+
"tags: [stale]\n"
|
| 1423 |
+
"---\n"
|
| 1424 |
+
"# Stale Physical Page\n",
|
| 1425 |
+
encoding="utf-8",
|
| 1426 |
+
)
|
| 1427 |
+
write_wiki_base_pack(
|
| 1428 |
+
pack_dir=wiki / "wiki-packs" / "base-export-1",
|
| 1429 |
+
pack_id="base-export-1",
|
| 1430 |
+
base_export_id="export-1",
|
| 1431 |
+
pages={
|
| 1432 |
+
"entities/skills/python-patterns.md": (
|
| 1433 |
+
"---\n"
|
| 1434 |
+
"name: python-patterns\n"
|
| 1435 |
+
"title: Fresh Pack Page\n"
|
| 1436 |
+
"tags: [pack]\n"
|
| 1437 |
+
"---\n"
|
| 1438 |
+
"# Fresh Pack Page\n\n"
|
| 1439 |
+
"This content came from the merged wiki pack.\n"
|
| 1440 |
+
)
|
| 1441 |
+
},
|
| 1442 |
+
)
|
| 1443 |
+
toolbox = CtxCoreToolbox(wiki_dir=wiki, graph_path=tmp_path / "missing.json")
|
| 1444 |
+
|
| 1445 |
+
result = json.loads(
|
| 1446 |
+
toolbox.dispatch(
|
| 1447 |
+
ToolCall(
|
| 1448 |
+
id="c1",
|
| 1449 |
+
name="ctx__wiki_get",
|
| 1450 |
+
arguments={"slug": "python-patterns", "entity_type": "skill"},
|
| 1451 |
+
)
|
| 1452 |
+
)
|
| 1453 |
+
)
|
| 1454 |
+
|
| 1455 |
+
assert "error" not in result
|
| 1456 |
+
assert result["frontmatter"]["title"] == "Fresh Pack Page"
|
| 1457 |
+
assert "merged wiki pack" in result["body"]
|
| 1458 |
+
|
| 1459 |
|
| 1460 |
# ── _query_to_tags ────────────────────────────────────────────────────────
|
| 1461 |
|
src/tests/test_harness_install.py
CHANGED
|
@@ -991,6 +991,8 @@ def test_recommend_mode_passes_structured_harness_requirements(
|
|
| 991 |
"build a code agent",
|
| 992 |
"--model",
|
| 993 |
"openai/gpt-5.5",
|
|
|
|
|
|
|
| 994 |
"--harness-runtime",
|
| 995 |
"windows python",
|
| 996 |
"--harness-autonomy",
|
|
@@ -1013,6 +1015,7 @@ def test_recommend_mode_passes_structured_harness_requirements(
|
|
| 1013 |
"verification": "pytest ruff",
|
| 1014 |
"privacy": "private repo no secrets",
|
| 1015 |
"attach_mode": "mcp",
|
|
|
|
| 1016 |
}
|
| 1017 |
|
| 1018 |
|
|
@@ -1099,6 +1102,32 @@ def test_recommend_no_fit_prints_custom_harness_plan(
|
|
| 1099 |
assert "Privacy/network: offline source code" in output
|
| 1100 |
|
| 1101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1102 |
def test_recommend_no_fit_writes_custom_harness_plan(
|
| 1103 |
tmp_path: Path,
|
| 1104 |
monkeypatch: Any,
|
|
|
|
| 991 |
"build a code agent",
|
| 992 |
"--model",
|
| 993 |
"openai/gpt-5.5",
|
| 994 |
+
"--api-key-env",
|
| 995 |
+
"OPENAI_API_KEY",
|
| 996 |
"--harness-runtime",
|
| 997 |
"windows python",
|
| 998 |
"--harness-autonomy",
|
|
|
|
| 1015 |
"verification": "pytest ruff",
|
| 1016 |
"privacy": "private repo no secrets",
|
| 1017 |
"attach_mode": "mcp",
|
| 1018 |
+
"api_key_env": "OPENAI_API_KEY",
|
| 1019 |
}
|
| 1020 |
|
| 1021 |
|
|
|
|
| 1102 |
assert "Privacy/network: offline source code" in output
|
| 1103 |
|
| 1104 |
|
| 1105 |
+
def test_recommend_mode_accepts_huggingface_api_key_env(
|
| 1106 |
+
monkeypatch: Any,
|
| 1107 |
+
capsys: Any,
|
| 1108 |
+
) -> None:
|
| 1109 |
+
monkeypatch.setattr(harness_install, "recommend_harnesses_for_cli", lambda **_: [])
|
| 1110 |
+
|
| 1111 |
+
rc = harness_install.main([
|
| 1112 |
+
"--recommend",
|
| 1113 |
+
"--goal",
|
| 1114 |
+
"build a code review harness for a small hosted model",
|
| 1115 |
+
"--model-provider",
|
| 1116 |
+
"huggingface",
|
| 1117 |
+
"--model",
|
| 1118 |
+
"HuggingFaceTB/SmolLM2-135M-Instruct",
|
| 1119 |
+
"--api-key-env",
|
| 1120 |
+
"HF_TOKEN",
|
| 1121 |
+
"--plan-on-no-fit",
|
| 1122 |
+
])
|
| 1123 |
+
|
| 1124 |
+
assert rc == 0
|
| 1125 |
+
output = capsys.readouterr().out
|
| 1126 |
+
assert "Model provider: huggingface" in output
|
| 1127 |
+
assert "API key env var: HF_TOKEN" in output
|
| 1128 |
+
assert "hf_" not in output
|
| 1129 |
+
|
| 1130 |
+
|
| 1131 |
def test_recommend_no_fit_writes_custom_harness_plan(
|
| 1132 |
tmp_path: Path,
|
| 1133 |
monkeypatch: Any,
|
src/tests/test_harness_recommendations.py
CHANGED
|
@@ -13,6 +13,17 @@ import ctx_init
|
|
| 13 |
import scan_repo
|
| 14 |
from ctx.core.resolve import resolve_skills
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
def _minimal_profile() -> dict[str, Any]:
|
| 18 |
return {
|
|
@@ -262,6 +273,21 @@ def test_ctx_init_keeps_domain_goal_strong_with_install_requirements(
|
|
| 262 |
assert "gpt-5" not in results[0]["fit_signals"]
|
| 263 |
|
| 264 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
def test_ctx_init_recommends_harness_from_wiki_frontmatter_only(
|
| 266 |
monkeypatch: pytest.MonkeyPatch,
|
| 267 |
) -> None:
|
|
@@ -295,6 +321,126 @@ def test_ctx_init_recommends_harness_from_wiki_frontmatter_only(
|
|
| 295 |
assert set(results[0]["fit_signals"]) >= {"agent", "automation", "browser", "openai"}
|
| 296 |
|
| 297 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
def test_ctx_init_rejects_weak_single_signal_harness_match(
|
| 299 |
monkeypatch: pytest.MonkeyPatch,
|
| 300 |
) -> None:
|
|
|
|
| 13 |
import scan_repo
|
| 14 |
from ctx.core.resolve import resolve_skills
|
| 15 |
|
| 16 |
+
_REAL_LOAD_HARNESS_CATALOG_GRAPH = ctx_init._load_harness_catalog_graph
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@pytest.fixture(autouse=True)
|
| 20 |
+
def _isolate_harness_catalog_fast_path(monkeypatch: pytest.MonkeyPatch) -> None:
|
| 21 |
+
monkeypatch.setattr(
|
| 22 |
+
ctx_init,
|
| 23 |
+
"_load_harness_catalog_graph",
|
| 24 |
+
ctx_init._empty_harness_graph,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
|
| 28 |
def _minimal_profile() -> dict[str, Any]:
|
| 29 |
return {
|
|
|
|
| 273 |
assert "gpt-5" not in results[0]["fit_signals"]
|
| 274 |
|
| 275 |
|
| 276 |
+
def test_ctx_init_rejects_narrow_domain_harness_for_generic_coding_agent(
|
| 277 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 278 |
+
) -> None:
|
| 279 |
+
monkeypatch.setattr(ctx_init, "_load_recommendation_graph", _harness_graph)
|
| 280 |
+
|
| 281 |
+
results = ctx_init.recommend_harnesses(
|
| 282 |
+
"build an openai python coding agent with filesystem and test verification",
|
| 283 |
+
top_k=5,
|
| 284 |
+
model_provider="openai",
|
| 285 |
+
model="openai/gpt-4.1",
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
assert "text-to-cad" not in [row["name"] for row in results]
|
| 289 |
+
|
| 290 |
+
|
| 291 |
def test_ctx_init_recommends_harness_from_wiki_frontmatter_only(
|
| 292 |
monkeypatch: pytest.MonkeyPatch,
|
| 293 |
) -> None:
|
|
|
|
| 321 |
assert set(results[0]["fit_signals"]) >= {"agent", "automation", "browser", "openai"}
|
| 322 |
|
| 323 |
|
| 324 |
+
def test_ctx_init_uses_harness_catalog_without_loading_full_graph(
|
| 325 |
+
tmp_path: Path,
|
| 326 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 327 |
+
) -> None:
|
| 328 |
+
harnesses = tmp_path / "entities" / "harnesses"
|
| 329 |
+
harnesses.mkdir(parents=True)
|
| 330 |
+
(harnesses / "hf-code-review.md").write_text(
|
| 331 |
+
"---\n"
|
| 332 |
+
"name: hf-code-review\n"
|
| 333 |
+
"type: harness\n"
|
| 334 |
+
"tags: [harness, huggingface, python, code, review, pytest, filesystem]\n"
|
| 335 |
+
"model_providers: [huggingface]\n"
|
| 336 |
+
"capabilities: [code review, pytest verification, filesystem tools]\n"
|
| 337 |
+
"runtimes: [python, windows, macos, linux]\n"
|
| 338 |
+
"attach_modes: [mcp]\n"
|
| 339 |
+
"---\n\n# HF Code Review\n",
|
| 340 |
+
encoding="utf-8",
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
import ctx_config
|
| 344 |
+
|
| 345 |
+
monkeypatch.setattr(
|
| 346 |
+
ctx_config,
|
| 347 |
+
"cfg",
|
| 348 |
+
type("Cfg", (), {
|
| 349 |
+
"wiki_dir": tmp_path,
|
| 350 |
+
"claude_dir": tmp_path / ".claude",
|
| 351 |
+
"recommendation_top_k": 5,
|
| 352 |
+
"harness_recommendation_min_fit_score": 0.85,
|
| 353 |
+
})(),
|
| 354 |
+
)
|
| 355 |
+
monkeypatch.setattr(
|
| 356 |
+
ctx_init,
|
| 357 |
+
"_load_recommendation_graph",
|
| 358 |
+
lambda: pytest.fail("interactive harness recommendation loaded full graph"),
|
| 359 |
+
)
|
| 360 |
+
monkeypatch.setattr(
|
| 361 |
+
ctx_init,
|
| 362 |
+
"_load_harness_catalog_graph",
|
| 363 |
+
_REAL_LOAD_HARNESS_CATALOG_GRAPH,
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
results = ctx_init.recommend_harnesses(
|
| 367 |
+
"build a huggingface python code review harness with pytest and filesystem tools",
|
| 368 |
+
model_provider="huggingface",
|
| 369 |
+
model="HuggingFaceTB/SmolLM2-135M-Instruct",
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
assert [row["name"] for row in results] == ["hf-code-review"]
|
| 373 |
+
assert results[0]["fit_score"] >= 0.85
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def test_ctx_init_uses_runtime_harness_body_for_cloud_tool_fit(
|
| 377 |
+
tmp_path: Path,
|
| 378 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 379 |
+
) -> None:
|
| 380 |
+
harnesses = tmp_path / "entities" / "harnesses"
|
| 381 |
+
harnesses.mkdir(parents=True)
|
| 382 |
+
(harnesses / "mirage.md").write_text(
|
| 383 |
+
"---\n"
|
| 384 |
+
"title: Mirage\n"
|
| 385 |
+
"type: harness\n"
|
| 386 |
+
"tags: [harness, virtual-filesystem, sandbox, agent-tools]\n"
|
| 387 |
+
"model_providers: [openai, local, model-agnostic]\n"
|
| 388 |
+
"capabilities:\n"
|
| 389 |
+
" - filesystem-like access to cloud services and remote resources\n"
|
| 390 |
+
"runtimes: [python, node, linux, macos]\n"
|
| 391 |
+
"---\n\n"
|
| 392 |
+
"# Mirage\n\n"
|
| 393 |
+
"Use when the user wants their own model with sandboxed filesystem-like "
|
| 394 |
+
"tool access across GitHub, Slack, S3, Google Drive, Linear, and Notion.\n",
|
| 395 |
+
encoding="utf-8",
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
import ctx_config
|
| 399 |
+
|
| 400 |
+
monkeypatch.setattr(
|
| 401 |
+
ctx_config,
|
| 402 |
+
"cfg",
|
| 403 |
+
type("Cfg", (), {
|
| 404 |
+
"wiki_dir": tmp_path,
|
| 405 |
+
"claude_dir": tmp_path / ".claude",
|
| 406 |
+
"recommendation_top_k": 5,
|
| 407 |
+
"harness_recommendation_min_fit_score": 0.85,
|
| 408 |
+
})(),
|
| 409 |
+
)
|
| 410 |
+
monkeypatch.setattr(
|
| 411 |
+
ctx_init,
|
| 412 |
+
"_load_recommendation_graph",
|
| 413 |
+
lambda: pytest.fail("runtime harness recommendation loaded full graph"),
|
| 414 |
+
)
|
| 415 |
+
monkeypatch.setattr(
|
| 416 |
+
ctx_init,
|
| 417 |
+
"_load_harness_catalog_graph",
|
| 418 |
+
_REAL_LOAD_HARNESS_CATALOG_GRAPH,
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
results = ctx_init.recommend_harnesses(
|
| 422 |
+
"I use my own OpenAI-compatible local model and need sandboxed "
|
| 423 |
+
"filesystem-like tool access across GitHub Slack S3 Google Drive "
|
| 424 |
+
"Linear and Notion for coding agents",
|
| 425 |
+
model_provider="openai",
|
| 426 |
+
model="gpt-4.1",
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
assert [row["name"] for row in results] == ["mirage"]
|
| 430 |
+
assert results[0]["fit_score"] >= 0.85
|
| 431 |
+
assert set(results[0]["fit_signals"]) >= {
|
| 432 |
+
"agents",
|
| 433 |
+
"filesystem",
|
| 434 |
+
"github",
|
| 435 |
+
"linear",
|
| 436 |
+
"notion",
|
| 437 |
+
"openai",
|
| 438 |
+
"sandboxed",
|
| 439 |
+
"slack",
|
| 440 |
+
"tool",
|
| 441 |
+
}
|
| 442 |
+
|
| 443 |
+
|
| 444 |
def test_ctx_init_rejects_weak_single_signal_harness_match(
|
| 445 |
monkeypatch: pytest.MonkeyPatch,
|
| 446 |
) -> None:
|
src/tests/test_huggingface_sync.py
CHANGED
|
@@ -56,6 +56,11 @@ def test_hf_hydrated_artifact_min_size_contract() -> None:
|
|
| 56 |
}
|
| 57 |
|
| 58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
class _FakeRepoInfo:
|
| 60 |
sha = "abc1234"
|
| 61 |
|
|
@@ -73,13 +78,17 @@ class _FakeHfApi:
|
|
| 73 |
self.calls.append(("list_repo_files", kwargs))
|
| 74 |
return self.remote_files
|
| 75 |
|
| 76 |
-
def upload_large_folder(self, **kwargs: object) -> None:
|
| 77 |
-
self.calls.append(("upload_large_folder", kwargs))
|
| 78 |
-
|
| 79 |
def upload_folder(self, **kwargs: object) -> _FakeCommitInfo:
|
| 80 |
self.calls.append(("upload_folder", kwargs))
|
| 81 |
return _FakeCommitInfo()
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
def repo_info(self, **kwargs: object) -> _FakeRepoInfo:
|
| 84 |
self.calls.append(("repo_info", kwargs))
|
| 85 |
return _FakeRepoInfo()
|
|
@@ -156,11 +165,20 @@ def test_hf_sync_workflow_uses_secret_and_hardened_script() -> None:
|
|
| 156 |
assert "HF_TOKEN: ${{ secrets.HF_TOKEN }}" in text
|
| 157 |
assert "lfs: false" in text
|
| 158 |
assert "git lfs pull" not in text
|
| 159 |
-
assert "
|
|
|
|
|
|
|
| 160 |
for artifact in _required_hydrated_artifacts():
|
| 161 |
assert artifact.as_posix() in text
|
| 162 |
-
assert f"
|
| 163 |
assert "scripts/sync_huggingface.py" in text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
assert "Set the HF_TOKEN repository secret" in text
|
| 165 |
assert "hf_" not in text
|
| 166 |
|
|
@@ -193,7 +211,7 @@ def test_hf_sync_tolerates_create_rate_limit_when_repo_exists_after_retry() -> N
|
|
| 193 |
]
|
| 194 |
|
| 195 |
|
| 196 |
-
def
|
| 197 |
tmp_path: Path,
|
| 198 |
) -> None:
|
| 199 |
export_dir = tmp_path / "export"
|
|
@@ -209,20 +227,16 @@ def test_hf_upload_prefers_large_folder_when_remote_has_no_stale_paths(
|
|
| 209 |
repo_id="Stevesolun/ctx",
|
| 210 |
repo_type="dataset",
|
| 211 |
head="abcdef1234567890",
|
| 212 |
-
prefer_large_upload=True,
|
| 213 |
)
|
| 214 |
|
| 215 |
-
assert url == "https://huggingface.co/datasets/Stevesolun/ctx/commit/
|
| 216 |
-
assert [call[0] for call in api.calls] == [
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
]
|
| 221 |
-
|
| 222 |
-
assert
|
| 223 |
-
assert large_upload["repo_type"] == "dataset"
|
| 224 |
-
assert large_upload["folder_path"] == str(export_dir)
|
| 225 |
-
assert large_upload["print_report"] is True
|
| 226 |
|
| 227 |
|
| 228 |
def test_hf_upload_falls_back_to_clean_upload_when_remote_has_stale_paths(
|
|
@@ -239,16 +253,41 @@ def test_hf_upload_falls_back_to_clean_upload_when_remote_has_stale_paths(
|
|
| 239 |
repo_id="Stevesolun/ctx",
|
| 240 |
repo_type="dataset",
|
| 241 |
head="abcdef1234567890",
|
| 242 |
-
prefer_large_upload=True,
|
| 243 |
)
|
| 244 |
|
| 245 |
assert url == "https://huggingface.co/datasets/Stevesolun/ctx/commit/fallback"
|
| 246 |
-
assert [call[0] for call in api.calls] == ["
|
| 247 |
-
clean_upload = api.calls[
|
| 248 |
assert clean_upload["delete_patterns"] == "*"
|
| 249 |
assert clean_upload["commit_message"] == "Sync ctx abcdef1"
|
| 250 |
|
| 251 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
def test_hf_export_copies_hydrated_artifacts_even_when_untracked(
|
| 253 |
tmp_path: Path, monkeypatch
|
| 254 |
) -> None:
|
|
|
|
| 56 |
}
|
| 57 |
|
| 58 |
|
| 59 |
+
def test_hf_sync_defaults_to_dataset_repo_type() -> None:
|
| 60 |
+
assert sync_huggingface.DEFAULT_REPO_ID == "Stevesolun/ctx"
|
| 61 |
+
assert sync_huggingface.DEFAULT_REPO_TYPE == "dataset"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
class _FakeRepoInfo:
|
| 65 |
sha = "abc1234"
|
| 66 |
|
|
|
|
| 78 |
self.calls.append(("list_repo_files", kwargs))
|
| 79 |
return self.remote_files
|
| 80 |
|
|
|
|
|
|
|
|
|
|
| 81 |
def upload_folder(self, **kwargs: object) -> _FakeCommitInfo:
|
| 82 |
self.calls.append(("upload_folder", kwargs))
|
| 83 |
return _FakeCommitInfo()
|
| 84 |
|
| 85 |
+
def upload_file(self, **kwargs: object) -> _FakeCommitInfo:
|
| 86 |
+
path = kwargs.get("path_or_fileobj")
|
| 87 |
+
if isinstance(path, str):
|
| 88 |
+
kwargs = {**kwargs, "content": Path(path).read_text(encoding="utf-8")}
|
| 89 |
+
self.calls.append(("upload_file", kwargs))
|
| 90 |
+
return _FakeCommitInfo()
|
| 91 |
+
|
| 92 |
def repo_info(self, **kwargs: object) -> _FakeRepoInfo:
|
| 93 |
self.calls.append(("repo_info", kwargs))
|
| 94 |
return _FakeRepoInfo()
|
|
|
|
| 165 |
assert "HF_TOKEN: ${{ secrets.HF_TOKEN }}" in text
|
| 166 |
assert "lfs: false" in text
|
| 167 |
assert "git lfs pull" not in text
|
| 168 |
+
assert "Resolving graph artifacts from matching release assets" in text
|
| 169 |
+
assert 'tag_name.startswith("graph-artifacts-")' in text
|
| 170 |
+
assert "latest_tag" not in text
|
| 171 |
for artifact in _required_hydrated_artifacts():
|
| 172 |
assert artifact.as_posix() in text
|
| 173 |
+
assert f'hydrate_from_release("{artifact.as_posix()}"' in text
|
| 174 |
assert "scripts/sync_huggingface.py" in text
|
| 175 |
+
assert "--repo-type dataset" in text
|
| 176 |
+
assert "--repo-type model" not in text
|
| 177 |
+
assert "Classify sync scope" in text
|
| 178 |
+
assert "card_only_files" in text
|
| 179 |
+
assert 'SYNC_MODE" == "card"' in text
|
| 180 |
+
assert "--card-only" in text
|
| 181 |
+
assert "timeout-minutes: 60" in text
|
| 182 |
assert "Set the HF_TOKEN repository secret" in text
|
| 183 |
assert "hf_" not in text
|
| 184 |
|
|
|
|
| 211 |
]
|
| 212 |
|
| 213 |
|
| 214 |
+
def test_hf_upload_uses_clean_folder_commit(
|
| 215 |
tmp_path: Path,
|
| 216 |
) -> None:
|
| 217 |
export_dir = tmp_path / "export"
|
|
|
|
| 227 |
repo_id="Stevesolun/ctx",
|
| 228 |
repo_type="dataset",
|
| 229 |
head="abcdef1234567890",
|
|
|
|
| 230 |
)
|
| 231 |
|
| 232 |
+
assert url == "https://huggingface.co/datasets/Stevesolun/ctx/commit/fallback"
|
| 233 |
+
assert [call[0] for call in api.calls] == ["upload_folder"]
|
| 234 |
+
upload = api.calls[0][1]
|
| 235 |
+
assert upload["repo_id"] == "Stevesolun/ctx"
|
| 236 |
+
assert upload["repo_type"] == "dataset"
|
| 237 |
+
assert upload["folder_path"] == str(export_dir)
|
| 238 |
+
assert upload["delete_patterns"] == "*"
|
| 239 |
+
assert upload["commit_message"] == "Sync ctx abcdef1"
|
|
|
|
|
|
|
|
|
|
| 240 |
|
| 241 |
|
| 242 |
def test_hf_upload_falls_back_to_clean_upload_when_remote_has_stale_paths(
|
|
|
|
| 253 |
repo_id="Stevesolun/ctx",
|
| 254 |
repo_type="dataset",
|
| 255 |
head="abcdef1234567890",
|
|
|
|
| 256 |
)
|
| 257 |
|
| 258 |
assert url == "https://huggingface.co/datasets/Stevesolun/ctx/commit/fallback"
|
| 259 |
+
assert [call[0] for call in api.calls] == ["upload_folder"]
|
| 260 |
+
clean_upload = api.calls[0][1]
|
| 261 |
assert clean_upload["delete_patterns"] == "*"
|
| 262 |
assert clean_upload["commit_message"] == "Sync ctx abcdef1"
|
| 263 |
|
| 264 |
|
| 265 |
+
def test_hf_card_upload_only_patches_readme(tmp_path: Path) -> None:
|
| 266 |
+
repo = tmp_path / "repo"
|
| 267 |
+
repo.mkdir()
|
| 268 |
+
(repo / "README.md").write_text("# ctx\n\nbody\n", encoding="utf-8")
|
| 269 |
+
api = _FakeHfApi(remote_files=[])
|
| 270 |
+
|
| 271 |
+
url = sync_huggingface._upload_readme_card(
|
| 272 |
+
api=api,
|
| 273 |
+
repo=repo,
|
| 274 |
+
repo_id="Stevesolun/ctx",
|
| 275 |
+
repo_type="dataset",
|
| 276 |
+
head="abcdef1234567890",
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
assert url == "https://huggingface.co/datasets/Stevesolun/ctx/commit/fallback"
|
| 280 |
+
assert [call[0] for call in api.calls] == ["upload_file"]
|
| 281 |
+
upload = api.calls[0][1]
|
| 282 |
+
assert upload["repo_id"] == "Stevesolun/ctx"
|
| 283 |
+
assert upload["repo_type"] == "dataset"
|
| 284 |
+
assert upload["path_in_repo"] == "README.md"
|
| 285 |
+
assert upload["commit_message"] == "Sync ctx card abcdef1"
|
| 286 |
+
rendered = str(upload["content"])
|
| 287 |
+
assert rendered.startswith("---\nlicense: mit\n")
|
| 288 |
+
assert rendered.endswith("# ctx\n\nbody\n")
|
| 289 |
+
|
| 290 |
+
|
| 291 |
def test_hf_export_copies_hydrated_artifacts_even_when_untracked(
|
| 292 |
tmp_path: Path, monkeypatch
|
| 293 |
) -> None:
|
src/tests/test_incremental_attach_az_flow.py
CHANGED
|
@@ -101,7 +101,7 @@ def test_entity_onboarding_incremental_attach_a_to_z(
|
|
| 101 |
skill_add = _fresh_module("skill_add")
|
| 102 |
mcp_add = _fresh_module("mcp_add")
|
| 103 |
harness_add = _fresh_module("harness_add")
|
| 104 |
-
|
| 105 |
mcp_entity = _fresh_module("mcp_entity")
|
| 106 |
|
| 107 |
claude = tmp_path / ".claude"
|
|
@@ -115,8 +115,8 @@ def test_entity_onboarding_incremental_attach_a_to_z(
|
|
| 115 |
monkeypatch.setattr(skill_add, "record_embedding", lambda **_kwargs: None)
|
| 116 |
monkeypatch.setattr(mcp_add, "check_intake", _allow_intake)
|
| 117 |
monkeypatch.setattr(mcp_add, "record_embedding", lambda **_kwargs: None)
|
| 118 |
-
monkeypatch.setattr(
|
| 119 |
-
monkeypatch.setattr(
|
| 120 |
|
| 121 |
source = tmp_path / "SKILL.md"
|
| 122 |
source.write_text(
|
|
@@ -270,17 +270,17 @@ def test_entity_onboarding_incremental_attach_a_to_z(
|
|
| 270 |
assert attached["status"] == "inserted"
|
| 271 |
assert overlay.is_file()
|
| 272 |
|
| 273 |
-
graph_payload =
|
| 274 |
assert graph_payload["center"] == "skill:az-attached"
|
| 275 |
assert {node["data"]["id"] for node in graph_payload["nodes"]} >= {
|
| 276 |
"skill:az-attached",
|
| 277 |
"skill:existing-python-helper",
|
| 278 |
}
|
| 279 |
-
rendered =
|
| 280 |
assert "Knowledge graph" in rendered
|
| 281 |
assert "az-attached" in rendered
|
| 282 |
|
| 283 |
-
ok, message =
|
| 284 |
assert ok is True, message
|
| 285 |
assert not (wiki / "entities" / "skills" / "az-skill.md").exists()
|
| 286 |
jobs = wiki_queue.list_jobs(wiki_queue.queue_db_path(wiki))
|
|
|
|
| 101 |
skill_add = _fresh_module("skill_add")
|
| 102 |
mcp_add = _fresh_module("mcp_add")
|
| 103 |
harness_add = _fresh_module("harness_add")
|
| 104 |
+
mt = _fresh_module("ctx.monitor.testing")
|
| 105 |
mcp_entity = _fresh_module("mcp_entity")
|
| 106 |
|
| 107 |
claude = tmp_path / ".claude"
|
|
|
|
| 115 |
monkeypatch.setattr(skill_add, "record_embedding", lambda **_kwargs: None)
|
| 116 |
monkeypatch.setattr(mcp_add, "check_intake", _allow_intake)
|
| 117 |
monkeypatch.setattr(mcp_add, "record_embedding", lambda **_kwargs: None)
|
| 118 |
+
monkeypatch.setattr(mt, "claude_dir", lambda: claude)
|
| 119 |
+
monkeypatch.setattr(mt, "dashboard_graph_index_archives", lambda: [])
|
| 120 |
|
| 121 |
source = tmp_path / "SKILL.md"
|
| 122 |
source.write_text(
|
|
|
|
| 270 |
assert attached["status"] == "inserted"
|
| 271 |
assert overlay.is_file()
|
| 272 |
|
| 273 |
+
graph_payload = mt.graph_neighborhood("az-attached", entity_type="skill")
|
| 274 |
assert graph_payload["center"] == "skill:az-attached"
|
| 275 |
assert {node["data"]["id"] for node in graph_payload["nodes"]} >= {
|
| 276 |
"skill:az-attached",
|
| 277 |
"skill:existing-python-helper",
|
| 278 |
}
|
| 279 |
+
rendered = mt.render_graph("az-attached", "skill")
|
| 280 |
assert "Knowledge graph" in rendered
|
| 281 |
assert "az-attached" in rendered
|
| 282 |
|
| 283 |
+
ok, message = mt.delete_wiki_entity("az-skill", "skill")
|
| 284 |
assert ok is True, message
|
| 285 |
assert not (wiki / "entities" / "skills" / "az-skill.md").exists()
|
| 286 |
jobs = wiki_queue.list_jobs(wiki_queue.queue_db_path(wiki))
|
src/tests/test_incremental_attach_calibration.py
CHANGED
|
@@ -12,6 +12,12 @@ from ctx.core.graph.incremental_attach import (
|
|
| 12 |
main,
|
| 13 |
render_calibration_markdown,
|
| 14 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
from ctx.core.graph.resolve_graph import load_graph
|
| 16 |
from ctx.core.graph.vector_index import build_vector_index
|
| 17 |
|
|
@@ -102,6 +108,28 @@ def test_main_calibrate_outputs_json(tmp_path, capsys) -> None:
|
|
| 102 |
assert '"recommended_min_semantic_score": 0.8' in output
|
| 103 |
|
| 104 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
def test_main_attach_dry_run_outputs_overlay_without_writing(tmp_path, capsys) -> None:
|
| 106 |
index_dir = tmp_path / "vector-index"
|
| 107 |
build_vector_index(
|
|
@@ -138,6 +166,113 @@ def test_main_attach_dry_run_outputs_overlay_without_writing(tmp_path, capsys) -
|
|
| 138 |
assert '"target": "skill:python-testing"' in output
|
| 139 |
|
| 140 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
def test_main_attach_writes_idempotent_overlay_used_by_resolver(tmp_path) -> None:
|
| 142 |
index_dir = tmp_path / "vector-index"
|
| 143 |
build_vector_index(
|
|
@@ -205,6 +340,123 @@ def test_main_attach_writes_idempotent_overlay_used_by_resolver(tmp_path) -> Non
|
|
| 205 |
assert not loaded_after_change.has_edge("skill:new-python", "skill:python-testing")
|
| 206 |
|
| 207 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
def test_main_attach_default_min_score_matches_build_floor(tmp_path) -> None:
|
| 209 |
index_dir = tmp_path / "vector-index"
|
| 210 |
build_vector_index(
|
|
|
|
| 12 |
main,
|
| 13 |
render_calibration_markdown,
|
| 14 |
)
|
| 15 |
+
from ctx.core.graph.graph_packs import (
|
| 16 |
+
build_pack_manifest,
|
| 17 |
+
load_merged_pack_graph,
|
| 18 |
+
write_base_pack,
|
| 19 |
+
write_pack_manifest,
|
| 20 |
+
)
|
| 21 |
from ctx.core.graph.resolve_graph import load_graph
|
| 22 |
from ctx.core.graph.vector_index import build_vector_index
|
| 23 |
|
|
|
|
| 108 |
assert '"recommended_min_semantic_score": 0.8' in output
|
| 109 |
|
| 110 |
|
| 111 |
+
def test_main_calibrate_accepts_pack_only_graph_dir(tmp_path, capsys) -> None:
|
| 112 |
+
graph_dir = tmp_path / "graphify-out"
|
| 113 |
+
G = nx.Graph()
|
| 114 |
+
G.add_node("skill:a", type="skill")
|
| 115 |
+
G.add_node("skill:b", type="skill")
|
| 116 |
+
G.add_edge("skill:a", "skill:b", semantic_sim=0.8, final_weight=0.4)
|
| 117 |
+
write_base_pack(
|
| 118 |
+
pack_dir=graph_dir / "packs" / "base-export-1",
|
| 119 |
+
pack_id="base-export-1",
|
| 120 |
+
base_export_id="export-1",
|
| 121 |
+
config_hash="config-1",
|
| 122 |
+
model_id="model-1",
|
| 123 |
+
graph=G,
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
assert main(["calibrate", "--graph-dir", str(graph_dir), "--json"]) == 0
|
| 127 |
+
|
| 128 |
+
output = capsys.readouterr().out
|
| 129 |
+
assert '"node_count": 2' in output
|
| 130 |
+
assert '"recommended_min_semantic_score": 0.8' in output
|
| 131 |
+
|
| 132 |
+
|
| 133 |
def test_main_attach_dry_run_outputs_overlay_without_writing(tmp_path, capsys) -> None:
|
| 134 |
index_dir = tmp_path / "vector-index"
|
| 135 |
build_vector_index(
|
|
|
|
| 166 |
assert '"target": "skill:python-testing"' in output
|
| 167 |
|
| 168 |
|
| 169 |
+
def test_main_attach_queries_delta_vector_indexes(tmp_path, capsys) -> None:
|
| 170 |
+
index_dir = tmp_path / "base-vector-index"
|
| 171 |
+
build_vector_index(
|
| 172 |
+
kind="numpy-flat",
|
| 173 |
+
model_id="model-a",
|
| 174 |
+
node_ids=["skill:base-ruby"],
|
| 175 |
+
content_hashes=["hb"],
|
| 176 |
+
vectors=np.asarray([[0.0, 1.0]], dtype="float32"),
|
| 177 |
+
).save(index_dir)
|
| 178 |
+
delta_index_dir = tmp_path / "delta-vector-index"
|
| 179 |
+
build_vector_index(
|
| 180 |
+
kind="numpy-flat",
|
| 181 |
+
model_id="model-a",
|
| 182 |
+
node_ids=["skill:delta-python"],
|
| 183 |
+
content_hashes=["hd"],
|
| 184 |
+
vectors=np.asarray([[1.0, 0.0]], dtype="float32"),
|
| 185 |
+
).save(delta_index_dir)
|
| 186 |
+
overlay = tmp_path / "entity-overlays.jsonl"
|
| 187 |
+
|
| 188 |
+
rc = main([
|
| 189 |
+
"attach",
|
| 190 |
+
"--index-dir", str(index_dir),
|
| 191 |
+
"--delta-index-dir", str(delta_index_dir),
|
| 192 |
+
"--overlay", str(overlay),
|
| 193 |
+
"--node-id", "skill:new-python",
|
| 194 |
+
"--label", "new-python",
|
| 195 |
+
"--type", "skill",
|
| 196 |
+
"--text", "new python testing helper",
|
| 197 |
+
"--model-id", "model-a",
|
| 198 |
+
"--vector-json", "[1.0, 0.0]",
|
| 199 |
+
"--top-k", "1",
|
| 200 |
+
"--min-score", "0.5",
|
| 201 |
+
"--dry-run",
|
| 202 |
+
])
|
| 203 |
+
|
| 204 |
+
assert rc == 0
|
| 205 |
+
assert not overlay.exists()
|
| 206 |
+
output = capsys.readouterr().out
|
| 207 |
+
assert '"target": "skill:delta-python"' in output
|
| 208 |
+
assert '"target": "skill:base-ruby"' not in output
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def test_main_validate_indexes_reports_base_and_delta(tmp_path, capsys) -> None:
|
| 212 |
+
index_dir = tmp_path / "base-vector-index"
|
| 213 |
+
build_vector_index(
|
| 214 |
+
kind="numpy-flat",
|
| 215 |
+
model_id="model-a",
|
| 216 |
+
node_ids=["skill:base-python"],
|
| 217 |
+
content_hashes=["hb"],
|
| 218 |
+
vectors=np.asarray([[1.0, 0.0]], dtype="float32"),
|
| 219 |
+
).save(index_dir)
|
| 220 |
+
delta_index_dir = tmp_path / "delta-vector-index"
|
| 221 |
+
build_vector_index(
|
| 222 |
+
kind="numpy-flat",
|
| 223 |
+
model_id="model-a",
|
| 224 |
+
node_ids=["skill:delta-python"],
|
| 225 |
+
content_hashes=["hd"],
|
| 226 |
+
vectors=np.asarray([[0.9, 0.1]], dtype="float32"),
|
| 227 |
+
).save(delta_index_dir)
|
| 228 |
+
|
| 229 |
+
rc = main([
|
| 230 |
+
"validate-indexes",
|
| 231 |
+
"--index-dir", str(index_dir),
|
| 232 |
+
"--delta-index-dir", str(delta_index_dir),
|
| 233 |
+
"--json",
|
| 234 |
+
])
|
| 235 |
+
|
| 236 |
+
assert rc == 0
|
| 237 |
+
payload = json.loads(capsys.readouterr().out)
|
| 238 |
+
assert payload["ok"] is True
|
| 239 |
+
assert payload["model_id"] == "model-a"
|
| 240 |
+
assert payload["index_count"] == 2
|
| 241 |
+
assert payload["node_count"] == 2
|
| 242 |
+
assert [item["role"] for item in payload["indexes"]] == ["base", "delta"]
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def test_main_validate_indexes_rejects_incompatible_delta(tmp_path, capsys) -> None:
|
| 246 |
+
index_dir = tmp_path / "base-vector-index"
|
| 247 |
+
build_vector_index(
|
| 248 |
+
kind="numpy-flat",
|
| 249 |
+
model_id="model-a",
|
| 250 |
+
node_ids=["skill:base-python"],
|
| 251 |
+
content_hashes=["hb"],
|
| 252 |
+
vectors=np.asarray([[1.0, 0.0]], dtype="float32"),
|
| 253 |
+
).save(index_dir)
|
| 254 |
+
delta_index_dir = tmp_path / "delta-vector-index"
|
| 255 |
+
build_vector_index(
|
| 256 |
+
kind="numpy-flat",
|
| 257 |
+
model_id="model-b",
|
| 258 |
+
node_ids=["skill:delta-python"],
|
| 259 |
+
content_hashes=["hd"],
|
| 260 |
+
vectors=np.asarray([[0.9, 0.1]], dtype="float32"),
|
| 261 |
+
).save(delta_index_dir)
|
| 262 |
+
|
| 263 |
+
rc = main([
|
| 264 |
+
"validate-indexes",
|
| 265 |
+
"--index-dir", str(index_dir),
|
| 266 |
+
"--delta-index-dir", str(delta_index_dir),
|
| 267 |
+
"--json",
|
| 268 |
+
])
|
| 269 |
+
|
| 270 |
+
assert rc == 1
|
| 271 |
+
payload = json.loads(capsys.readouterr().out)
|
| 272 |
+
assert payload["ok"] is False
|
| 273 |
+
assert "delta vector index is unreadable or stale" in payload["error"]
|
| 274 |
+
|
| 275 |
+
|
| 276 |
def test_main_attach_writes_idempotent_overlay_used_by_resolver(tmp_path) -> None:
|
| 277 |
index_dir = tmp_path / "vector-index"
|
| 278 |
build_vector_index(
|
|
|
|
| 340 |
assert not loaded_after_change.has_edge("skill:new-python", "skill:python-testing")
|
| 341 |
|
| 342 |
|
| 343 |
+
def test_main_attach_writes_idempotent_overlay_pack(tmp_path, capsys) -> None:
|
| 344 |
+
index_dir = tmp_path / "vector-index"
|
| 345 |
+
build_vector_index(
|
| 346 |
+
kind="numpy-flat",
|
| 347 |
+
model_id="model-a",
|
| 348 |
+
node_ids=["skill:python-testing"],
|
| 349 |
+
content_hashes=["ha"],
|
| 350 |
+
vectors=np.asarray([[1.0, 0.0]], dtype="float32"),
|
| 351 |
+
).save(index_dir)
|
| 352 |
+
|
| 353 |
+
packs_dir = tmp_path / "packs"
|
| 354 |
+
base_dir = packs_dir / "base-export-1"
|
| 355 |
+
base_dir.mkdir(parents=True)
|
| 356 |
+
graph_json = base_dir / "graph.json"
|
| 357 |
+
graph_json.write_text(
|
| 358 |
+
json.dumps({
|
| 359 |
+
"graph": {"export_id": "export-1"},
|
| 360 |
+
"nodes": [{"id": "skill:python-testing", "type": "skill"}],
|
| 361 |
+
"edges": [],
|
| 362 |
+
}),
|
| 363 |
+
encoding="utf-8",
|
| 364 |
+
)
|
| 365 |
+
write_pack_manifest(
|
| 366 |
+
base_dir / "graph-pack-manifest.json",
|
| 367 |
+
build_pack_manifest(
|
| 368 |
+
pack_dir=base_dir,
|
| 369 |
+
pack_id="base-export-1",
|
| 370 |
+
pack_type="base",
|
| 371 |
+
base_export_id="export-1",
|
| 372 |
+
parent_export_id=None,
|
| 373 |
+
config_hash="config-sha",
|
| 374 |
+
model_id="model-a",
|
| 375 |
+
node_count=1,
|
| 376 |
+
edge_count=0,
|
| 377 |
+
artifact_paths=["graph.json"],
|
| 378 |
+
),
|
| 379 |
+
)
|
| 380 |
+
overlay = tmp_path / "entity-overlays.jsonl"
|
| 381 |
+
args = [
|
| 382 |
+
"attach",
|
| 383 |
+
"--index-dir", str(index_dir),
|
| 384 |
+
"--overlay", str(overlay),
|
| 385 |
+
"--pack-root", str(packs_dir),
|
| 386 |
+
"--base-export-id", "export-1",
|
| 387 |
+
"--config-hash", "config-sha",
|
| 388 |
+
"--node-id", "skill:new-python",
|
| 389 |
+
"--label", "new-python",
|
| 390 |
+
"--type", "skill",
|
| 391 |
+
"--tag", "python",
|
| 392 |
+
"--text", "new python testing helper",
|
| 393 |
+
"--model-id", "model-a",
|
| 394 |
+
"--vector-json", "[1.0, 0.0]",
|
| 395 |
+
"--top-k", "1",
|
| 396 |
+
"--min-score", "0.5",
|
| 397 |
+
"--json",
|
| 398 |
+
]
|
| 399 |
+
|
| 400 |
+
assert main(args) == 0
|
| 401 |
+
first = json.loads(capsys.readouterr().out)
|
| 402 |
+
assert first["overlay_pack"]["status"] == "inserted"
|
| 403 |
+
assert main(args) == 0
|
| 404 |
+
second = json.loads(capsys.readouterr().out)
|
| 405 |
+
|
| 406 |
+
assert second["status"] == "unchanged"
|
| 407 |
+
assert second["overlay_pack"]["status"] == "unchanged"
|
| 408 |
+
assert len([path for path in packs_dir.iterdir() if path.name.startswith("overlay-")]) == 1
|
| 409 |
+
graph = load_merged_pack_graph(packs_dir)
|
| 410 |
+
assert graph.has_edge("skill:new-python", "skill:python-testing")
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def test_main_attach_overlay_pack_replaces_stale_incident_edges(tmp_path, capsys) -> None:
|
| 414 |
+
index_dir = tmp_path / "vector-index"
|
| 415 |
+
build_vector_index(
|
| 416 |
+
kind="numpy-flat",
|
| 417 |
+
model_id="model-a",
|
| 418 |
+
node_ids=["skill:old-target", "skill:new-target"],
|
| 419 |
+
content_hashes=["ha", "hb"],
|
| 420 |
+
vectors=np.asarray([[1.0, 0.0], [0.0, 1.0]], dtype="float32"),
|
| 421 |
+
).save(index_dir)
|
| 422 |
+
packs_dir = tmp_path / "packs"
|
| 423 |
+
base_graph = nx.Graph()
|
| 424 |
+
base_graph.add_node("skill:old-target", type="skill")
|
| 425 |
+
base_graph.add_node("skill:new-target", type="skill")
|
| 426 |
+
write_base_pack(
|
| 427 |
+
pack_dir=packs_dir / "base-export-1",
|
| 428 |
+
pack_id="base-export-1",
|
| 429 |
+
base_export_id="export-1",
|
| 430 |
+
config_hash="config-sha",
|
| 431 |
+
model_id="model-a",
|
| 432 |
+
graph=base_graph,
|
| 433 |
+
)
|
| 434 |
+
overlay = tmp_path / "entity-overlays.jsonl"
|
| 435 |
+
common = [
|
| 436 |
+
"attach",
|
| 437 |
+
"--index-dir", str(index_dir),
|
| 438 |
+
"--overlay", str(overlay),
|
| 439 |
+
"--pack-root", str(packs_dir),
|
| 440 |
+
"--base-export-id", "export-1",
|
| 441 |
+
"--config-hash", "config-sha",
|
| 442 |
+
"--node-id", "skill:changing",
|
| 443 |
+
"--label", "changing",
|
| 444 |
+
"--type", "skill",
|
| 445 |
+
"--model-id", "model-a",
|
| 446 |
+
"--top-k", "1",
|
| 447 |
+
"--min-score", "0.5",
|
| 448 |
+
"--json",
|
| 449 |
+
]
|
| 450 |
+
|
| 451 |
+
assert main([*common, "--text", "old body", "--vector-json", "[1.0, 0.0]"]) == 0
|
| 452 |
+
capsys.readouterr()
|
| 453 |
+
assert main([*common, "--text", "new body", "--vector-json", "[0.0, 1.0]"]) == 0
|
| 454 |
+
|
| 455 |
+
graph = load_merged_pack_graph(packs_dir)
|
| 456 |
+
assert not graph.has_edge("skill:changing", "skill:old-target")
|
| 457 |
+
assert graph.has_edge("skill:changing", "skill:new-target")
|
| 458 |
+
|
| 459 |
+
|
| 460 |
def test_main_attach_default_min_score_matches_build_floor(tmp_path) -> None:
|
| 461 |
index_dir = tmp_path / "vector-index"
|
| 462 |
build_vector_index(
|
src/tests/test_incremental_attach_shadow.py
CHANGED
|
@@ -8,6 +8,7 @@ import networkx as nx
|
|
| 8 |
import numpy as np
|
| 9 |
|
| 10 |
from ctx.core.graph.incremental_shadow import main, run_shadow_validation
|
|
|
|
| 11 |
from ctx.core.graph.semantic_edges import (
|
| 12 |
_l2_normalize,
|
| 13 |
_topk_pairs,
|
|
@@ -141,6 +142,42 @@ def test_shadow_cli_returns_nonzero_when_gate_fails(tmp_path: Path, capsys) -> N
|
|
| 141 |
assert '"gate_passed": false' in capsys.readouterr().out
|
| 142 |
|
| 143 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
def test_shadow_incremental_graph_matches_full_graph(
|
| 145 |
tmp_path: Path,
|
| 146 |
monkeypatch,
|
|
|
|
| 8 |
import numpy as np
|
| 9 |
|
| 10 |
from ctx.core.graph.incremental_shadow import main, run_shadow_validation
|
| 11 |
+
from ctx.core.graph.graph_packs import write_base_pack
|
| 12 |
from ctx.core.graph.semantic_edges import (
|
| 13 |
_l2_normalize,
|
| 14 |
_topk_pairs,
|
|
|
|
| 142 |
assert '"gate_passed": false' in capsys.readouterr().out
|
| 143 |
|
| 144 |
|
| 145 |
+
def test_shadow_cli_accepts_pack_only_graph_dir(tmp_path: Path, capsys) -> None:
|
| 146 |
+
index_dir = tmp_path / "vector-index"
|
| 147 |
+
build_vector_index(
|
| 148 |
+
kind="numpy-flat",
|
| 149 |
+
model_id="model-a",
|
| 150 |
+
node_ids=["skill:alpha", "skill:beta"],
|
| 151 |
+
content_hashes=["ha", "hb"],
|
| 152 |
+
vectors=np.asarray([[1.0, 0.0], [0.95, 0.05]], dtype="float32"),
|
| 153 |
+
).save(index_dir)
|
| 154 |
+
graph_dir = tmp_path / "graphify-out"
|
| 155 |
+
graph = nx.Graph()
|
| 156 |
+
graph.add_edge("skill:alpha", "skill:beta", semantic_sim=0.9)
|
| 157 |
+
write_base_pack(
|
| 158 |
+
pack_dir=graph_dir / "packs" / "base-export-1",
|
| 159 |
+
pack_id="base-export-1",
|
| 160 |
+
base_export_id="export-1",
|
| 161 |
+
config_hash="config-1",
|
| 162 |
+
model_id="model-a",
|
| 163 |
+
graph=graph,
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
rc = main([
|
| 167 |
+
"--index-dir", str(index_dir),
|
| 168 |
+
"--graph-dir", str(graph_dir),
|
| 169 |
+
"--node", "skill:alpha",
|
| 170 |
+
"--top-k", "1",
|
| 171 |
+
"--min-score", "0.5",
|
| 172 |
+
"--json",
|
| 173 |
+
])
|
| 174 |
+
|
| 175 |
+
assert rc == 0
|
| 176 |
+
output = capsys.readouterr().out
|
| 177 |
+
assert '"baseline": "graph-semantic-edges"' in output
|
| 178 |
+
assert '"gate_passed": true' in output
|
| 179 |
+
|
| 180 |
+
|
| 181 |
def test_shadow_incremental_graph_matches_full_graph(
|
| 182 |
tmp_path: Path,
|
| 183 |
monkeypatch,
|
src/tests/test_link_conversions.py
CHANGED
|
@@ -25,6 +25,7 @@ import pytest
|
|
| 25 |
sys.path.insert(0, str(Path(__file__).parents[1]))
|
| 26 |
|
| 27 |
import link_conversions as _lc
|
|
|
|
| 28 |
from link_conversions import (
|
| 29 |
ConvertedSkill,
|
| 30 |
_build_new_entity_page,
|
|
@@ -504,6 +505,31 @@ class TestRun:
|
|
| 504 |
log_content = (wiki / "log.md").read_text()
|
| 505 |
assert "link-conversions" in log_content
|
| 506 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 507 |
|
| 508 |
# ---------------------------------------------------------------------------
|
| 509 |
# main()
|
|
|
|
| 25 |
sys.path.insert(0, str(Path(__file__).parents[1]))
|
| 26 |
|
| 27 |
import link_conversions as _lc
|
| 28 |
+
from ctx.core.wiki.wiki_packs import load_merged_wiki_pages, write_wiki_base_pack
|
| 29 |
from link_conversions import (
|
| 30 |
ConvertedSkill,
|
| 31 |
_build_new_entity_page,
|
|
|
|
| 505 |
log_content = (wiki / "log.md").read_text()
|
| 506 |
assert "link-conversions" in log_content
|
| 507 |
|
| 508 |
+
def test_pack_only_wiki_is_updated_through_overlays(self, tmp_path):
|
| 509 |
+
wiki = tmp_path / "wiki"
|
| 510 |
+
(wiki / "converted").mkdir(parents=True)
|
| 511 |
+
write_wiki_base_pack(
|
| 512 |
+
pack_dir=wiki / "wiki-packs" / "base-export-1",
|
| 513 |
+
pack_id="base-export-1",
|
| 514 |
+
base_export_id="export-1",
|
| 515 |
+
pages={
|
| 516 |
+
"index.md": "# Index\n\n## Skills\n\n## Total pages: 0 | Last updated: 2024-01-01\n",
|
| 517 |
+
"log.md": "# Log\n",
|
| 518 |
+
},
|
| 519 |
+
)
|
| 520 |
+
_make_converted_skill(wiki, "react")
|
| 521 |
+
|
| 522 |
+
result = run(wiki, tmp_path / "skills")
|
| 523 |
+
|
| 524 |
+
assert result.created == ["react"]
|
| 525 |
+
assert result.errors == []
|
| 526 |
+
assert not (wiki / "entities" / "skills" / "react.md").exists()
|
| 527 |
+
merged = load_merged_wiki_pages(wiki / "wiki-packs")
|
| 528 |
+
assert "has_pipeline: true" in merged["entities/skills/react.md"]
|
| 529 |
+
assert "[[entities/skills/react]]" in merged["index.md"]
|
| 530 |
+
assert "link-conversions" in merged["log.md"]
|
| 531 |
+
assert "react" in merged["converted-index.md"]
|
| 532 |
+
|
| 533 |
|
| 534 |
# ---------------------------------------------------------------------------
|
| 535 |
# main()
|
src/tests/test_lint.py
CHANGED
|
@@ -7,6 +7,7 @@ Every test builds its own minimal wiki structure via tmp_path so the real
|
|
| 7 |
|
| 8 |
from __future__ import annotations
|
| 9 |
|
|
|
|
| 10 |
import sys
|
| 11 |
from pathlib import Path
|
| 12 |
|
|
@@ -14,11 +15,12 @@ from pathlib import Path
|
|
| 14 |
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 15 |
|
| 16 |
from ctx.core.wiki import wiki_lint as wl # noqa: E402
|
|
|
|
| 17 |
|
| 18 |
from ._wiki_helpers import _FRESH_DATE, _STALE_DATE, make_entity_page, make_wiki # noqa: E402
|
| 19 |
|
| 20 |
|
| 21 |
-
def _collect(wiki: Path) -> dict[str,
|
| 22 |
"""Thin wrapper around wiki_lint's internal page collector."""
|
| 23 |
return wl._collect_pages(wiki)
|
| 24 |
|
|
@@ -225,3 +227,55 @@ class TestLintFixIndex:
|
|
| 225 |
assert text.index("- [[entities/mcp-servers/g/github]]") > text.index("## MCP Servers")
|
| 226 |
assert text.index("- [[entities/harnesses/openhands]]") > text.index("## Harnesses")
|
| 227 |
assert text.index("- [[entities/agents/reviewer]]") < text.index("## MCP Servers")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
from __future__ import annotations
|
| 9 |
|
| 10 |
+
import re
|
| 11 |
import sys
|
| 12 |
from pathlib import Path
|
| 13 |
|
|
|
|
| 15 |
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 16 |
|
| 17 |
from ctx.core.wiki import wiki_lint as wl # noqa: E402
|
| 18 |
+
from ctx.core.wiki.wiki_packs import load_merged_wiki_pages, write_wiki_base_pack # noqa: E402
|
| 19 |
|
| 20 |
from ._wiki_helpers import _FRESH_DATE, _STALE_DATE, make_entity_page, make_wiki # noqa: E402
|
| 21 |
|
| 22 |
|
| 23 |
+
def _collect(wiki: Path) -> dict[str, wl.WikiPage]:
|
| 24 |
"""Thin wrapper around wiki_lint's internal page collector."""
|
| 25 |
return wl._collect_pages(wiki)
|
| 26 |
|
|
|
|
| 227 |
assert text.index("- [[entities/mcp-servers/g/github]]") > text.index("## MCP Servers")
|
| 228 |
assert text.index("- [[entities/harnesses/openhands]]") > text.index("## Harnesses")
|
| 229 |
assert text.index("- [[entities/agents/reviewer]]") < text.index("## MCP Servers")
|
| 230 |
+
|
| 231 |
+
def test_fix_index_writes_pack_overlay_when_wiki_is_pack_only(self, tmp_path: Path) -> None:
|
| 232 |
+
wiki = tmp_path / "wiki"
|
| 233 |
+
write_wiki_base_pack(
|
| 234 |
+
pack_dir=wiki / "wiki-packs" / "base-export-1",
|
| 235 |
+
pack_id="base-export-1",
|
| 236 |
+
base_export_id="wiki-export-1",
|
| 237 |
+
pages={
|
| 238 |
+
"index.md": "# Index\n\n## Skills\n\n## Agents\n",
|
| 239 |
+
"entities/skills/pack-skill.md": """---
|
| 240 |
+
title: pack-skill
|
| 241 |
+
created: 2026-01-01
|
| 242 |
+
updated: 2026-03-01
|
| 243 |
+
type: skill
|
| 244 |
+
tags: [python]
|
| 245 |
+
---
|
| 246 |
+
|
| 247 |
+
Body with [[entities/skills/pack-skill]].
|
| 248 |
+
""",
|
| 249 |
+
},
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
pages = _collect(wiki)
|
| 253 |
+
assert "entities/skills/pack-skill" in pages
|
| 254 |
+
added = wl.fix_index(wiki, ["entities/skills/pack-skill"])
|
| 255 |
+
|
| 256 |
+
assert added == 1
|
| 257 |
+
assert not (wiki / "index.md").exists()
|
| 258 |
+
merged = load_merged_wiki_pages(wiki / "wiki-packs")
|
| 259 |
+
assert "- [[entities/skills/pack-skill]]" in merged["index.md"]
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class TestLintFixLogRotation:
|
| 263 |
+
def test_fix_log_rotation_writes_pack_overlay_when_wiki_is_pack_only(
|
| 264 |
+
self, tmp_path: Path
|
| 265 |
+
) -> None:
|
| 266 |
+
wiki = tmp_path / "wiki"
|
| 267 |
+
entries = "".join(f"## [2026-01-{(i % 28) + 1:02d}] entry {i}\n\n" for i in range(505))
|
| 268 |
+
write_wiki_base_pack(
|
| 269 |
+
pack_dir=wiki / "wiki-packs" / "base-export-1",
|
| 270 |
+
pack_id="base-export-1",
|
| 271 |
+
base_export_id="wiki-export-1",
|
| 272 |
+
pages={"log.md": "# Log\n\n" + entries},
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
assert wl.fix_log_rotation(wiki) is True
|
| 276 |
+
|
| 277 |
+
merged = load_merged_wiki_pages(wiki / "wiki-packs")
|
| 278 |
+
assert len(re.findall(r"^##\s+\[", merged["log.md"], re.MULTILINE)) == 100
|
| 279 |
+
archive = f"log-archive-{wl.TODAY.isoformat()}.md"
|
| 280 |
+
assert archive in merged
|
| 281 |
+
assert "entry 0" in merged[archive]
|
src/tests/test_maintainer_script_bom_inputs.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import sqlite3
|
| 5 |
+
import sys
|
| 6 |
+
import zlib
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from scripts import audit_backup
|
| 10 |
+
from scripts.build_dashboard_graph_index import build_dashboard_index
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_audit_backup_accepts_bom_manifest(
|
| 14 |
+
tmp_path: Path,
|
| 15 |
+
monkeypatch,
|
| 16 |
+
capsys,
|
| 17 |
+
) -> None:
|
| 18 |
+
claude_home = tmp_path / "home" / ".claude"
|
| 19 |
+
claude_home.mkdir(parents=True)
|
| 20 |
+
config = claude_home / "skill-system-config.json"
|
| 21 |
+
config.write_text('{"ok": true}', encoding="utf-8")
|
| 22 |
+
snapshot = tmp_path / "snapshot"
|
| 23 |
+
snapshot.mkdir()
|
| 24 |
+
manifest = {
|
| 25 |
+
"entries": [
|
| 26 |
+
{
|
| 27 |
+
"source": str(config),
|
| 28 |
+
"dest": "skill-system-config.json",
|
| 29 |
+
"size": config.stat().st_size,
|
| 30 |
+
}
|
| 31 |
+
]
|
| 32 |
+
}
|
| 33 |
+
(snapshot / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8-sig")
|
| 34 |
+
|
| 35 |
+
monkeypatch.setattr(audit_backup, "CLAUDE_HOME", claude_home)
|
| 36 |
+
monkeypatch.setattr(sys, "argv", ["audit_backup.py", str(snapshot)])
|
| 37 |
+
|
| 38 |
+
assert audit_backup.main() == 0
|
| 39 |
+
output = capsys.readouterr().out
|
| 40 |
+
assert "entries: 1" in output
|
| 41 |
+
assert "OK:" in output
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_dashboard_graph_index_accepts_bom_graph_json(tmp_path: Path) -> None:
|
| 45 |
+
graph_json = tmp_path / "graph.json"
|
| 46 |
+
output = tmp_path / "dashboard.sqlite3"
|
| 47 |
+
graph_json.write_text(
|
| 48 |
+
json.dumps({
|
| 49 |
+
"graph": {"export_id": "fixture"},
|
| 50 |
+
"nodes": [
|
| 51 |
+
{
|
| 52 |
+
"id": "skill:alpha",
|
| 53 |
+
"label": "Alpha",
|
| 54 |
+
"type": "skill",
|
| 55 |
+
"tags": ["python", "test"],
|
| 56 |
+
"quality_score": 0.9,
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"id": "mcp-server:github",
|
| 60 |
+
"label": "GitHub",
|
| 61 |
+
"type": "mcp-server",
|
| 62 |
+
"tags": ["github"],
|
| 63 |
+
},
|
| 64 |
+
],
|
| 65 |
+
"links": [
|
| 66 |
+
{
|
| 67 |
+
"source": "skill:alpha",
|
| 68 |
+
"target": "mcp-server:github",
|
| 69 |
+
"weight": 0.77,
|
| 70 |
+
"shared_tags": ["github"],
|
| 71 |
+
"reasons": ["fixture"],
|
| 72 |
+
}
|
| 73 |
+
],
|
| 74 |
+
}),
|
| 75 |
+
encoding="utf-8-sig",
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
build_dashboard_index(graph_json, output, top_k=5)
|
| 79 |
+
|
| 80 |
+
conn = sqlite3.connect(output)
|
| 81 |
+
try:
|
| 82 |
+
assert conn.execute(
|
| 83 |
+
"SELECT value FROM meta WHERE key='nodes_count'",
|
| 84 |
+
).fetchone() == ("2",)
|
| 85 |
+
payload = conn.execute(
|
| 86 |
+
"SELECT payload FROM neighbors WHERE source='skill:alpha'",
|
| 87 |
+
).fetchone()[0]
|
| 88 |
+
finally:
|
| 89 |
+
conn.close()
|
| 90 |
+
neighbors = json.loads(zlib.decompress(payload).decode("utf-8"))
|
| 91 |
+
assert neighbors[0]["target"] == "mcp-server:github"
|
src/tests/test_mcp_add.py
CHANGED
|
@@ -31,6 +31,7 @@ if str(SRC_DIR) not in sys.path:
|
|
| 31 |
|
| 32 |
from mcp_entity import McpRecord # noqa: E402
|
| 33 |
from ctx.core.wiki import wiki_queue # noqa: E402
|
|
|
|
| 34 |
|
| 35 |
|
| 36 |
# ---------------------------------------------------------------------------
|
|
@@ -248,7 +249,17 @@ class TestAddMcpExistingReview:
|
|
| 248 |
self, patched_mcp_add: Any, wiki_dir: Path
|
| 249 |
) -> None:
|
| 250 |
record_a = _make_record(name="github-mcp", sources=["awesome-mcp"])
|
| 251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
|
| 253 |
record_b = _make_record(
|
| 254 |
name="github-mcp",
|
|
@@ -263,13 +274,15 @@ class TestAddMcpExistingReview:
|
|
| 263 |
)
|
| 264 |
|
| 265 |
page = wiki_dir / "entities" / "mcp-servers" / "g" / "github-mcp.md"
|
| 266 |
-
|
|
|
|
| 267 |
_, fm_block, _ = text.split("---", 2)
|
| 268 |
fm = yaml.safe_load(fm_block)
|
| 269 |
assert isinstance(fm, dict)
|
| 270 |
assert result["is_new_page"] is False
|
| 271 |
assert result["skipped"] is False
|
| 272 |
assert result["merged_sources"] == ["awesome-mcp", "pulsemcp"]
|
|
|
|
| 273 |
assert fm["sources"] == ["awesome-mcp", "pulsemcp"]
|
| 274 |
assert fm["description"] == record_b.description
|
| 275 |
assert record_b.description in text
|
|
@@ -526,15 +539,27 @@ class TestCrossSourceCanonicalKeyDedup:
|
|
| 526 |
def test_second_source_merges_into_first_entity_path(
|
| 527 |
self, patched_mcp_add: Any, wiki_dir: Path
|
| 528 |
) -> None:
|
| 529 |
-
# awesome-mcp
|
|
|
|
| 530 |
record_awesome = _make_record(
|
| 531 |
name="modelcontextprotocol/servers",
|
| 532 |
github_url="https://github.com/modelcontextprotocol/servers",
|
| 533 |
sources=["awesome-mcp"],
|
| 534 |
)
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 538 |
|
| 539 |
# pulsemcp finds the same repo under a different slug.
|
| 540 |
record_pulsemcp = _make_record(
|
|
@@ -557,11 +582,67 @@ class TestCrossSourceCanonicalKeyDedup:
|
|
| 557 |
first_path.relative_to(wiki_dir)
|
| 558 |
).replace("\\", "/")
|
| 559 |
|
| 560 |
-
# And only ONE
|
| 561 |
-
|
| 562 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 563 |
)
|
| 564 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 565 |
|
| 566 |
def test_records_without_github_url_still_use_slug_dedup(
|
| 567 |
self, patched_mcp_add: Any, wiki_dir: Path
|
|
@@ -751,3 +832,120 @@ class TestAddMcpFromFixtures:
|
|
| 751 |
record = McpRecord.from_dict(data)
|
| 752 |
result = patched_mcp_add.add_mcp(record=record, wiki_path=wiki_dir)
|
| 753 |
assert result["is_new_page"] is True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
from mcp_entity import McpRecord # noqa: E402
|
| 33 |
from ctx.core.wiki import wiki_queue # noqa: E402
|
| 34 |
+
from ctx.core.wiki.wiki_packs import load_merged_wiki_pages, write_wiki_base_pack # noqa: E402
|
| 35 |
|
| 36 |
|
| 37 |
# ---------------------------------------------------------------------------
|
|
|
|
| 249 |
self, patched_mcp_add: Any, wiki_dir: Path
|
| 250 |
) -> None:
|
| 251 |
record_a = _make_record(name="github-mcp", sources=["awesome-mcp"])
|
| 252 |
+
packs_dir = wiki_dir / "wiki-packs"
|
| 253 |
+
write_wiki_base_pack(
|
| 254 |
+
pack_dir=packs_dir / "base-export-1",
|
| 255 |
+
pack_id="base-export-1",
|
| 256 |
+
base_export_id="wiki-export-1",
|
| 257 |
+
pages={
|
| 258 |
+
"entities/mcp-servers/g/github-mcp.md": (
|
| 259 |
+
patched_mcp_add.generate_mcp_page(record_a)
|
| 260 |
+
)
|
| 261 |
+
},
|
| 262 |
+
)
|
| 263 |
|
| 264 |
record_b = _make_record(
|
| 265 |
name="github-mcp",
|
|
|
|
| 274 |
)
|
| 275 |
|
| 276 |
page = wiki_dir / "entities" / "mcp-servers" / "g" / "github-mcp.md"
|
| 277 |
+
merged = load_merged_wiki_pages(packs_dir)
|
| 278 |
+
text = merged["entities/mcp-servers/g/github-mcp.md"]
|
| 279 |
_, fm_block, _ = text.split("---", 2)
|
| 280 |
fm = yaml.safe_load(fm_block)
|
| 281 |
assert isinstance(fm, dict)
|
| 282 |
assert result["is_new_page"] is False
|
| 283 |
assert result["skipped"] is False
|
| 284 |
assert result["merged_sources"] == ["awesome-mcp", "pulsemcp"]
|
| 285 |
+
assert not page.exists()
|
| 286 |
assert fm["sources"] == ["awesome-mcp", "pulsemcp"]
|
| 287 |
assert fm["description"] == record_b.description
|
| 288 |
assert record_b.description in text
|
|
|
|
| 539 |
def test_second_source_merges_into_first_entity_path(
|
| 540 |
self, patched_mcp_add: Any, wiki_dir: Path
|
| 541 |
) -> None:
|
| 542 |
+
# awesome-mcp exists first under its name-derived slug, but only
|
| 543 |
+
# inside the modular wiki base pack.
|
| 544 |
record_awesome = _make_record(
|
| 545 |
name="modelcontextprotocol/servers",
|
| 546 |
github_url="https://github.com/modelcontextprotocol/servers",
|
| 547 |
sources=["awesome-mcp"],
|
| 548 |
)
|
| 549 |
+
first_path = (
|
| 550 |
+
wiki_dir / "entities" / "mcp-servers" / record_awesome.entity_relpath()
|
| 551 |
+
)
|
| 552 |
+
packs_dir = wiki_dir / "wiki-packs"
|
| 553 |
+
write_wiki_base_pack(
|
| 554 |
+
pack_dir=packs_dir / "base-export-1",
|
| 555 |
+
pack_id="base-export-1",
|
| 556 |
+
base_export_id="wiki-export-1",
|
| 557 |
+
pages={
|
| 558 |
+
first_path.relative_to(wiki_dir).as_posix(): (
|
| 559 |
+
patched_mcp_add.generate_mcp_page(record_awesome)
|
| 560 |
+
)
|
| 561 |
+
},
|
| 562 |
+
)
|
| 563 |
|
| 564 |
# pulsemcp finds the same repo under a different slug.
|
| 565 |
record_pulsemcp = _make_record(
|
|
|
|
| 582 |
first_path.relative_to(wiki_dir)
|
| 583 |
).replace("\\", "/")
|
| 584 |
|
| 585 |
+
# And only ONE logical MCP page exists in the merged wiki.
|
| 586 |
+
merged_pages = {
|
| 587 |
+
relpath: text
|
| 588 |
+
for relpath, text in load_merged_wiki_pages(packs_dir).items()
|
| 589 |
+
if relpath.startswith("entities/mcp-servers/") and relpath.endswith(".md")
|
| 590 |
+
}
|
| 591 |
+
assert sorted(merged_pages) == [first_path.relative_to(wiki_dir).as_posix()]
|
| 592 |
+
assert not first_path.exists()
|
| 593 |
+
|
| 594 |
+
def test_second_source_uses_pack_canonical_index_without_physical_scan(
|
| 595 |
+
self,
|
| 596 |
+
patched_mcp_add: Any,
|
| 597 |
+
wiki_dir: Path,
|
| 598 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 599 |
+
) -> None:
|
| 600 |
+
record_awesome = _make_record(
|
| 601 |
+
name="modelcontextprotocol/servers",
|
| 602 |
+
github_url="https://github.com/modelcontextprotocol/servers",
|
| 603 |
+
sources=["awesome-mcp"],
|
| 604 |
+
)
|
| 605 |
+
mcp_dir = wiki_dir / "entities" / "mcp-servers"
|
| 606 |
+
first_path = mcp_dir / record_awesome.entity_relpath()
|
| 607 |
+
packs_dir = wiki_dir / "wiki-packs"
|
| 608 |
+
write_wiki_base_pack(
|
| 609 |
+
pack_dir=packs_dir / "base-export-1",
|
| 610 |
+
pack_id="base-export-1",
|
| 611 |
+
base_export_id="wiki-export-1",
|
| 612 |
+
pages={
|
| 613 |
+
first_path.relative_to(wiki_dir).as_posix(): (
|
| 614 |
+
patched_mcp_add.generate_mcp_page(record_awesome)
|
| 615 |
+
)
|
| 616 |
+
},
|
| 617 |
+
)
|
| 618 |
+
target = patched_mcp_add._normalize_github_url(record_awesome.github_url)
|
| 619 |
+
assert target is not None
|
| 620 |
+
patched_mcp_add.mcp_canonical_index.upsert(
|
| 621 |
+
mcp_dir,
|
| 622 |
+
target,
|
| 623 |
+
slug=first_path.stem,
|
| 624 |
+
relpath=first_path.relative_to(mcp_dir).as_posix(),
|
| 625 |
+
)
|
| 626 |
+
|
| 627 |
+
def fail_physical_scan(*args: Any, **kwargs: Any) -> None:
|
| 628 |
+
raise AssertionError("physical MCP scan should not run on indexed pack hit")
|
| 629 |
+
|
| 630 |
+
monkeypatch.setattr(
|
| 631 |
+
patched_mcp_add,
|
| 632 |
+
"_scan_for_github_url",
|
| 633 |
+
fail_physical_scan,
|
| 634 |
+
)
|
| 635 |
+
|
| 636 |
+
record_pulsemcp = _make_record(
|
| 637 |
+
name="modelcontextprotocol-servers-mcp",
|
| 638 |
+
github_url="https://github.com/modelcontextprotocol/servers",
|
| 639 |
+
sources=["pulsemcp"],
|
| 640 |
)
|
| 641 |
+
result = patched_mcp_add.add_mcp(record=record_pulsemcp, wiki_path=wiki_dir)
|
| 642 |
+
|
| 643 |
+
assert result["is_new_page"] is False
|
| 644 |
+
assert result["path"] == str(first_path)
|
| 645 |
+
assert result["merged_sources"] == ["awesome-mcp", "pulsemcp"]
|
| 646 |
|
| 647 |
def test_records_without_github_url_still_use_slug_dedup(
|
| 648 |
self, patched_mcp_add: Any, wiki_dir: Path
|
|
|
|
| 832 |
record = McpRecord.from_dict(data)
|
| 833 |
result = patched_mcp_add.add_mcp(record=record, wiki_path=wiki_dir)
|
| 834 |
assert result["is_new_page"] is True
|
| 835 |
+
|
| 836 |
+
|
| 837 |
+
class TestAddMcpCliInput:
|
| 838 |
+
def test_from_json_accepts_utf8_bom(
|
| 839 |
+
self,
|
| 840 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 841 |
+
tmp_path: Path,
|
| 842 |
+
) -> None:
|
| 843 |
+
import mcp_add # noqa: PLC0415
|
| 844 |
+
|
| 845 |
+
record_path = tmp_path / "mcp.json"
|
| 846 |
+
record_path.write_text(
|
| 847 |
+
"\ufeff"
|
| 848 |
+
+ json.dumps(
|
| 849 |
+
{
|
| 850 |
+
"name": "bom-json-mcp",
|
| 851 |
+
"description": "MCP loaded from a Windows UTF-8 BOM JSON file.",
|
| 852 |
+
"sources": ["test"],
|
| 853 |
+
"github_url": "https://github.com/example/bom-json-mcp",
|
| 854 |
+
"tags": ["testing"],
|
| 855 |
+
}
|
| 856 |
+
),
|
| 857 |
+
encoding="utf-8",
|
| 858 |
+
)
|
| 859 |
+
wiki = tmp_path / "wiki"
|
| 860 |
+
monkeypatch.setattr(sys, "argv", [
|
| 861 |
+
"mcp_add.py",
|
| 862 |
+
"--from-json", str(record_path),
|
| 863 |
+
"--wiki", str(wiki),
|
| 864 |
+
])
|
| 865 |
+
monkeypatch.setattr("mcp_add.check_intake", _fake_allow)
|
| 866 |
+
monkeypatch.setattr("mcp_add.record_embedding", _fake_record_embedding)
|
| 867 |
+
monkeypatch.setattr("mcp_add.update_index", lambda *a, **k: None)
|
| 868 |
+
monkeypatch.setattr("mcp_add.append_log", lambda *a, **k: None)
|
| 869 |
+
|
| 870 |
+
mcp_add.main()
|
| 871 |
+
|
| 872 |
+
assert (
|
| 873 |
+
wiki / "entities" / "mcp-servers" / "b" / "bom-json-mcp.md"
|
| 874 |
+
).exists()
|
| 875 |
+
|
| 876 |
+
def test_from_stdin_accepts_utf8_bom(
|
| 877 |
+
self,
|
| 878 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 879 |
+
tmp_path: Path,
|
| 880 |
+
) -> None:
|
| 881 |
+
import io
|
| 882 |
+
import mcp_add # noqa: PLC0415
|
| 883 |
+
|
| 884 |
+
wiki = tmp_path / "wiki"
|
| 885 |
+
monkeypatch.setattr(sys, "argv", [
|
| 886 |
+
"mcp_add.py",
|
| 887 |
+
"--from-stdin",
|
| 888 |
+
"--wiki", str(wiki),
|
| 889 |
+
])
|
| 890 |
+
monkeypatch.setattr(
|
| 891 |
+
sys,
|
| 892 |
+
"stdin",
|
| 893 |
+
io.StringIO(
|
| 894 |
+
"\ufeff"
|
| 895 |
+
+ json.dumps(
|
| 896 |
+
{
|
| 897 |
+
"name": "bom-stdin-mcp",
|
| 898 |
+
"description": (
|
| 899 |
+
"MCP loaded from a Windows UTF-8 BOM stdin stream."
|
| 900 |
+
),
|
| 901 |
+
"sources": ["test"],
|
| 902 |
+
"github_url": "https://github.com/example/bom-stdin-mcp",
|
| 903 |
+
"tags": ["testing"],
|
| 904 |
+
}
|
| 905 |
+
)
|
| 906 |
+
+ "\n"
|
| 907 |
+
),
|
| 908 |
+
)
|
| 909 |
+
monkeypatch.setattr("mcp_add.check_intake", _fake_allow)
|
| 910 |
+
monkeypatch.setattr("mcp_add.record_embedding", _fake_record_embedding)
|
| 911 |
+
monkeypatch.setattr("mcp_add.update_index", lambda *a, **k: None)
|
| 912 |
+
monkeypatch.setattr("mcp_add.append_log", lambda *a, **k: None)
|
| 913 |
+
|
| 914 |
+
mcp_add.main()
|
| 915 |
+
|
| 916 |
+
assert (
|
| 917 |
+
wiki / "entities" / "mcp-servers" / "b" / "bom-stdin-mcp.md"
|
| 918 |
+
).exists()
|
| 919 |
+
|
| 920 |
+
def test_rejected_batch_exits_nonzero(
|
| 921 |
+
self,
|
| 922 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 923 |
+
tmp_path: Path,
|
| 924 |
+
) -> None:
|
| 925 |
+
import mcp_add # noqa: PLC0415
|
| 926 |
+
|
| 927 |
+
record_path = tmp_path / "mcp.json"
|
| 928 |
+
record_path.write_text(
|
| 929 |
+
json.dumps(
|
| 930 |
+
{
|
| 931 |
+
"name": "rejected-cli-mcp",
|
| 932 |
+
"description": "Rejected MCP candidate for exit-code regression.",
|
| 933 |
+
"sources": ["test"],
|
| 934 |
+
"github_url": "https://github.com/example/rejected-cli-mcp",
|
| 935 |
+
"tags": ["testing"],
|
| 936 |
+
}
|
| 937 |
+
),
|
| 938 |
+
encoding="utf-8",
|
| 939 |
+
)
|
| 940 |
+
monkeypatch.setattr(sys, "argv", [
|
| 941 |
+
"mcp_add.py",
|
| 942 |
+
"--from-json", str(record_path),
|
| 943 |
+
"--wiki", str(tmp_path / "wiki"),
|
| 944 |
+
])
|
| 945 |
+
monkeypatch.setattr("mcp_add.check_intake", _fake_reject)
|
| 946 |
+
monkeypatch.setattr("mcp_add.record_embedding", _fake_record_embedding)
|
| 947 |
+
|
| 948 |
+
with pytest.raises(SystemExit) as exc:
|
| 949 |
+
mcp_add.main()
|
| 950 |
+
|
| 951 |
+
assert exc.value.code == 1
|
src/tests/test_mcp_canonical_index.py
CHANGED
|
@@ -30,6 +30,7 @@ if str(SRC_DIR) not in sys.path:
|
|
| 30 |
sys.path.insert(0, str(SRC_DIR))
|
| 31 |
|
| 32 |
import mcp_canonical_index as mci # noqa: E402
|
|
|
|
| 33 |
|
| 34 |
|
| 35 |
# ── Helpers ──────────────────────────────────────────────────────────────────
|
|
@@ -222,6 +223,42 @@ class TestRebuild:
|
|
| 222 |
assert skipped == 0
|
| 223 |
assert idx["by_github_url"] == {}
|
| 224 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
|
| 226 |
# ── Integration: mcp_add._find_existing_by_github_url with cache ────────────
|
| 227 |
|
|
|
|
| 30 |
sys.path.insert(0, str(SRC_DIR))
|
| 31 |
|
| 32 |
import mcp_canonical_index as mci # noqa: E402
|
| 33 |
+
from ctx.core.wiki.wiki_packs import write_wiki_base_pack # noqa: E402
|
| 34 |
|
| 35 |
|
| 36 |
# ── Helpers ──────────────────────────────────────────────────────────────────
|
|
|
|
| 223 |
assert skipped == 0
|
| 224 |
assert idx["by_github_url"] == {}
|
| 225 |
|
| 226 |
+
def test_rebuilds_from_pack_only_wiki_pages(self, tmp_path: Path) -> None:
|
| 227 |
+
wiki = tmp_path / "wiki"
|
| 228 |
+
mcp_dir = wiki / "entities" / "mcp-servers"
|
| 229 |
+
write_wiki_base_pack(
|
| 230 |
+
pack_dir=wiki / "wiki-packs" / "base-export-1",
|
| 231 |
+
pack_id="base-export-1",
|
| 232 |
+
base_export_id="wiki-export-1",
|
| 233 |
+
pages={
|
| 234 |
+
"entities/mcp-servers/a/alpha.md": (
|
| 235 |
+
"---\n"
|
| 236 |
+
"name: alpha\n"
|
| 237 |
+
"github_url: https://github.com/Org/Alpha\n"
|
| 238 |
+
"---\n"
|
| 239 |
+
"# alpha\n"
|
| 240 |
+
),
|
| 241 |
+
"entities/mcp-servers/b/beta.md": (
|
| 242 |
+
"---\n"
|
| 243 |
+
"name: beta\n"
|
| 244 |
+
"---\n"
|
| 245 |
+
"# beta\n"
|
| 246 |
+
),
|
| 247 |
+
},
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
idx, indexed, skipped = mci.rebuild_from_scan(mcp_dir)
|
| 251 |
+
|
| 252 |
+
assert indexed == 1
|
| 253 |
+
assert skipped == 1
|
| 254 |
+
assert idx["by_github_url"] == {
|
| 255 |
+
"https://github.com/org/alpha": {
|
| 256 |
+
"slug": "alpha",
|
| 257 |
+
"relpath": "a/alpha.md",
|
| 258 |
+
}
|
| 259 |
+
}
|
| 260 |
+
assert (mcp_dir / mci.INDEX_FILENAME).is_file()
|
| 261 |
+
|
| 262 |
|
| 263 |
# ── Integration: mcp_add._find_existing_by_github_url with cache ────────────
|
| 264 |
|
src/tests/test_mcp_enrich_render_scalar.py
CHANGED
|
@@ -26,6 +26,7 @@ from pathlib import Path
|
|
| 26 |
sys.path.insert(0, str(Path(__file__).parents[1]))
|
| 27 |
|
| 28 |
import mcp_enrich as _me
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
class TestRenderScalar:
|
|
@@ -119,3 +120,47 @@ class TestRenderScalar:
|
|
| 119 |
f"YAML injection via newline succeeded — found status keys: "
|
| 120 |
f"{status_keys!r}\nFull frontmatter:\n{fm}"
|
| 121 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
sys.path.insert(0, str(Path(__file__).parents[1]))
|
| 27 |
|
| 28 |
import mcp_enrich as _me
|
| 29 |
+
from ctx.core.wiki.wiki_packs import load_merged_wiki_pages, write_wiki_base_pack
|
| 30 |
|
| 31 |
|
| 32 |
class TestRenderScalar:
|
|
|
|
| 120 |
f"YAML injection via newline succeeded — found status keys: "
|
| 121 |
f"{status_keys!r}\nFull frontmatter:\n{fm}"
|
| 122 |
)
|
| 123 |
+
|
| 124 |
+
def test_enrich_entities_updates_pack_only_mcp_page(self, tmp_path, monkeypatch):
|
| 125 |
+
wiki = tmp_path / "wiki"
|
| 126 |
+
relpath = "entities/mcp-servers/p/pack-only.md"
|
| 127 |
+
write_wiki_base_pack(
|
| 128 |
+
pack_dir=wiki / "wiki-packs" / "base-export-1",
|
| 129 |
+
pack_id="base-export-1",
|
| 130 |
+
base_export_id="wiki-export-1",
|
| 131 |
+
pages={
|
| 132 |
+
relpath: (
|
| 133 |
+
"---\n"
|
| 134 |
+
"name: Pack Only\n"
|
| 135 |
+
"homepage_url: https://www.pulsemcp.com/servers/source-slug\n"
|
| 136 |
+
"github_url: null\n"
|
| 137 |
+
"stars: null\n"
|
| 138 |
+
"updated: '2026-01-01'\n"
|
| 139 |
+
"---\n"
|
| 140 |
+
"# Pack Only\n"
|
| 141 |
+
)
|
| 142 |
+
},
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
class Source:
|
| 146 |
+
def fetch_details(self, slug, *, refresh=False): # noqa: ARG002, ANN001, ANN201
|
| 147 |
+
assert slug == "source-slug"
|
| 148 |
+
return {"github_url": "https://github.com/example/pack-only", "stars": 7}
|
| 149 |
+
|
| 150 |
+
monkeypatch.setitem(_me.SOURCES, "pulsemcp", Source())
|
| 151 |
+
|
| 152 |
+
entity_paths = list(_me._iter_entities(wiki))
|
| 153 |
+
checkpoint = _me._empty_checkpoint("pulsemcp")
|
| 154 |
+
_me.enrich_entities(
|
| 155 |
+
entity_paths,
|
| 156 |
+
source_name="pulsemcp",
|
| 157 |
+
wiki_path=wiki,
|
| 158 |
+
checkpoint=checkpoint,
|
| 159 |
+
sleep_seconds=0,
|
| 160 |
+
report_progress=False,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
merged = load_merged_wiki_pages(wiki / "wiki-packs")
|
| 164 |
+
assert 'github_url: "https://github.com/example/pack-only"' in merged[relpath]
|
| 165 |
+
assert "stars: 7" in merged[relpath]
|
| 166 |
+
assert not (wiki / relpath).exists()
|
src/tests/test_mcp_quality.py
CHANGED
|
@@ -18,6 +18,7 @@ import sys
|
|
| 18 |
from datetime import datetime
|
| 19 |
from pathlib import Path
|
| 20 |
|
|
|
|
| 21 |
import pytest
|
| 22 |
|
| 23 |
SRC_DIR = Path(__file__).resolve().parents[1]
|
|
@@ -25,7 +26,9 @@ if str(SRC_DIR) not in sys.path:
|
|
| 25 |
sys.path.insert(0, str(SRC_DIR))
|
| 26 |
|
| 27 |
import mcp_quality as mq # noqa: E402
|
|
|
|
| 28 |
from ctx.core.quality.quality_signals import SignalResult # noqa: E402
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
# ---------------------------------------------------------------------------
|
|
@@ -389,6 +392,30 @@ class TestPersistQuality:
|
|
| 389 |
assert "- **Grade:** B" in content
|
| 390 |
assert "- **Computed:** 2026-04-21T00:00:00+00:00" in content
|
| 391 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
|
| 393 |
# ---------------------------------------------------------------------------
|
| 394 |
# TestLoadGraphIndex
|
|
@@ -470,6 +497,60 @@ class TestLoadGraphIndex:
|
|
| 470 |
# Cross-type = 2 (skill + agent only)
|
| 471 |
assert node["cross_type_degree"] == 2
|
| 472 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 473 |
|
| 474 |
# ---------------------------------------------------------------------------
|
| 475 |
# TestCLI
|
|
|
|
| 18 |
from datetime import datetime
|
| 19 |
from pathlib import Path
|
| 20 |
|
| 21 |
+
import networkx as nx
|
| 22 |
import pytest
|
| 23 |
|
| 24 |
SRC_DIR = Path(__file__).resolve().parents[1]
|
|
|
|
| 26 |
sys.path.insert(0, str(SRC_DIR))
|
| 27 |
|
| 28 |
import mcp_quality as mq # noqa: E402
|
| 29 |
+
from ctx.core.graph.graph_packs import write_base_pack, write_overlay_pack # noqa: E402
|
| 30 |
from ctx.core.quality.quality_signals import SignalResult # noqa: E402
|
| 31 |
+
from ctx.core.wiki.wiki_packs import load_merged_wiki_pages, write_wiki_base_pack # noqa: E402
|
| 32 |
|
| 33 |
|
| 34 |
# ---------------------------------------------------------------------------
|
|
|
|
| 392 |
assert "- **Grade:** B" in content
|
| 393 |
assert "- **Computed:** 2026-04-21T00:00:00+00:00" in content
|
| 394 |
|
| 395 |
+
def test_recompute_all_updates_pack_only_mcp_page(self, tmp_path: Path) -> None:
|
| 396 |
+
wiki_dir = tmp_path / "wiki"
|
| 397 |
+
relpath = "entities/mcp-servers/g/github.md"
|
| 398 |
+
write_wiki_base_pack(
|
| 399 |
+
pack_dir=wiki_dir / "wiki-packs" / "base-export-1",
|
| 400 |
+
pack_id="base-export-1",
|
| 401 |
+
base_export_id="wiki-export-1",
|
| 402 |
+
pages={relpath: _entity_frontmatter(name="github")},
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
assert mq.discover_mcp_slugs(wiki_dir) == ["github"]
|
| 406 |
+
|
| 407 |
+
scores, failures = mq.recompute_all(
|
| 408 |
+
wiki_dir=wiki_dir,
|
| 409 |
+
sidecar_dir=tmp_path / "quality",
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
assert failures == []
|
| 413 |
+
assert [score.slug for score in scores] == ["github"]
|
| 414 |
+
merged = load_merged_wiki_pages(wiki_dir / "wiki-packs")
|
| 415 |
+
assert "quality_score:" in merged[relpath]
|
| 416 |
+
assert "<!-- quality:begin -->" in merged[relpath]
|
| 417 |
+
assert not (wiki_dir / relpath).exists()
|
| 418 |
+
|
| 419 |
|
| 420 |
# ---------------------------------------------------------------------------
|
| 421 |
# TestLoadGraphIndex
|
|
|
|
| 497 |
# Cross-type = 2 (skill + agent only)
|
| 498 |
assert node["cross_type_degree"] == 2
|
| 499 |
|
| 500 |
+
def test_active_graph_packs_override_stale_graph_json(
|
| 501 |
+
self, tmp_path: Path
|
| 502 |
+
) -> None:
|
| 503 |
+
wiki_dir = tmp_path / "wiki"
|
| 504 |
+
graph_dir = wiki_dir / "graphify-out"
|
| 505 |
+
packs_dir = graph_dir / "packs"
|
| 506 |
+
graph_dir.mkdir(parents=True)
|
| 507 |
+
(graph_dir / "graph.json").write_text(
|
| 508 |
+
json.dumps({
|
| 509 |
+
"directed": False,
|
| 510 |
+
"multigraph": False,
|
| 511 |
+
"graph": {},
|
| 512 |
+
"nodes": [
|
| 513 |
+
{"id": "mcp-server:github", "type": "mcp-server"},
|
| 514 |
+
{"id": "mcp-server:stale", "type": "mcp-server"},
|
| 515 |
+
],
|
| 516 |
+
"edges": [
|
| 517 |
+
{"source": "mcp-server:github", "target": "mcp-server:stale"},
|
| 518 |
+
],
|
| 519 |
+
}),
|
| 520 |
+
encoding="utf-8",
|
| 521 |
+
)
|
| 522 |
+
graph = nx.Graph()
|
| 523 |
+
graph.add_node("mcp-server:github", type="mcp-server")
|
| 524 |
+
graph.add_node("skill:git", type="skill")
|
| 525 |
+
graph.add_edge("mcp-server:github", "skill:git")
|
| 526 |
+
write_base_pack(
|
| 527 |
+
pack_dir=packs_dir / "base-export-1",
|
| 528 |
+
pack_id="base-export-1",
|
| 529 |
+
base_export_id="export-1",
|
| 530 |
+
config_hash="config-sha",
|
| 531 |
+
model_id="test-model",
|
| 532 |
+
graph=graph,
|
| 533 |
+
)
|
| 534 |
+
write_overlay_pack(
|
| 535 |
+
pack_dir=packs_dir / "overlay-agent",
|
| 536 |
+
pack_id="overlay-agent",
|
| 537 |
+
base_export_id="export-1",
|
| 538 |
+
parent_export_id="export-1",
|
| 539 |
+
config_hash="config-sha",
|
| 540 |
+
model_id="test-model",
|
| 541 |
+
nodes=[{"id": "agent:coder", "type": "agent"}],
|
| 542 |
+
edges=[{"source": "mcp-server:github", "target": "agent:coder"}],
|
| 543 |
+
tombstones=[],
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
index = mq.load_graph_index(wiki_dir)
|
| 547 |
+
|
| 548 |
+
assert "mcp-server:stale" not in index
|
| 549 |
+
assert index["mcp-server:github"] == {
|
| 550 |
+
"degree": 2,
|
| 551 |
+
"cross_type_degree": 2,
|
| 552 |
+
}
|
| 553 |
+
|
| 554 |
|
| 555 |
# ---------------------------------------------------------------------------
|
| 556 |
# TestCLI
|
src/tests/test_mcp_server.py
CHANGED
|
@@ -32,6 +32,7 @@ from typing import Any
|
|
| 32 |
|
| 33 |
import pytest
|
| 34 |
|
|
|
|
| 35 |
from ctx.adapters.generic.tools import (
|
| 36 |
McpClient,
|
| 37 |
McpServerConfig,
|
|
@@ -110,6 +111,19 @@ def _mcp_subprocess_env(wiki: Path, graph_path: Path) -> dict[str, str]:
|
|
| 110 |
}
|
| 111 |
|
| 112 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
# ── Server-level loop behaviour ─────────────────────────────────────────────
|
| 114 |
|
| 115 |
|
|
@@ -130,6 +144,22 @@ class TestRunServerLifecycle:
|
|
| 130 |
# id is null when the request couldn't be parsed.
|
| 131 |
assert frames[0]["id"] is None
|
| 132 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
def test_non_object_request_rejected(self) -> None:
|
| 134 |
frames = _drive(b"[1, 2, 3]\n")
|
| 135 |
assert frames[0]["error"]["code"] == _ErrorCode.INVALID_REQUEST
|
|
@@ -188,6 +218,20 @@ class TestNotifications:
|
|
| 188 |
frames = _drive(_encode_notification("ping"))
|
| 189 |
assert frames == []
|
| 190 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
def test_cancelled_notification_is_silent(self) -> None:
|
| 192 |
frames = _drive(_encode_notification("notifications/cancelled", {"requestId": 1}))
|
| 193 |
assert frames == []
|
|
@@ -234,6 +278,37 @@ class TestToolsCall:
|
|
| 234 |
frames = _drive(_encode_request(1, "tools/call", {"arguments": {}}))
|
| 235 |
assert frames[0]["error"]["code"] == _ErrorCode.INVALID_PARAMS
|
| 236 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
def test_non_dict_arguments_yields_invalid_params(self) -> None:
|
| 238 |
frames = _drive(
|
| 239 |
_encode_request(
|
|
|
|
| 32 |
|
| 33 |
import pytest
|
| 34 |
|
| 35 |
+
import ctx.mcp_server.server as mcp_server
|
| 36 |
from ctx.adapters.generic.tools import (
|
| 37 |
McpClient,
|
| 38 |
McpServerConfig,
|
|
|
|
| 111 |
}
|
| 112 |
|
| 113 |
|
| 114 |
+
@pytest.fixture()
|
| 115 |
+
def captured_mcp_events(
|
| 116 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 117 |
+
) -> list[dict[str, Any]]:
|
| 118 |
+
events: list[dict[str, Any]] = []
|
| 119 |
+
|
| 120 |
+
def _capture_record_event(event_name: str, **kwargs: Any) -> None:
|
| 121 |
+
events.append({"event_name": event_name, **kwargs})
|
| 122 |
+
|
| 123 |
+
monkeypatch.setattr(mcp_server, "record_event", _capture_record_event)
|
| 124 |
+
return events
|
| 125 |
+
|
| 126 |
+
|
| 127 |
# ── Server-level loop behaviour ─────────────────────────────────────────────
|
| 128 |
|
| 129 |
|
|
|
|
| 144 |
# id is null when the request couldn't be parsed.
|
| 145 |
assert frames[0]["id"] is None
|
| 146 |
|
| 147 |
+
def test_invalid_json_emits_parse_error_telemetry(
|
| 148 |
+
self,
|
| 149 |
+
captured_mcp_events: list[dict[str, Any]],
|
| 150 |
+
) -> None:
|
| 151 |
+
raw_frame = "{not valid json"
|
| 152 |
+
|
| 153 |
+
_drive((raw_frame + "\n").encode("utf-8"))
|
| 154 |
+
|
| 155 |
+
event = captured_mcp_events[-1]
|
| 156 |
+
assert event["event_name"] == "ctx.mcp.request"
|
| 157 |
+
assert event["outcome"] == "error"
|
| 158 |
+
assert event["error_kind"] == "parse_error"
|
| 159 |
+
assert event["payload"]["rpc.method"] == "<parse-error>"
|
| 160 |
+
assert event["payload"]["otel.status_code"] == "ERROR"
|
| 161 |
+
assert raw_frame not in json.dumps(event["payload"])
|
| 162 |
+
|
| 163 |
def test_non_object_request_rejected(self) -> None:
|
| 164 |
frames = _drive(b"[1, 2, 3]\n")
|
| 165 |
assert frames[0]["error"]["code"] == _ErrorCode.INVALID_REQUEST
|
|
|
|
| 218 |
frames = _drive(_encode_notification("ping"))
|
| 219 |
assert frames == []
|
| 220 |
|
| 221 |
+
def test_ping_notification_emits_no_response_telemetry(
|
| 222 |
+
self,
|
| 223 |
+
captured_mcp_events: list[dict[str, Any]],
|
| 224 |
+
) -> None:
|
| 225 |
+
frames = _drive(_encode_notification("ping"))
|
| 226 |
+
|
| 227 |
+
assert frames == []
|
| 228 |
+
event = captured_mcp_events[-1]
|
| 229 |
+
assert event["event_name"] == "ctx.mcp.request"
|
| 230 |
+
assert event["outcome"] == "ok"
|
| 231 |
+
assert event["payload"]["rpc.method"] == "ping"
|
| 232 |
+
assert event["payload"]["ctx.notification"] is True
|
| 233 |
+
assert event["payload"]["ctx.response_emitted"] is False
|
| 234 |
+
|
| 235 |
def test_cancelled_notification_is_silent(self) -> None:
|
| 236 |
frames = _drive(_encode_notification("notifications/cancelled", {"requestId": 1}))
|
| 237 |
assert frames == []
|
|
|
|
| 278 |
frames = _drive(_encode_request(1, "tools/call", {"arguments": {}}))
|
| 279 |
assert frames[0]["error"]["code"] == _ErrorCode.INVALID_PARAMS
|
| 280 |
|
| 281 |
+
def test_tool_call_emits_otel_telemetry_without_raw_arguments(
|
| 282 |
+
self,
|
| 283 |
+
captured_mcp_events: list[dict[str, Any]],
|
| 284 |
+
) -> None:
|
| 285 |
+
raw_query = "private acme query"
|
| 286 |
+
frames = _drive(
|
| 287 |
+
_encode_request(
|
| 288 |
+
1,
|
| 289 |
+
"tools/call",
|
| 290 |
+
{
|
| 291 |
+
"name": "fs__read_file",
|
| 292 |
+
"arguments": {"query": raw_query, "top_k": 3},
|
| 293 |
+
},
|
| 294 |
+
)
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
assert frames[0]["error"]["code"] == _ErrorCode.METHOD_NOT_FOUND
|
| 298 |
+
event = captured_mcp_events[-1]
|
| 299 |
+
assert event["event_name"] == "ctx.mcp.request"
|
| 300 |
+
assert event["source"] == "ctx-mcp-server"
|
| 301 |
+
assert event["transport"] == "mcp-jsonrpc"
|
| 302 |
+
assert event["outcome"] == "error"
|
| 303 |
+
assert event["payload"]["rpc.method"] == "tools/call"
|
| 304 |
+
assert event["payload"]["ctx.tool.name"] == "fs__read_file"
|
| 305 |
+
assert event["payload"]["ctx.arguments.keys"] == ["query", "top_k"]
|
| 306 |
+
assert event["payload"]["ctx.query.length"] == len(raw_query)
|
| 307 |
+
assert event["payload"]["ctx.query.hash"].startswith("sha256:")
|
| 308 |
+
assert event["payload"]["ctx.arguments.top_k"] == 3
|
| 309 |
+
assert event["payload"]["otel.status_code"] == "ERROR"
|
| 310 |
+
assert raw_query not in json.dumps(event["payload"])
|
| 311 |
+
|
| 312 |
def test_non_dict_arguments_yields_invalid_params(self) -> None:
|
| 313 |
frames = _drive(
|
| 314 |
_encode_request(
|
src/tests/test_monitor_testing_api.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stable testing facade for ctx monitor internals."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import importlib
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_monitor_testing_facade_exposes_public_helper_names() -> None:
|
| 9 |
+
testing = importlib.import_module("ctx.monitor.testing")
|
| 10 |
+
|
| 11 |
+
assert callable(testing.read_jsonl)
|
| 12 |
+
assert callable(testing.render_graph)
|
| 13 |
+
assert callable(testing.make_monitor_server)
|
src/tests/test_pack_compaction.py
ADDED
|
@@ -0,0 +1,621 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import networkx as nx
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
from ctx.core.graph.graph_packs import (
|
| 11 |
+
discover_pack_manifests,
|
| 12 |
+
load_merged_pack_graph,
|
| 13 |
+
write_base_pack,
|
| 14 |
+
write_overlay_pack,
|
| 15 |
+
)
|
| 16 |
+
from ctx.core.graph.graph_store import graph_store_is_fresh, search_nodes
|
| 17 |
+
from ctx.core.wiki import pack_compaction
|
| 18 |
+
from ctx.core.wiki.pack_compaction import (
|
| 19 |
+
PackCompactionError,
|
| 20 |
+
compact_active_pack_sets,
|
| 21 |
+
pack_compaction_status,
|
| 22 |
+
promote_staged_pack_sets,
|
| 23 |
+
)
|
| 24 |
+
from ctx.core.wiki.wiki_packs import (
|
| 25 |
+
discover_wiki_pack_manifests,
|
| 26 |
+
load_merged_wiki_pages,
|
| 27 |
+
write_wiki_base_pack,
|
| 28 |
+
write_wiki_overlay_pack,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_compact_active_pack_sets_stages_graph_and_wiki_without_mutating_active(
|
| 33 |
+
tmp_path: Path,
|
| 34 |
+
) -> None:
|
| 35 |
+
wiki = tmp_path / "wiki"
|
| 36 |
+
graph_packs, wiki_packs = _write_active_pack_sets(wiki)
|
| 37 |
+
staging_dir = tmp_path / "staged-compaction"
|
| 38 |
+
|
| 39 |
+
result = compact_active_pack_sets(
|
| 40 |
+
wiki_path=wiki,
|
| 41 |
+
base_export_id="export-2",
|
| 42 |
+
staging_dir=staging_dir,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
assert result.graph_manifest.pack_id == "base-export-2"
|
| 46 |
+
assert result.wiki_manifest.pack_id == "base-export-2"
|
| 47 |
+
assert [entry.manifest.pack_id for entry in discover_pack_manifests(graph_packs)] == [
|
| 48 |
+
"base-export-1",
|
| 49 |
+
"overlay-new",
|
| 50 |
+
]
|
| 51 |
+
assert [entry.manifest.pack_id for entry in discover_wiki_pack_manifests(wiki_packs)] == [
|
| 52 |
+
"base-export-1",
|
| 53 |
+
"overlay-new",
|
| 54 |
+
]
|
| 55 |
+
compacted_graph = load_merged_pack_graph(staging_dir / "graph-packs")
|
| 56 |
+
assert "skill:old" not in compacted_graph
|
| 57 |
+
assert compacted_graph.has_edge("skill:new", "skill:keep")
|
| 58 |
+
assert load_merged_wiki_pages(staging_dir / "wiki-packs") == {
|
| 59 |
+
"entities/skills/keep.md": "# Keep\n",
|
| 60 |
+
"entities/skills/new.md": "# New\n",
|
| 61 |
+
}
|
| 62 |
+
manifest = json.loads((staging_dir / "pack-compaction-manifest.json").read_text())
|
| 63 |
+
assert manifest["schema_version"] == 1
|
| 64 |
+
assert manifest["operation"] == "pack-compaction-stage"
|
| 65 |
+
assert manifest["base_export_id"] == "export-2"
|
| 66 |
+
assert manifest["staged_graph_packs_dir"] == str(staging_dir / "graph-packs")
|
| 67 |
+
assert manifest["staged_wiki_packs_dir"] == str(staging_dir / "wiki-packs")
|
| 68 |
+
assert manifest["graph"]["pack_id"] == "base-export-2"
|
| 69 |
+
assert manifest["wiki"]["pack_id"] == "base-export-2"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_compact_active_pack_sets_rejects_graph_wiki_mismatch_before_return(
|
| 73 |
+
tmp_path: Path,
|
| 74 |
+
) -> None:
|
| 75 |
+
wiki = tmp_path / "wiki"
|
| 76 |
+
graph_packs, wiki_packs = _write_active_pack_sets(wiki)
|
| 77 |
+
staging_dir = tmp_path / "staged-compaction"
|
| 78 |
+
write_overlay_pack(
|
| 79 |
+
pack_dir=graph_packs / "overlay-missing-wiki",
|
| 80 |
+
pack_id="overlay-missing-wiki",
|
| 81 |
+
base_export_id="export-1",
|
| 82 |
+
parent_export_id="export-1",
|
| 83 |
+
config_hash="config-1",
|
| 84 |
+
model_id="model-1",
|
| 85 |
+
nodes=[{"id": "skill:missing-wiki", "type": "skill", "label": "missing wiki"}],
|
| 86 |
+
edges=[{"source": "skill:missing-wiki", "target": "skill:keep", "weight": 0.8}],
|
| 87 |
+
tombstones=[],
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
with pytest.raises(PackCompactionError, match="missing wiki pages"):
|
| 91 |
+
compact_active_pack_sets(
|
| 92 |
+
wiki_path=wiki,
|
| 93 |
+
base_export_id="export-2",
|
| 94 |
+
staging_dir=staging_dir,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
assert not staging_dir.exists()
|
| 98 |
+
assert [entry.manifest.pack_id for entry in discover_pack_manifests(graph_packs)] == [
|
| 99 |
+
"base-export-1",
|
| 100 |
+
"overlay-new",
|
| 101 |
+
"overlay-missing-wiki",
|
| 102 |
+
]
|
| 103 |
+
assert [entry.manifest.pack_id for entry in discover_wiki_pack_manifests(wiki_packs)] == [
|
| 104 |
+
"base-export-1",
|
| 105 |
+
"overlay-new",
|
| 106 |
+
]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def test_pack_compaction_cli_emits_json_for_staged_pack_sets(
|
| 110 |
+
tmp_path: Path,
|
| 111 |
+
capsys: pytest.CaptureFixture[str],
|
| 112 |
+
) -> None:
|
| 113 |
+
wiki = tmp_path / "wiki"
|
| 114 |
+
_write_active_pack_sets(wiki)
|
| 115 |
+
staging_dir = tmp_path / "staged-compaction"
|
| 116 |
+
|
| 117 |
+
result = pack_compaction.main([
|
| 118 |
+
"compact",
|
| 119 |
+
"--wiki-path",
|
| 120 |
+
str(wiki),
|
| 121 |
+
"--base-export-id",
|
| 122 |
+
"export-2",
|
| 123 |
+
"--staging-dir",
|
| 124 |
+
str(staging_dir),
|
| 125 |
+
"--json",
|
| 126 |
+
])
|
| 127 |
+
|
| 128 |
+
assert result == 0
|
| 129 |
+
payload = json.loads(capsys.readouterr().out)
|
| 130 |
+
assert payload["graph"]["pack_id"] == "base-export-2"
|
| 131 |
+
assert payload["wiki"]["pack_id"] == "base-export-2"
|
| 132 |
+
assert payload["staged_graph_packs_dir"] == str(staging_dir / "graph-packs")
|
| 133 |
+
assert payload["staged_wiki_packs_dir"] == str(staging_dir / "wiki-packs")
|
| 134 |
+
assert "skill:old" not in load_merged_pack_graph(staging_dir / "graph-packs")
|
| 135 |
+
assert "entities/skills/old.md" not in load_merged_wiki_pages(staging_dir / "wiki-packs")
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def test_pack_compaction_status_reports_overlay_threshold(
|
| 139 |
+
tmp_path: Path,
|
| 140 |
+
) -> None:
|
| 141 |
+
wiki = tmp_path / "wiki"
|
| 142 |
+
_write_active_pack_sets(wiki)
|
| 143 |
+
|
| 144 |
+
default_status = pack_compaction_status(wiki_path=wiki)
|
| 145 |
+
assert default_status["overlay_threshold"] == 25
|
| 146 |
+
assert default_status["needs_compaction"] is False
|
| 147 |
+
|
| 148 |
+
status = pack_compaction_status(
|
| 149 |
+
wiki_path=wiki,
|
| 150 |
+
overlay_threshold=1,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
assert status["base_export_id"] == "export-1"
|
| 154 |
+
assert status["graph_overlay_count"] == 1
|
| 155 |
+
assert status["wiki_overlay_count"] == 1
|
| 156 |
+
assert status["max_overlay_count"] == 1
|
| 157 |
+
assert status["overlay_threshold"] == 1
|
| 158 |
+
assert status["needs_compaction"] is True
|
| 159 |
+
assert status["can_compact_now"] is True
|
| 160 |
+
assert status["graph_pack_ids"] == ["base-export-1", "overlay-new"]
|
| 161 |
+
assert status["wiki_pack_ids"] == ["base-export-1", "overlay-new"]
|
| 162 |
+
validation = status["validation"]
|
| 163 |
+
assert isinstance(validation, dict)
|
| 164 |
+
assert validation["graph_nodes"] == 2
|
| 165 |
+
assert validation["wiki_pages"] == 2
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def test_pack_compaction_cli_status_emits_json(
|
| 169 |
+
tmp_path: Path,
|
| 170 |
+
capsys: pytest.CaptureFixture[str],
|
| 171 |
+
) -> None:
|
| 172 |
+
wiki = tmp_path / "wiki"
|
| 173 |
+
_write_active_pack_sets(wiki)
|
| 174 |
+
|
| 175 |
+
rc = pack_compaction.main([
|
| 176 |
+
"status",
|
| 177 |
+
"--wiki-path",
|
| 178 |
+
str(wiki),
|
| 179 |
+
"--overlay-threshold",
|
| 180 |
+
"2",
|
| 181 |
+
"--json",
|
| 182 |
+
])
|
| 183 |
+
|
| 184 |
+
assert rc == 0
|
| 185 |
+
payload = json.loads(capsys.readouterr().out)
|
| 186 |
+
assert payload["base_export_id"] == "export-1"
|
| 187 |
+
assert payload["max_overlay_count"] == 1
|
| 188 |
+
assert payload["overlay_threshold"] == 2
|
| 189 |
+
assert payload["needs_compaction"] is False
|
| 190 |
+
assert payload["can_compact_now"] is True
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def test_promote_staged_pack_sets_replaces_graph_and_wiki_with_backups(
|
| 194 |
+
tmp_path: Path,
|
| 195 |
+
) -> None:
|
| 196 |
+
wiki = tmp_path / "wiki"
|
| 197 |
+
_write_active_pack_sets(wiki)
|
| 198 |
+
staged = compact_active_pack_sets(
|
| 199 |
+
wiki_path=wiki,
|
| 200 |
+
base_export_id="export-2",
|
| 201 |
+
staging_dir=tmp_path / "staged-compaction",
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
result = promote_staged_pack_sets(
|
| 205 |
+
wiki_path=wiki,
|
| 206 |
+
staged_graph_packs_dir=staged.staged_graph_packs_dir,
|
| 207 |
+
staged_wiki_packs_dir=staged.staged_wiki_packs_dir,
|
| 208 |
+
graph_backup_packs_dir=tmp_path / "graph-packs.backup",
|
| 209 |
+
wiki_backup_packs_dir=tmp_path / "wiki-packs.backup",
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
active_graph = load_merged_pack_graph(wiki / "graphify-out" / "packs")
|
| 213 |
+
assert "skill:old" not in active_graph
|
| 214 |
+
assert active_graph.has_edge("skill:new", "skill:keep")
|
| 215 |
+
assert load_merged_wiki_pages(wiki / "wiki-packs") == {
|
| 216 |
+
"entities/skills/keep.md": "# Keep\n",
|
| 217 |
+
"entities/skills/new.md": "# New\n",
|
| 218 |
+
}
|
| 219 |
+
backup_graph = load_merged_pack_graph(tmp_path / "graph-packs.backup")
|
| 220 |
+
assert "skill:old" not in backup_graph
|
| 221 |
+
assert backup_graph.has_edge("skill:new", "skill:keep")
|
| 222 |
+
assert [entry.manifest.pack_id for entry in discover_pack_manifests(tmp_path / "graph-packs.backup")] == [
|
| 223 |
+
"base-export-1",
|
| 224 |
+
"overlay-new",
|
| 225 |
+
]
|
| 226 |
+
assert load_merged_wiki_pages(tmp_path / "wiki-packs.backup") == {
|
| 227 |
+
"entities/skills/keep.md": "# Keep\n",
|
| 228 |
+
"entities/skills/new.md": "# New\n",
|
| 229 |
+
}
|
| 230 |
+
assert [entry.manifest.pack_id for entry in discover_wiki_pack_manifests(tmp_path / "wiki-packs.backup")] == [
|
| 231 |
+
"base-export-1",
|
| 232 |
+
"overlay-new",
|
| 233 |
+
]
|
| 234 |
+
assert result.graph.promoted_pack_ids == ["base-export-2"]
|
| 235 |
+
assert result.wiki.promoted_pack_ids == ["base-export-2"]
|
| 236 |
+
store_path = wiki / "graphify-out" / "graph-store.sqlite3"
|
| 237 |
+
assert result.graph_store == {"rebuilt": True, "nodes": 2, "edges": 1}
|
| 238 |
+
assert graph_store_is_fresh(store_path, wiki / "graphify-out") is True
|
| 239 |
+
assert [row["id"] for row in search_nodes(store_path, "new")] == ["skill:new"]
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def test_pack_compaction_cli_promotes_staged_pack_sets(
|
| 243 |
+
tmp_path: Path,
|
| 244 |
+
capsys: pytest.CaptureFixture[str],
|
| 245 |
+
) -> None:
|
| 246 |
+
wiki = tmp_path / "wiki"
|
| 247 |
+
_write_active_pack_sets(wiki)
|
| 248 |
+
staged = compact_active_pack_sets(
|
| 249 |
+
wiki_path=wiki,
|
| 250 |
+
base_export_id="export-2",
|
| 251 |
+
staging_dir=tmp_path / "staged-compaction",
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
rc = pack_compaction.main([
|
| 255 |
+
"promote",
|
| 256 |
+
"--wiki-path",
|
| 257 |
+
str(wiki),
|
| 258 |
+
"--staged-graph-packs-dir",
|
| 259 |
+
str(staged.staged_graph_packs_dir),
|
| 260 |
+
"--staged-wiki-packs-dir",
|
| 261 |
+
str(staged.staged_wiki_packs_dir),
|
| 262 |
+
"--graph-backup-packs-dir",
|
| 263 |
+
str(tmp_path / "graph-packs.backup"),
|
| 264 |
+
"--wiki-backup-packs-dir",
|
| 265 |
+
str(tmp_path / "wiki-packs.backup"),
|
| 266 |
+
"--json",
|
| 267 |
+
])
|
| 268 |
+
|
| 269 |
+
assert rc == 0
|
| 270 |
+
payload = json.loads(capsys.readouterr().out)
|
| 271 |
+
assert payload["graph"]["promoted_pack_ids"] == ["base-export-2"]
|
| 272 |
+
assert payload["wiki"]["promoted_pack_ids"] == ["base-export-2"]
|
| 273 |
+
assert "skill:old" not in load_merged_pack_graph(wiki / "graphify-out" / "packs")
|
| 274 |
+
assert "entities/skills/old.md" not in load_merged_wiki_pages(wiki / "wiki-packs")
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def test_pack_compaction_cli_compact_promote_one_shot(
|
| 278 |
+
tmp_path: Path,
|
| 279 |
+
capsys: pytest.CaptureFixture[str],
|
| 280 |
+
) -> None:
|
| 281 |
+
wiki = tmp_path / "wiki"
|
| 282 |
+
_write_active_pack_sets(wiki)
|
| 283 |
+
staging_dir = tmp_path / "staged-one-shot"
|
| 284 |
+
store_path = tmp_path / "graph-store.sqlite3"
|
| 285 |
+
|
| 286 |
+
rc = pack_compaction.main([
|
| 287 |
+
"compact-promote",
|
| 288 |
+
"--wiki-path",
|
| 289 |
+
str(wiki),
|
| 290 |
+
"--base-export-id",
|
| 291 |
+
"export-2",
|
| 292 |
+
"--staging-dir",
|
| 293 |
+
str(staging_dir),
|
| 294 |
+
"--graph-backup-packs-dir",
|
| 295 |
+
str(tmp_path / "graph-packs.backup"),
|
| 296 |
+
"--wiki-backup-packs-dir",
|
| 297 |
+
str(tmp_path / "wiki-packs.backup"),
|
| 298 |
+
"--graph-store-db",
|
| 299 |
+
str(store_path),
|
| 300 |
+
"--json",
|
| 301 |
+
])
|
| 302 |
+
|
| 303 |
+
assert rc == 0
|
| 304 |
+
payload = json.loads(capsys.readouterr().out)
|
| 305 |
+
assert payload["compaction"]["base_export_id"] == "export-2"
|
| 306 |
+
assert payload["promotion"]["graph"]["promoted_pack_ids"] == ["base-export-2"]
|
| 307 |
+
assert payload["promotion"]["wiki"]["promoted_pack_ids"] == ["base-export-2"]
|
| 308 |
+
assert payload["promotion"]["graph_store"] == {"rebuilt": True, "nodes": 2, "edges": 1}
|
| 309 |
+
assert "skill:old" not in load_merged_pack_graph(wiki / "graphify-out" / "packs")
|
| 310 |
+
assert "entities/skills/old.md" not in load_merged_wiki_pages(wiki / "wiki-packs")
|
| 311 |
+
assert graph_store_is_fresh(store_path, wiki / "graphify-out") is True
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def test_pack_compaction_cli_validates_active_pack_sets(
|
| 315 |
+
tmp_path: Path,
|
| 316 |
+
capsys: pytest.CaptureFixture[str],
|
| 317 |
+
) -> None:
|
| 318 |
+
wiki = tmp_path / "wiki"
|
| 319 |
+
_write_active_pack_sets(wiki)
|
| 320 |
+
|
| 321 |
+
rc = pack_compaction.main([
|
| 322 |
+
"validate",
|
| 323 |
+
"--wiki-path",
|
| 324 |
+
str(wiki),
|
| 325 |
+
"--json",
|
| 326 |
+
])
|
| 327 |
+
|
| 328 |
+
assert rc == 0
|
| 329 |
+
payload = json.loads(capsys.readouterr().out)
|
| 330 |
+
assert payload["graph_nodes"] == 2
|
| 331 |
+
assert payload["graph_edges"] == 1
|
| 332 |
+
assert payload["wiki_pages"] == 2
|
| 333 |
+
assert payload["graph_pack_ids"] == ["base-export-1", "overlay-new"]
|
| 334 |
+
assert payload["base_export_id"] == "export-1"
|
| 335 |
+
assert payload["missing_wiki_pages"] == 0
|
| 336 |
+
assert payload["orphan_wiki_pages"] == 0
|
| 337 |
+
assert payload["stale_wiki_links"] == 0
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def test_pack_compaction_cli_validates_staged_pack_sets_with_manifest(
|
| 341 |
+
tmp_path: Path,
|
| 342 |
+
capsys: pytest.CaptureFixture[str],
|
| 343 |
+
) -> None:
|
| 344 |
+
wiki = tmp_path / "wiki"
|
| 345 |
+
_write_active_pack_sets(wiki)
|
| 346 |
+
staged = compact_active_pack_sets(
|
| 347 |
+
wiki_path=wiki,
|
| 348 |
+
base_export_id="export-2",
|
| 349 |
+
staging_dir=tmp_path / "staged-compaction",
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
rc = pack_compaction.main([
|
| 353 |
+
"validate",
|
| 354 |
+
"--staged-graph-packs-dir",
|
| 355 |
+
str(staged.staged_graph_packs_dir),
|
| 356 |
+
"--staged-wiki-packs-dir",
|
| 357 |
+
str(staged.staged_wiki_packs_dir),
|
| 358 |
+
"--require-compaction-manifest",
|
| 359 |
+
"--json",
|
| 360 |
+
])
|
| 361 |
+
|
| 362 |
+
assert rc == 0
|
| 363 |
+
payload = json.loads(capsys.readouterr().out)
|
| 364 |
+
assert payload["graph_nodes"] == 2
|
| 365 |
+
assert payload["graph_edges"] == 1
|
| 366 |
+
assert payload["wiki_pages"] == 2
|
| 367 |
+
assert payload["graph_pack_ids"] == ["base-export-2"]
|
| 368 |
+
assert payload["base_export_id"] == "export-2"
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def test_pack_compaction_validate_rejects_stale_entity_wikilinks(
|
| 372 |
+
tmp_path: Path,
|
| 373 |
+
capsys: pytest.CaptureFixture[str],
|
| 374 |
+
) -> None:
|
| 375 |
+
wiki = tmp_path / "wiki"
|
| 376 |
+
_write_active_pack_sets(wiki)
|
| 377 |
+
write_wiki_overlay_pack(
|
| 378 |
+
pack_dir=wiki / "wiki-packs" / "overlay-z-stale-link",
|
| 379 |
+
pack_id="overlay-z-stale-link",
|
| 380 |
+
base_export_id="export-1",
|
| 381 |
+
parent_export_id="export-1",
|
| 382 |
+
pages={"entities/skills/new.md": "# New\n\n[[entities/skills/missing]]\n"},
|
| 383 |
+
tombstones=[],
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
rc = pack_compaction.main([
|
| 387 |
+
"validate",
|
| 388 |
+
"--wiki-path",
|
| 389 |
+
str(wiki),
|
| 390 |
+
"--json",
|
| 391 |
+
])
|
| 392 |
+
|
| 393 |
+
assert rc == 1
|
| 394 |
+
assert "stale wiki links: 1" in capsys.readouterr().err
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def test_promote_staged_pack_sets_rejects_invalid_staged_wiki_before_graph_swap(
|
| 398 |
+
tmp_path: Path,
|
| 399 |
+
) -> None:
|
| 400 |
+
wiki = tmp_path / "wiki"
|
| 401 |
+
_write_active_pack_sets(wiki)
|
| 402 |
+
staged = compact_active_pack_sets(
|
| 403 |
+
wiki_path=wiki,
|
| 404 |
+
base_export_id="export-2",
|
| 405 |
+
staging_dir=tmp_path / "staged-compaction",
|
| 406 |
+
)
|
| 407 |
+
pages_path = staged.staged_wiki_packs_dir / "base-export-2" / "pages.jsonl"
|
| 408 |
+
pages_path.write_text('{"path":"entities/skills/new.md","text":"tampered","sha256":"bad"}\n')
|
| 409 |
+
|
| 410 |
+
with pytest.raises(PackCompactionError, match="checksum mismatch"):
|
| 411 |
+
promote_staged_pack_sets(
|
| 412 |
+
wiki_path=wiki,
|
| 413 |
+
staged_graph_packs_dir=staged.staged_graph_packs_dir,
|
| 414 |
+
staged_wiki_packs_dir=staged.staged_wiki_packs_dir,
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
assert [entry.manifest.pack_id for entry in discover_pack_manifests(wiki / "graphify-out" / "packs")] == [
|
| 418 |
+
"base-export-1",
|
| 419 |
+
"overlay-new",
|
| 420 |
+
]
|
| 421 |
+
assert [entry.manifest.pack_id for entry in discover_wiki_pack_manifests(wiki / "wiki-packs")] == [
|
| 422 |
+
"base-export-1",
|
| 423 |
+
"overlay-new",
|
| 424 |
+
]
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def test_promote_staged_pack_sets_rejects_graph_wiki_entity_mismatch(
|
| 428 |
+
tmp_path: Path,
|
| 429 |
+
) -> None:
|
| 430 |
+
wiki = tmp_path / "wiki"
|
| 431 |
+
_write_active_pack_sets(wiki)
|
| 432 |
+
staged = compact_active_pack_sets(
|
| 433 |
+
wiki_path=wiki,
|
| 434 |
+
base_export_id="export-2",
|
| 435 |
+
staging_dir=tmp_path / "staged-compaction",
|
| 436 |
+
)
|
| 437 |
+
staged_wiki_base = staged.staged_wiki_packs_dir / "base-export-2"
|
| 438 |
+
pages_path = staged_wiki_base / "pages.jsonl"
|
| 439 |
+
page_rows = [
|
| 440 |
+
json.loads(line)
|
| 441 |
+
for line in pages_path.read_text(encoding="utf-8").splitlines()
|
| 442 |
+
if line.strip()
|
| 443 |
+
]
|
| 444 |
+
page_rows = [
|
| 445 |
+
row
|
| 446 |
+
for row in page_rows
|
| 447 |
+
if row["path"] != "entities/skills/new.md"
|
| 448 |
+
]
|
| 449 |
+
pages_path.write_text(
|
| 450 |
+
"".join(json.dumps(row, sort_keys=True, separators=(",", ":")) + "\n" for row in page_rows),
|
| 451 |
+
encoding="utf-8",
|
| 452 |
+
)
|
| 453 |
+
wiki_manifest_path = staged_wiki_base / "wiki-pack-manifest.json"
|
| 454 |
+
wiki_manifest = json.loads(wiki_manifest_path.read_text(encoding="utf-8"))
|
| 455 |
+
wiki_manifest["page_count"] = len(page_rows)
|
| 456 |
+
wiki_manifest["checksums"]["pages.jsonl"] = _sha256_file(pages_path)
|
| 457 |
+
wiki_manifest_path.write_text(json.dumps(wiki_manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
| 458 |
+
compaction_manifest = json.loads(staged.manifest_path.read_text(encoding="utf-8"))
|
| 459 |
+
compaction_manifest["wiki"] = wiki_manifest
|
| 460 |
+
staged.manifest_path.write_text(
|
| 461 |
+
json.dumps(compaction_manifest, indent=2, sort_keys=True) + "\n",
|
| 462 |
+
encoding="utf-8",
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
with pytest.raises(PackCompactionError, match="missing wiki pages"):
|
| 466 |
+
promote_staged_pack_sets(
|
| 467 |
+
wiki_path=wiki,
|
| 468 |
+
staged_graph_packs_dir=staged.staged_graph_packs_dir,
|
| 469 |
+
staged_wiki_packs_dir=staged.staged_wiki_packs_dir,
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
assert [entry.manifest.pack_id for entry in discover_pack_manifests(wiki / "graphify-out" / "packs")] == [
|
| 473 |
+
"base-export-1",
|
| 474 |
+
"overlay-new",
|
| 475 |
+
]
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def test_promote_staged_pack_sets_rejects_missing_compaction_manifest(
|
| 479 |
+
tmp_path: Path,
|
| 480 |
+
) -> None:
|
| 481 |
+
wiki = tmp_path / "wiki"
|
| 482 |
+
_write_active_pack_sets(wiki)
|
| 483 |
+
staged = compact_active_pack_sets(
|
| 484 |
+
wiki_path=wiki,
|
| 485 |
+
base_export_id="export-2",
|
| 486 |
+
staging_dir=tmp_path / "staged-compaction",
|
| 487 |
+
)
|
| 488 |
+
staged.manifest_path.unlink()
|
| 489 |
+
|
| 490 |
+
with pytest.raises(PackCompactionError, match="pack-compaction-manifest.json"):
|
| 491 |
+
promote_staged_pack_sets(
|
| 492 |
+
wiki_path=wiki,
|
| 493 |
+
staged_graph_packs_dir=staged.staged_graph_packs_dir,
|
| 494 |
+
staged_wiki_packs_dir=staged.staged_wiki_packs_dir,
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
assert [entry.manifest.pack_id for entry in discover_pack_manifests(wiki / "graphify-out" / "packs")] == [
|
| 498 |
+
"base-export-1",
|
| 499 |
+
"overlay-new",
|
| 500 |
+
]
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def test_promote_staged_pack_sets_rejects_manifest_dir_mismatch(
|
| 504 |
+
tmp_path: Path,
|
| 505 |
+
) -> None:
|
| 506 |
+
wiki = tmp_path / "wiki"
|
| 507 |
+
_write_active_pack_sets(wiki)
|
| 508 |
+
staged = compact_active_pack_sets(
|
| 509 |
+
wiki_path=wiki,
|
| 510 |
+
base_export_id="export-2",
|
| 511 |
+
staging_dir=tmp_path / "staged-compaction",
|
| 512 |
+
)
|
| 513 |
+
manifest = json.loads(staged.manifest_path.read_text(encoding="utf-8"))
|
| 514 |
+
manifest["staged_wiki_packs_dir"] = str(tmp_path / "other-wiki-packs")
|
| 515 |
+
staged.manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
| 516 |
+
|
| 517 |
+
with pytest.raises(PackCompactionError, match="staged_wiki_packs_dir"):
|
| 518 |
+
promote_staged_pack_sets(
|
| 519 |
+
wiki_path=wiki,
|
| 520 |
+
staged_graph_packs_dir=staged.staged_graph_packs_dir,
|
| 521 |
+
staged_wiki_packs_dir=staged.staged_wiki_packs_dir,
|
| 522 |
+
)
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
def test_promote_staged_pack_sets_rejects_manifest_graph_section_drift(
|
| 526 |
+
tmp_path: Path,
|
| 527 |
+
) -> None:
|
| 528 |
+
wiki = tmp_path / "wiki"
|
| 529 |
+
_write_active_pack_sets(wiki)
|
| 530 |
+
staged = compact_active_pack_sets(
|
| 531 |
+
wiki_path=wiki,
|
| 532 |
+
base_export_id="export-2",
|
| 533 |
+
staging_dir=tmp_path / "staged-compaction",
|
| 534 |
+
)
|
| 535 |
+
manifest = json.loads(staged.manifest_path.read_text(encoding="utf-8"))
|
| 536 |
+
manifest["graph"]["edge_count"] = 999
|
| 537 |
+
staged.manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
| 538 |
+
|
| 539 |
+
with pytest.raises(PackCompactionError, match="graph manifest"):
|
| 540 |
+
promote_staged_pack_sets(
|
| 541 |
+
wiki_path=wiki,
|
| 542 |
+
staged_graph_packs_dir=staged.staged_graph_packs_dir,
|
| 543 |
+
staged_wiki_packs_dir=staged.staged_wiki_packs_dir,
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
def test_promote_staged_pack_sets_rejects_unrecorded_staged_wiki_overlay(
|
| 548 |
+
tmp_path: Path,
|
| 549 |
+
) -> None:
|
| 550 |
+
wiki = tmp_path / "wiki"
|
| 551 |
+
_write_active_pack_sets(wiki)
|
| 552 |
+
staged = compact_active_pack_sets(
|
| 553 |
+
wiki_path=wiki,
|
| 554 |
+
base_export_id="export-2",
|
| 555 |
+
staging_dir=tmp_path / "staged-compaction",
|
| 556 |
+
)
|
| 557 |
+
write_wiki_overlay_pack(
|
| 558 |
+
pack_dir=staged.staged_wiki_packs_dir / "overlay-extra",
|
| 559 |
+
pack_id="overlay-extra",
|
| 560 |
+
base_export_id="export-2",
|
| 561 |
+
parent_export_id="export-2",
|
| 562 |
+
pages={"entities/skills/extra.md": "# Extra\n"},
|
| 563 |
+
tombstones=[],
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
with pytest.raises(PackCompactionError, match="exactly one base pack"):
|
| 567 |
+
promote_staged_pack_sets(
|
| 568 |
+
wiki_path=wiki,
|
| 569 |
+
staged_graph_packs_dir=staged.staged_graph_packs_dir,
|
| 570 |
+
staged_wiki_packs_dir=staged.staged_wiki_packs_dir,
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def _write_active_pack_sets(wiki: Path) -> tuple[Path, Path]:
|
| 575 |
+
graph_packs = wiki / "graphify-out" / "packs"
|
| 576 |
+
wiki_packs = wiki / "wiki-packs"
|
| 577 |
+
graph = nx.Graph()
|
| 578 |
+
graph.add_node("skill:old", type="skill", label="old")
|
| 579 |
+
graph.add_node("skill:keep", type="skill", label="keep")
|
| 580 |
+
graph.add_edge("skill:old", "skill:keep", weight=0.2)
|
| 581 |
+
write_base_pack(
|
| 582 |
+
pack_dir=graph_packs / "base-export-1",
|
| 583 |
+
pack_id="base-export-1",
|
| 584 |
+
base_export_id="export-1",
|
| 585 |
+
config_hash="config-1",
|
| 586 |
+
model_id="model-1",
|
| 587 |
+
graph=graph,
|
| 588 |
+
)
|
| 589 |
+
write_overlay_pack(
|
| 590 |
+
pack_dir=graph_packs / "overlay-new",
|
| 591 |
+
pack_id="overlay-new",
|
| 592 |
+
base_export_id="export-1",
|
| 593 |
+
parent_export_id="export-1",
|
| 594 |
+
config_hash="config-1",
|
| 595 |
+
model_id="model-1",
|
| 596 |
+
nodes=[{"id": "skill:new", "type": "skill", "label": "new"}],
|
| 597 |
+
edges=[{"source": "skill:new", "target": "skill:keep", "weight": 0.9}],
|
| 598 |
+
tombstones=[{"node_id": "skill:old"}],
|
| 599 |
+
)
|
| 600 |
+
write_wiki_base_pack(
|
| 601 |
+
pack_dir=wiki_packs / "base-export-1",
|
| 602 |
+
pack_id="base-export-1",
|
| 603 |
+
base_export_id="export-1",
|
| 604 |
+
pages={
|
| 605 |
+
"entities/skills/old.md": "# Old\n",
|
| 606 |
+
"entities/skills/keep.md": "# Keep\n",
|
| 607 |
+
},
|
| 608 |
+
)
|
| 609 |
+
write_wiki_overlay_pack(
|
| 610 |
+
pack_dir=wiki_packs / "overlay-new",
|
| 611 |
+
pack_id="overlay-new",
|
| 612 |
+
base_export_id="export-1",
|
| 613 |
+
parent_export_id="export-1",
|
| 614 |
+
pages={"entities/skills/new.md": "# New\n"},
|
| 615 |
+
tombstones=["entities/skills/old.md"],
|
| 616 |
+
)
|
| 617 |
+
return graph_packs, wiki_packs
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
def _sha256_file(path: Path) -> str:
|
| 621 |
+
return hashlib.sha256(path.read_bytes()).hexdigest()
|
src/tests/test_pack_full_wiki_tar.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import io
|
| 4 |
+
import json
|
| 5 |
+
import tarfile
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from ctx.core.wiki.wiki_packs import load_merged_wiki_pages
|
| 9 |
+
from scripts.pack_full_wiki_tar import repack_full_wiki_tar
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _add_text(tf: tarfile.TarFile, name: str, text: str) -> None:
|
| 13 |
+
payload = text.encode("utf-8")
|
| 14 |
+
info = tarfile.TarInfo(name)
|
| 15 |
+
info.size = len(payload)
|
| 16 |
+
tf.addfile(info, io.BytesIO(payload))
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_repack_full_wiki_tar_moves_high_fanout_pages_into_wiki_pack(
|
| 20 |
+
tmp_path: Path,
|
| 21 |
+
) -> None:
|
| 22 |
+
source = tmp_path / "wiki-graph.tar.gz"
|
| 23 |
+
target = tmp_path / "wiki-graph-packed.tar.gz"
|
| 24 |
+
with tarfile.open(source, "w:gz") as tf:
|
| 25 |
+
_add_text(tf, "index.md", "# Wiki\n")
|
| 26 |
+
_add_text(tf, "entities/skills/current.md", "# Current Skill\n")
|
| 27 |
+
_add_text(tf, "entities/skills/empty.md", "")
|
| 28 |
+
_add_text(tf, "entities/agents/reviewer.md", "# Reviewer Agent\n")
|
| 29 |
+
_add_text(tf, "entities/mcp-servers/github.md", "# GitHub MCP\n")
|
| 30 |
+
_add_text(tf, "entities/harnesses/langgraph.md", "# LangGraph Harness\n")
|
| 31 |
+
_add_text(tf, "concepts/empty.md", "")
|
| 32 |
+
_add_text(
|
| 33 |
+
tf,
|
| 34 |
+
"graphify-out/graph-export-manifest.json",
|
| 35 |
+
json.dumps({"export_id": "test-export"}),
|
| 36 |
+
)
|
| 37 |
+
_add_text(tf, "graphify-out/graph-report.md", "# Graph Report\n")
|
| 38 |
+
_add_text(tf, "graphify-out/graph.json", json.dumps({"nodes": [], "edges": []}))
|
| 39 |
+
_add_text(tf, "external-catalogs/skills-sh/catalog.json", json.dumps({"skills": []}))
|
| 40 |
+
|
| 41 |
+
stats = repack_full_wiki_tar(source, target)
|
| 42 |
+
|
| 43 |
+
assert stats.removed_expanded_markdown_pages == 5
|
| 44 |
+
assert stats.packed_pages == 8
|
| 45 |
+
with tarfile.open(target, "r:gz") as tf:
|
| 46 |
+
names = {member.name for member in tf.getmembers()}
|
| 47 |
+
tf.extractall(tmp_path / "extracted")
|
| 48 |
+
|
| 49 |
+
assert "entities/skills/current.md" not in names
|
| 50 |
+
assert "entities/skills/empty.md" not in names
|
| 51 |
+
assert "entities/agents/reviewer.md" not in names
|
| 52 |
+
assert "entities/mcp-servers/github.md" not in names
|
| 53 |
+
assert "entities/harnesses/langgraph.md" in names
|
| 54 |
+
assert "concepts/empty.md" not in names
|
| 55 |
+
assert "graphify-out/graph-report.md" in names
|
| 56 |
+
assert "wiki-packs/base-test-export/wiki-pack-manifest.json" in names
|
| 57 |
+
assert "wiki-packs/base-test-export/pages.jsonl" in names
|
| 58 |
+
|
| 59 |
+
pages = load_merged_wiki_pages(tmp_path / "extracted" / "wiki-packs")
|
| 60 |
+
assert pages["entities/skills/current.md"] == "# Current Skill\n"
|
| 61 |
+
assert pages["entities/skills/empty.md"] == "<!-- empty markdown page -->\n"
|
| 62 |
+
assert pages["entities/agents/reviewer.md"] == "# Reviewer Agent\n"
|
| 63 |
+
assert pages["entities/mcp-servers/github.md"] == "# GitHub MCP\n"
|
| 64 |
+
assert pages["concepts/empty.md"] == "<!-- empty markdown page -->\n"
|
| 65 |
+
|
| 66 |
+
second_target = tmp_path / "wiki-graph-packed-again.tar.gz"
|
| 67 |
+
repack_full_wiki_tar(target, second_target)
|
| 68 |
+
with tarfile.open(second_target, "r:gz") as tf:
|
| 69 |
+
second_names = {member.name for member in tf.getmembers()}
|
| 70 |
+
tf.extractall(tmp_path / "extracted-again")
|
| 71 |
+
assert "graphify-out/graph-report.md" in second_names
|
| 72 |
+
repacked_pages = load_merged_wiki_pages(tmp_path / "extracted-again" / "wiki-packs")
|
| 73 |
+
assert repacked_pages["entities/skills/current.md"] == "# Current Skill\n"
|
| 74 |
+
assert repacked_pages["entities/agents/reviewer.md"] == "# Reviewer Agent\n"
|
| 75 |
+
assert repacked_pages["entities/mcp-servers/github.md"] == "# GitHub MCP\n"
|
src/tests/test_pack_validation.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import networkx as nx
|
| 4 |
+
|
| 5 |
+
from ctx.core.wiki.pack_validation import validate_graph_wiki_consistency
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_validate_graph_wiki_consistency_accepts_matching_entity_pages() -> None:
|
| 9 |
+
graph = nx.Graph()
|
| 10 |
+
graph.add_node("skill:python", type="skill")
|
| 11 |
+
graph.add_node("agent:reviewer", type="agent")
|
| 12 |
+
graph.add_node("mcp-server:github", type="mcp-server")
|
| 13 |
+
graph.add_node("harness:mirage", type="harness")
|
| 14 |
+
pages = {
|
| 15 |
+
"entities/skills/python.md": "# Python\n",
|
| 16 |
+
"entities/agents/reviewer.md": "# Reviewer\n",
|
| 17 |
+
"entities/mcp-servers/g/github.md": "# GitHub\n",
|
| 18 |
+
"entities/harnesses/mirage.md": "# Mirage\n",
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
report = validate_graph_wiki_consistency(graph, pages)
|
| 22 |
+
|
| 23 |
+
assert report.ok is True
|
| 24 |
+
assert report.missing_wiki_pages == []
|
| 25 |
+
assert report.orphan_wiki_pages == []
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_validate_graph_wiki_consistency_reports_missing_wiki_pages() -> None:
|
| 29 |
+
graph = nx.Graph()
|
| 30 |
+
graph.add_node("skill:python", type="skill")
|
| 31 |
+
graph.add_node("mcp-server:github", type="mcp-server")
|
| 32 |
+
|
| 33 |
+
report = validate_graph_wiki_consistency(graph, {"entities/skills/python.md": "# Python\n"})
|
| 34 |
+
|
| 35 |
+
assert report.ok is False
|
| 36 |
+
assert report.missing_wiki_pages == [
|
| 37 |
+
{
|
| 38 |
+
"node_id": "mcp-server:github",
|
| 39 |
+
"expected_paths": [
|
| 40 |
+
"entities/mcp-servers/g/github.md",
|
| 41 |
+
"entities/mcp-servers/github.md",
|
| 42 |
+
],
|
| 43 |
+
},
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def test_validate_graph_wiki_consistency_reports_orphan_wiki_pages() -> None:
|
| 48 |
+
graph = nx.Graph()
|
| 49 |
+
graph.add_node("skill:python", type="skill")
|
| 50 |
+
pages = {
|
| 51 |
+
"entities/skills/python.md": "# Python\n",
|
| 52 |
+
"entities/harnesses/mirage.md": "# Mirage\n",
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
report = validate_graph_wiki_consistency(graph, pages)
|
| 56 |
+
|
| 57 |
+
assert report.ok is False
|
| 58 |
+
assert report.orphan_wiki_pages == [
|
| 59 |
+
{
|
| 60 |
+
"path": "entities/harnesses/mirage.md",
|
| 61 |
+
"expected_node_id": "harness:mirage",
|
| 62 |
+
},
|
| 63 |
+
]
|
src/tests/test_package_scaffold.py
CHANGED
|
@@ -36,6 +36,8 @@ _EXPECTED_SUBPACKAGES: tuple[str, ...] = (
|
|
| 36 |
"ctx.adapters.generic.providers",
|
| 37 |
"ctx.adapters.generic.tools",
|
| 38 |
"ctx.cli",
|
|
|
|
|
|
|
| 39 |
"ctx.mcp_server",
|
| 40 |
"ctx.utils",
|
| 41 |
)
|
|
@@ -45,8 +47,10 @@ _EXPECTED_CONSOLE_SCRIPTS: tuple[str, ...] = (
|
|
| 45 |
"ctx-agent-add",
|
| 46 |
"ctx-agent-install",
|
| 47 |
"ctx-agent-mirror",
|
|
|
|
| 48 |
"ctx-bundle-suggest",
|
| 49 |
"ctx-dedup-check",
|
|
|
|
| 50 |
"ctx-harness-add",
|
| 51 |
"ctx-harness-install",
|
| 52 |
"ctx-incremental-attach",
|
|
@@ -64,6 +68,7 @@ _EXPECTED_CONSOLE_SCRIPTS: tuple[str, ...] = (
|
|
| 64 |
"ctx-mcp-server",
|
| 65 |
"ctx-mcp-uninstall",
|
| 66 |
"ctx-monitor",
|
|
|
|
| 67 |
"ctx-recommend",
|
| 68 |
"ctx-scan-repo",
|
| 69 |
"ctx-skill-add",
|
|
@@ -71,8 +76,14 @@ _EXPECTED_CONSOLE_SCRIPTS: tuple[str, ...] = (
|
|
| 71 |
"ctx-skill-install",
|
| 72 |
"ctx-skill-mirror",
|
| 73 |
"ctx-skill-quality",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
"ctx-source-registry",
|
| 75 |
"ctx-tag-backfill",
|
|
|
|
|
|
|
| 76 |
"ctx-toolbox",
|
| 77 |
"ctx-wiki-graphify",
|
| 78 |
"ctx-wiki-worker",
|
|
|
|
| 36 |
"ctx.adapters.generic.providers",
|
| 37 |
"ctx.adapters.generic.tools",
|
| 38 |
"ctx.cli",
|
| 39 |
+
"ctx.monitor",
|
| 40 |
+
"ctx.monitor.pages",
|
| 41 |
"ctx.mcp_server",
|
| 42 |
"ctx.utils",
|
| 43 |
)
|
|
|
|
| 47 |
"ctx-agent-add",
|
| 48 |
"ctx-agent-install",
|
| 49 |
"ctx-agent-mirror",
|
| 50 |
+
"ctx-agent-unload",
|
| 51 |
"ctx-bundle-suggest",
|
| 52 |
"ctx-dedup-check",
|
| 53 |
+
"ctx-graph-store",
|
| 54 |
"ctx-harness-add",
|
| 55 |
"ctx-harness-install",
|
| 56 |
"ctx-incremental-attach",
|
|
|
|
| 68 |
"ctx-mcp-server",
|
| 69 |
"ctx-mcp-uninstall",
|
| 70 |
"ctx-monitor",
|
| 71 |
+
"ctx-pack-compact",
|
| 72 |
"ctx-recommend",
|
| 73 |
"ctx-scan-repo",
|
| 74 |
"ctx-skill-add",
|
|
|
|
| 76 |
"ctx-skill-install",
|
| 77 |
"ctx-skill-mirror",
|
| 78 |
"ctx-skill-quality",
|
| 79 |
+
"ctx-skill-unload",
|
| 80 |
+
"ctx-skillspector-audit",
|
| 81 |
+
"ctx-skillspector-remediation",
|
| 82 |
+
"ctx-skillspector-scan",
|
| 83 |
"ctx-source-registry",
|
| 84 |
"ctx-tag-backfill",
|
| 85 |
+
"ctx-telemetry-export",
|
| 86 |
+
"ctx-telemetry-retention",
|
| 87 |
"ctx-toolbox",
|
| 88 |
"ctx-wiki-graphify",
|
| 89 |
"ctx-wiki-worker",
|